3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class is for activity functions
40 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
43 * static field for all the activity information that we can potentially export
48 static $_exportableFields = NULL;
51 * static field for all the activity information that we can potentially import
56 static $_importableFields = NULL;
59 * Check if there is absolute minimum of data to add the object
61 * @param array $params (reference ) an assoc array of name/value pairs
66 public static function dataExists(&$params) {
67 if (!empty($params['source_contact_id']) ||
!empty($params['id'])) {
74 * Takes a bunch of params that are needed to match certain criteria and
75 * retrieves the relevant objects. Typically the valid params are only
76 * contact_id. We'll tweak this function to be more full featured over a period
77 * of time. This is the inverse function of create. It also stores all the retrieved
78 * values in the default array
80 * @param array $params (reference ) an assoc array of name/value pairs
81 * @param array $defaults (reference ) an assoc array to hold the flattened values
82 * @param string $activityType activity type
84 * @return object CRM_Core_BAO_Meeting object
87 public static function retrieve(&$params, &$defaults) {
88 $activity = new CRM_Activity_DAO_Activity();
89 $activity->copyValues($params);
91 if ($activity->find(TRUE)) {
92 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
93 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
94 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
95 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
97 // TODO: at some stage we'll have to deal
98 // TODO: with multiple values for assignees and targets, but
99 // TODO: for now, let's just fetch first row
100 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
101 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
102 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
103 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
104 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
105 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
106 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
107 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
109 elseif (CRM_Core_Permission
::check('access CiviMail') ||
110 (CRM_Mailing_Info
::workflowEnabled() &&
111 CRM_Core_Permission
::check('create mailings')
114 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
115 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
119 $defaults['target_contact_value'] = ts('(recipients)');
122 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
123 $defaults['source_contact_id'] = $sourceContactId;
125 if ($sourceContactId &&
126 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
131 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
138 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
140 CRM_Core_DAO
::storeValues($activity, $defaults);
148 * Function to delete the activity
150 * @param array $params associated array
156 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
158 if (!empty($params['id']) && !is_array($params['id'])) {
159 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
162 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
165 $transaction = new CRM_Core_Transaction();
166 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
167 $sourceRecordIds = implode(',', $params['source_record_id']);
170 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
175 if (!isset($params['id'])) {
176 if (is_array($params['activity_type_id'])) {
177 $activityTypes = implode(',', $params['activity_type_id']);
180 $activityTypes = $params['activity_type_id'];
183 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
184 $dao = CRM_Core_DAO
::executeQuery($query);
187 $activity = new CRM_Activity_DAO_Activity();
188 $activity->copyValues($params);
189 $result = $activity->delete();
192 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
194 // CRM-13994 delete activity entity_tag
195 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
196 $dao = CRM_Core_DAO
::executeQuery($query);
200 $activity = new CRM_Activity_DAO_Activity();
201 $activity->copyValues($params);
203 $activity->is_deleted
= 1;
204 $result = $activity->save();
206 // CRM-4525 log activity delete
207 $logMsg = 'Case Activity deleted for';
210 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
211 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
212 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
213 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
214 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
215 if ($sourceContactId) {
216 $msgs[] = " source={$sourceContactId}";
219 //get target contacts.
220 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
221 if (!empty($targetContactIds)) {
222 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
224 //get assignee contacts.
225 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
226 if (!empty($assigneeContactIds)) {
227 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
230 $logMsg .= implode(', ', $msgs);
232 self
::logActivityAction($activity, $logMsg);
235 // delete the recently created Activity
237 $activityRecent = array(
238 'id' => $activity->id
,
239 'type' => 'Activity',
241 CRM_Utils_Recent
::del($activityRecent);
244 $transaction->commit();
245 if (isset($activity)) {
247 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
248 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
255 * Delete activity assignment record
257 * @param int $id activity id
262 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
263 $activityContact = new CRM_Activity_BAO_ActivityContact();
264 $activityContact->activity_id
= $activityId;
266 $activityContact->record_type_id
= $recordTypeID;
268 $activityContact->delete();
272 * Function to process the activities
274 * @param object $form form object
275 * @param array $params associated array of the submitted values
276 * @param array $ids array of ids
277 * @param string $activityType activity Type
278 * @param boolean $record true if it is Record Activity
283 public static function create(&$params) {
284 // check required params
285 if (!self
::dataExists($params)) {
286 throw new CRM_Core_Exception('Not enough data to create activity object');
289 $activity = new CRM_Activity_DAO_Activity();
291 if (isset($params['id']) && empty($params['id'])) {
292 unset($params['id']);
295 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
296 if (isset($params['activity_date_time']) &&
297 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
299 $params['status_id'] = 2;
302 $params['status_id'] = 1;
306 //set priority to Normal for Auto-populated activities (for Cases)
307 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
308 // if not set and not 0
309 !CRM_Utils_Array
::value('id', $params)
311 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
312 $params['priority_id'] = array_search('Normal', $priority);
315 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
316 $params['target_contact_id'] = array_unique($params['target_contact_id']);
318 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
319 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
323 if (!empty($params['id'])) {
324 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
327 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
330 $activity->copyValues($params);
331 if (isset($params['case_id'])) {
332 // CRM-8708, preserve case ID even though it's not part of the SQL model
333 $activity->case_id
= $params['case_id'];
335 elseif (is_numeric($activity->id
)) {
336 // CRM-8708, preserve case ID even though it's not part of the SQL model
337 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
341 $transaction = new CRM_Core_Transaction();
343 $result = $activity->save();
345 if (is_a($result, 'CRM_Core_Error')) {
346 $transaction->rollback();
350 $activityId = $activity->id
;
351 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
352 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
353 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
354 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
356 if (isset($params['source_contact_id'])) {
358 'activity_id' => $activityId,
359 'contact_id' => $params['source_contact_id'],
360 'record_type_id' => $sourceID
362 self
::deleteActivityContact($activityId, $sourceID);
363 CRM_Activity_BAO_ActivityContact
::create($acParams);
366 // check and attach and files as needed
367 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
369 // attempt to save activity assignment
370 $resultAssignment = NULL;
371 if (!empty($params['assignee_contact_id'])) {
373 $assignmentParams = array('activity_id' => $activityId);
375 if (is_array($params['assignee_contact_id'])) {
376 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
377 // first delete existing assignments if any
378 self
::deleteActivityContact($activityId, $assigneeID);
382 foreach ($params['assignee_contact_id'] as $acID) {
384 $values[] = "( $activityId, $acID, $assigneeID )";
387 while (!empty($values)) {
388 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
389 $str = implode(',', $input);
390 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
391 CRM_Core_DAO
::executeQuery($sql);
395 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
396 $assignmentParams['record_type_id'] = $assigneeID;
397 if (!empty($params['id'])) {
398 $assignment = new CRM_Activity_BAO_ActivityContact();
399 $assignment->activity_id
= $activityId;
400 $assignment->record_type_id
= $assigneeID;
401 $assignment->find(TRUE);
403 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
404 $assignmentParams['id'] = $assignment->id
;
405 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
409 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
414 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
415 self
::deleteActivityContact($activityId, $assigneeID);
419 if (is_a($resultAssignment, 'CRM_Core_Error')) {
420 $transaction->rollback();
421 return $resultAssignment;
424 // attempt to save activity targets
425 $resultTarget = NULL;
426 if (!empty($params['target_contact_id'])) {
428 $targetParams = array('activity_id' => $activityId);
429 $resultTarget = array();
430 if (is_array($params['target_contact_id'])) {
431 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
432 // first delete existing targets if any
433 self
::deleteActivityContact($activityId, $targetID );
437 foreach ($params['target_contact_id'] as $tid) {
439 $values[] = "( $activityId, $tid, $targetID )";
443 while (!empty($values)) {
444 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
445 $str = implode(',', $input);
446 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
447 CRM_Core_DAO
::executeQuery($sql);
451 $targetParams['contact_id'] = $params['target_contact_id'];
452 $targetParams['record_type_id'] = $targetID;
453 if (!empty($params['id'])) {
454 $target = new CRM_Activity_BAO_ActivityContact();
455 $target->activity_id
= $activityId;
456 $target->record_type_id
= $targetID;
459 if ($target->contact_id
!= $params['target_contact_id']) {
460 $targetParams['id'] = $target->id
;
461 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
465 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
470 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
471 self
::deleteActivityContact($activityId, $targetID );
475 // write to changelog before transaction is committed/rolled
476 // back (and prepare status to display)
477 if (!empty($params['id'])) {
478 $logMsg = "Activity (id: {$result->id} ) updated with ";
481 $logMsg = "Activity created for ";
485 if (isset($params['source_contact_id'])) {
486 $msgs[] = "source={$params['source_contact_id']}";
489 if (!empty($params['target_contact_id'])) {
490 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
491 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
492 // take only first target
493 // will be used for recently viewed display
494 $t = array_slice($params['target_contact_id'], 0, 1);
495 $recentContactId = $t[0];
497 //is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
498 // as it may always be an array
499 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
500 $msgs[] = "target={$params['target_contact_id']}";
501 // will be used for recently viewed display
502 $recentContactId = $params['target_contact_id'];
506 // at worst, take source for recently viewed display
507 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
510 if (isset($params['assignee_contact_id'])) {
511 if (is_array($params['assignee_contact_id'])) {
512 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
515 $msgs[] = "assignee={$params['assignee_contact_id']}";
518 $logMsg .= implode(', ', $msgs);
520 self
::logActivityAction($result, $logMsg);
522 if (!empty($params['custom']) &&
523 is_array($params['custom'])
525 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
528 $transaction->commit();
529 if (empty($params['skipRecentView'])) {
530 $recentOther = array();
531 if (!empty($params['case_id'])) {
532 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
533 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
534 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
538 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home";
539 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
540 $url = CRM_Utils_System
::url('civicrm/activity', $q);
541 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
542 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
543 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
547 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
548 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
552 if (CRM_Core_Permission
::check("delete activities")) {
553 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
554 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
559 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
560 if (CRM_Core_Permission
::check('delete activities')) {
561 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
562 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
568 if (!isset($activity->parent_id
)) {
569 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
570 // add the recently created Activity
571 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
572 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
575 if (isset($activitySubject)) {
576 $title = $activitySubject . ' - ';
579 $title = $title . $recentContactDisplay;
580 if (!empty($activityTypes[$activity->activity_type_id
])) {
581 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
584 CRM_Utils_Recent
::add($title,
589 $recentContactDisplay,
595 // reset the group contact cache since smart groups might be affected due to this
596 CRM_Contact_BAO_GroupContactCache
::remove();
598 if (!empty($params['id'])) {
599 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
602 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
605 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
607 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
608 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
610 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
612 'activity_id' => $activity->id
,
613 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
615 if ($caseParams['case_id']) {
616 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
619 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
626 public static function logActivityAction($activity, $logMessage = NULL) {
627 $session = CRM_Core_Session
::singleton();
628 $id = $session->get('userID');
630 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
631 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
632 $id = self
::getActivityContact($activity->id
. $sourceID);
635 'entity_table' => 'civicrm_activity',
636 'entity_id' => $activity->id
,
637 'modified_id' => $id,
638 'modified_date' => date('YmdHis'),
639 'data' => $logMessage,
641 CRM_Core_BAO_Log
::add($logParams);
646 * function to get the list Activities
648 * @param array $input array of parameters
650 * - contact_id int contact_id whose activities we want to retrieve
651 * - offset int which row to start from ?
652 * - rowCount int how many rows to fetch
653 * - sort object|array object or array describing sort order for sql query.
654 * - admin boolean if contact is admin
655 * - caseId int case ID
656 * - context string page on which selector is build
657 * - activity_type_id int|string the activitiy types we want to restrict by
659 * @return array (reference) $values the relevant data object values of open activities
664 static function &getActivities($input) {
665 //step 1: Get the basic activity data
666 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
672 $config = CRM_Core_Config
::singleton();
674 $randomNum = md5(uniqid());
675 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
677 $tableFields = array(
678 'activity_id' => 'int unsigned',
679 'activity_date_time' => 'datetime',
680 'source_record_id' => 'int unsigned',
681 'status_id' => 'int unsigned',
682 'subject' => 'varchar(255)',
683 'source_contact_name' => 'varchar(255)',
684 'activity_type_id' => 'int unsigned',
685 'activity_type' => 'varchar(128)',
686 'case_id' => 'int unsigned',
687 'case_subject' => 'varchar(255)',
688 'campaign_id' => 'int unsigned',
691 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
692 $insertValueSQL = array();
693 // The activityTempTable contains the sorted rows
694 // so in order to maintain the sort order as-is we add an auto_increment
695 // field; we can sort by this later to ensure the sort order stays correct.
696 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
697 foreach ($tableFields as $name => $desc) {
698 $sql .= "$name $desc,\n";
699 $insertValueSQL[] = $name;
702 // add unique key on activity_id just to be sure
703 // this cannot be primary key because we need that for the auto_increment
704 // fixed_sort_order field
706 UNIQUE KEY ( activity_id )
707 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
710 CRM_Core_DAO
::executeQuery($sql);
712 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
714 $order = $limit = $groupBy = '';
715 $groupBy = " GROUP BY tbl.activity_id ";
717 if (!empty($input['sort'])) {
718 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
719 $orderBy = $input['sort']->orderBy();
720 if (!empty($orderBy)) {
721 $order = " ORDER BY $orderBy";
724 elseif (trim($input['sort'])) {
725 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
726 $order = " ORDER BY $sort ";
731 // context = 'activity' in Activities tab.
732 $order = (CRM_Utils_Array
::value('context', $input) == 'activity') ?
" ORDER BY tbl.activity_date_time desc " : " ORDER BY tbl.status_id asc, tbl.activity_date_time asc ";
735 if (!empty($input['rowCount']) &&
736 $input['rowCount'] > 0
738 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
741 $input['count'] = FALSE;
743 // skip bulk activities in activity tab
744 $input['activity_type_exclude_id'][$bulkActivityTypeID] = $bulkActivityTypeID;
745 list($sqlClause, $params) = self
::getActivitySQLClause($input);
747 $query = "{$insertSQL}
748 SELECT DISTINCT tbl.* from ( {$sqlClause} )
751 //filter case activities - CRM-5761
752 $components = self
::activityComponents();
753 if (!in_array('CiviCase', $components)) {
755 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
756 WHERE civicrm_case_activity.id IS NULL";
759 $query = $query . $groupBy . $order . $limit;
761 $dao = CRM_Core_DAO
::executeQuery($query, $params);
763 // step 2: Get target and assignee contacts for above activities
764 // create temp table for target contacts
765 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
766 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
767 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
768 contact_name varchar(255), is_deleted int unsigned, INDEX index_activity_id( activity_id ) )
769 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
771 CRM_Core_DAO
::executeQuery($query);
773 // note that we ignore bulk email for targets, since we don't show it in selector
775 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
776 SELECT ac.activity_id,
781 FROM {$activityTempTable}
782 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
783 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
784 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
786 CRM_Core_DAO
::executeQuery($query);
788 // step 3: Combine all temp tables to get final query for activity selector
789 // sort by the original sort order, stored in fixed_sort_order
791 SELECT {$activityTempTable}.*,
792 {$activityContactTempTable}.contact_id,
793 {$activityContactTempTable}.record_type_id,
794 {$activityContactTempTable}.contact_name,
795 {$activityContactTempTable}.is_deleted
796 FROM {$activityTempTable}
797 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
798 ORDER BY fixed_sort_order
802 $dao = CRM_Core_DAO
::executeQuery($query);
804 //CRM-3553, need to check user has access to target groups.
805 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
807 (CRM_Core_Permission
::check('access CiviMail')) ||
808 (CRM_Mailing_Info
::workflowEnabled() &&
809 CRM_Core_Permission
::check('create mailings'))
813 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
816 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
817 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
818 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
819 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
822 while ($dao->fetch()) {
823 $activityID = $dao->activity_id
;
824 $values[$activityID]['activity_id'] = $dao->activity_id
;
825 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
826 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
827 $values[$activityID]['activity_type'] = $dao->activity_type
;
828 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
829 $values[$activityID]['status_id'] = $dao->status_id
;
830 $values[$activityID]['subject'] = $dao->subject
;
831 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
833 if ($dao->campaign_id
) {
834 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
837 if (empty($values[$activityID]['assignee_contact_name'])) {
838 $values[$activityID]['assignee_contact_name'] = array();
841 if (empty($values[$activityID]['target_contact_name'])) {
842 $values[$activityID]['target_contact_name'] = array();
845 // if deleted, wrap in <del>
846 if ( $dao->is_deleted
) {
847 $dao->contact_name
= "<del>{$dao->contact_name}</dao>";
850 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
851 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
852 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
855 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
856 // build array of target / assignee names
857 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
858 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
860 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
861 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
864 // case related fields
865 $values[$activityID]['case_id'] = $dao->case_id
;
866 $values[$activityID]['case_subject'] = $dao->case_subject
;
869 $values[$activityID]['recipients'] = ts('(recipients)');
870 $values[$activityID]['mailingId'] = false;
873 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
875 $values[$activityID]['mailingId'] = true;
884 * Get the component id and name those are enabled and logged in
885 * user has permission. To decide whether we are going to include
886 * component related activities w/ core activity retrieve process.
888 * return an array of component id and name.
891 static function activityComponents() {
892 $components = array();
893 $compInfo = CRM_Core_Component
::getEnabledComponents();
894 foreach ($compInfo as $compObj) {
895 if (!empty($compObj->info
['showActivitiesInCore'])) {
896 if ($compObj->info
['name'] == 'CiviCampaign') {
897 $componentPermission = "administer {$compObj->name}";
900 $componentPermission = "access {$compObj->name}";
902 if ($compObj->info
['name'] == 'CiviCase') {
903 if (CRM_Case_BAO_Case
::accessCiviCase()) {
904 $components[$compObj->componentID
] = $compObj->info
['name'];
907 elseif (CRM_Core_Permission
::check($componentPermission)) {
908 $components[$compObj->componentID
] = $compObj->info
['name'];
917 * function to get the activity Count
919 * @param array $input array of parameters
921 * - contact_id int contact_id whose activities we want to retrieve
922 * - admin boolean if contact is admin
923 * - caseId int case ID
924 * - context string page on which selector is build
925 * - activity_type_id int|string the activity types we want to restrict by
927 * @return int count of activities
932 static function &getActivitiesCount($input) {
933 // skip bulk activities in activity tab
934 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
939 $input['activity_type_exclude_id'][$bulkActivityTypeID] = $bulkActivityTypeID;
941 $input['count'] = TRUE;
942 list($sqlClause, $params) = self
::getActivitySQLClause($input);
944 //filter case activities - CRM-5761
945 $components = self
::activityComponents();
946 if (!in_array('CiviCase', $components)) {
948 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
949 FROM ( {$sqlClause} ) as tbl
950 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
951 WHERE civicrm_case_activity.id IS NULL";
954 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
957 return CRM_Core_DAO
::singleValueQuery($query, $params);
961 * function to get the activity sql clause to pick activities
963 * @param array $input array of parameters
965 * - contact_id int contact_id whose activities we want to retrieve
966 * - admin boolean if contact is admin
967 * - caseId int case ID
968 * - context string page on which selector is build
969 * - count boolean are we interested in the count clause only?
970 * - activity_type_id int|string the activity types we want to restrict by
972 * @return int count of activities
977 static function getActivitySQLClause($input) {
979 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
981 $config = CRM_Core_Config
::singleton();
982 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
983 $sourceWhere = ' ac.contact_id = %1 ';
984 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
986 $params = array(1 => array($input['contact_id'], 'Integer'));
989 $commonClauses = array(
990 "civicrm_option_group.name = 'activity_type'",
991 "civicrm_activity.is_deleted = 0",
992 "civicrm_activity.is_current_revision = 1",
993 "civicrm_activity.is_test= 0",
996 if ($input['context'] != 'activity') {
997 $commonClauses[] = "civicrm_activity.status_id = 1";
1000 //Filter on component IDs.
1001 $components = self
::activityComponents();
1002 if (!empty($components)) {
1003 $componentsIn = implode(',', array_keys($components));
1004 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1007 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1010 // activity type ID clause
1011 if (!empty($input['activity_type_id'])) {
1012 if (is_array($input['activity_type_id'])) {
1013 foreach ($input['activity_type_id'] as $idx => $value) {
1014 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1016 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1019 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1020 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1024 // exclude by activity type clause
1025 if (!empty($input['activity_type_exclude_id'])) {
1026 if (is_array($input['activity_type_exclude_id'])) {
1027 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1028 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1030 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1033 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1034 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1038 $commonClause = implode(' AND ', $commonClauses);
1040 $includeCaseActivities = FALSE;
1041 if (in_array('CiviCase', $components)) {
1042 $includeCaseActivities = TRUE;
1046 // build main activity table select clause
1049 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1050 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1052 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1053 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1056 if (!$input['count']) {
1058 civicrm_activity.activity_date_time,
1059 civicrm_activity.source_record_id,
1060 civicrm_activity.status_id,
1061 civicrm_activity.subject,
1062 contact.sort_name as source_contact_name,
1063 civicrm_option_value.value as activity_type_id,
1064 civicrm_option_value.label as activity_type,
1065 null as case_id, null as case_subject,
1066 civicrm_activity.campaign_id as campaign_id
1070 LEFT JOIN civicrm_activity_contact src ON (src.activity_id = ac.activity_id AND src.record_type_id = {$sourceID} AND src.contact_id = contact.id)
1075 SELECT civicrm_activity.id as activity_id
1077 from civicrm_activity
1078 left join civicrm_option_value on
1079 civicrm_activity.activity_type_id = civicrm_option_value.value
1080 left join civicrm_option_group on
1081 civicrm_option_group.id = civicrm_option_value.option_group_id
1088 // Build case clause
1089 // or else exclude Inbound Emails that have been filed on a case.
1092 if ($includeCaseActivities) {
1094 if (!$input['count']) {
1096 civicrm_activity.activity_date_time,
1097 civicrm_activity.source_record_id,
1098 civicrm_activity.status_id,
1099 civicrm_activity.subject,
1100 contact.sort_name as source_contact_name,
1101 civicrm_option_value.value as activity_type_id,
1102 civicrm_option_value.label as activity_type,
1103 null as case_id, null as case_subject,
1104 civicrm_activity.campaign_id as campaign_id';
1110 SELECT civicrm_activity.id as activity_id
1112 from civicrm_activity
1113 inner join civicrm_case_activity on
1114 civicrm_case_activity.activity_id = civicrm_activity.id
1115 inner join civicrm_case on
1116 civicrm_case_activity.case_id = civicrm_case.id
1117 inner join civicrm_case_contact on
1118 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1119 left join civicrm_option_value on
1120 civicrm_activity.activity_type_id = civicrm_option_value.value
1121 left join civicrm_option_group on
1122 civicrm_option_group.id = civicrm_option_value.option_group_id
1127 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1128 ( civicrm_option_value.name <> 'Inbound Email' AND
1129 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1135 $returnClause = " {$sourceClause} {$caseClause} ";
1137 return array($returnClause, $params);
1141 * send the message to all the contacts and also insert a
1142 * contact activity in each contacts record
1144 * @param array $contactDetails the array of contact details to send the email
1145 * @param string $subject the subject of the message
1146 * @param string $message the message contents
1147 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1148 * @param int $userID use this userID if set
1149 * @param string $from
1150 * @param array $attachments the array of attachments if any
1151 * @param string $cc cc recipient
1152 * @param string $bcc bcc recipient
1153 * @param array $contactIds contact ids
1154 * @param string $additionalDetails the additional information of CC and BCC appended to the activity Details
1156 * @return array ( sent, activityId) if any email is sent and activityId
1160 static function sendEmail(
1168 $attachments = NULL,
1171 $contactIds, // FIXME a param with no default shouldn't be last
1172 $additionalDetails = NULL
1174 // get the contact details of logged in contact, which we set as from email
1175 if ($userID == NULL) {
1176 $session = CRM_Core_Session
::singleton();
1177 $userID = $session->get('userID');
1180 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1182 return array(count($contactDetails), 0, count($contactDetails));
1184 if (!trim($fromDisplayName)) {
1185 $fromDisplayName = $fromEmail;
1189 // token replacement of addressee/email/postal greetings
1190 // get the tokens added in subject and message
1191 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1192 $messageToken = CRM_Utils_Token
::getTokens($text);
1193 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1194 $allTokens = array_merge($messageToken, $subjectToken);
1197 $from = "$fromDisplayName <$fromEmail>";
1200 //create the meta level record first ( email activity )
1201 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1206 // CRM-6265: save both text and HTML parts in details (if present)
1207 if ($html and $text) {
1208 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1211 $details = $html ?
$html : $text;
1212 $details .= $additionalDetails;
1215 $activityParams = array(
1216 'source_contact_id' => $userID,
1217 'activity_type_id' => $activityTypeID,
1218 'activity_date_time' => date('YmdHis'),
1219 'subject' => $subject,
1220 'details' => $details,
1221 // FIXME: check for name Completed and get ID from that lookup
1225 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1226 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1228 // add the attachments to activity params here
1230 // first process them
1231 $activityParams = array_merge($activityParams,
1236 $activity = self
::create($activityParams);
1238 // get the set of attachments from where they are stored
1239 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1242 $returnProperties = array();
1243 if (isset($messageToken['contact'])) {
1244 foreach ($messageToken['contact'] as $key => $value) {
1245 $returnProperties[$value] = 1;
1249 if (isset($subjectToken['contact'])) {
1250 foreach ($subjectToken['contact'] as $key => $value) {
1251 if (!isset($returnProperties[$value])) {
1252 $returnProperties[$value] = 1;
1258 // get token details for contacts, call only if tokens are used
1260 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1261 list($details) = CRM_Utils_Token
::getTokenDetails(
1266 'CRM_Activity_BAO_Activity'
1272 CRM_Utils_Hook
::tokens($tokens);
1273 $categories = array_keys($tokens);
1275 $escapeSmarty = FALSE;
1276 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1277 $smarty = CRM_Core_Smarty
::singleton();
1278 $escapeSmarty = TRUE;
1281 $sent = $notSent = array();
1282 foreach ($contactDetails as $values) {
1283 $contactId = $values['contact_id'];
1284 $emailAddress = $values['email'];
1286 if (!empty($details) && is_array($details["{$contactId}"])) {
1287 // unset email from details since it always returns primary email address
1288 unset($details["{$contactId}"]['email']);
1289 unset($details["{$contactId}"]['email_id']);
1290 $values = array_merge($values, $details["{$contactId}"]);
1293 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1294 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1297 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1298 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1299 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1305 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1306 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1307 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1313 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1314 // also add the contact tokens to the template
1315 $smarty->assign_by_ref('contact', $values);
1317 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1318 $tokenText = $smarty->fetch("string:$tokenText");
1319 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1323 if (self
::sendMessage(
1340 return array($sent, $activity->id
);
1343 static function sendSMS(&$contactDetails,
1345 &$smsParams = array(),
1349 if ($userID == NULL) {
1350 $session = CRM_Core_Session
::singleton();
1351 $userID = $session->get('userID');
1354 $text = &$activityParams['text_message'];
1355 $html = &$activityParams['html_message'];
1358 // token replacement of addressee/email/postal greetings
1359 // get the tokens added in subject and message
1360 $messageToken = CRM_Utils_Token
::getTokens($text);
1361 $messageToken = array_merge($messageToken,
1362 CRM_Utils_Token
::getTokens($html)
1365 //create the meta level record first ( sms activity )
1366 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1371 // CRM-6265: save both text and HTML parts in details (if present)
1372 if ($html and $text) {
1373 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1376 $details = $html ?
$html : $text;
1379 $activitySubject = $activityParams['activity_subject'];
1380 $activityParams = array(
1381 'source_contact_id' => $userID,
1382 'activity_type_id' => $activityTypeID,
1383 'activity_date_time' => date('YmdHis'),
1384 'subject' => $activitySubject,
1385 'details' => $details,
1386 // FIXME: check for name Completed and get ID from that lookup
1390 $activity = self
::create($activityParams);
1391 $activityID = $activity->id
;
1393 $returnProperties = array();
1395 if (isset($messageToken['contact'])) {
1396 foreach ($messageToken['contact'] as $key => $value) {
1397 $returnProperties[$value] = 1;
1403 CRM_Utils_Hook
::tokens($tokens);
1404 $categories = array_keys($tokens);
1406 // get token details for contacts, call only if tokens are used
1408 if (!empty($returnProperties) ||
!empty($tokens)) {
1409 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1413 'CRM_Activity_BAO_Activity'
1418 $escapeSmarty = FALSE;
1420 foreach ($contactDetails as $values) {
1421 $contactId = $values['contact_id'];
1423 if (!empty($details) && is_array($details["{$contactId}"])) {
1424 // unset email from details since it always returns primary email address
1425 unset($details["{$contactId}"]['email']);
1426 unset($details["{$contactId}"]['email_id']);
1427 $values = array_merge($values, $details["{$contactId}"]);
1430 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1431 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1433 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1434 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1436 // Only send if the phone is of type mobile
1437 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1438 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1439 $smsParams['To'] = $values['phone'];
1442 $smsParams['To'] = '';
1445 $sendResult = self
::sendSMSMessage(
1454 if (PEAR
::isError($sendResult)) {
1455 // Collect all of the PEAR_Error objects
1456 $errMsgs[] = $sendResult;
1462 // If at least one message was sent and no errors
1463 // were generated then return a boolean value of TRUE.
1464 // Otherwise, return FALSE (no messages sent) or
1465 // and array of 1 or more PEAR_Error objects.
1467 if ($success > 0 && count($errMsgs) == 0) {
1469 } elseif (count($errMsgs) > 0) {
1473 return array($sent, $activity->id
, $success);
1477 * send the sms message to a specific contact
1479 * @param int $toID the contact id of the recipient
1480 * @param int $activityID the activity ID that tracks the message
1481 * @param array $smsParams the params used for sending sms
1483 * @return mixed true on success or PEAR_Error object
1487 static function sendSMSMessage($toID,
1490 $smsParams = array(),
1495 $toPhoneNumber = "";
1497 if ($smsParams['To']) {
1498 $toPhoneNumber = trim($smsParams['To']);
1501 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1502 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1503 //to get primary mobile ph,if not get a first mobile ph
1504 if (!empty($toPhoneNumbers)) {
1505 $toPhoneNumerDetails = reset($toPhoneNumbers);
1506 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1507 //contact allows to send sms
1512 // make sure both phone are valid
1513 // and that the recipient wants to receive sms
1514 if (empty($toPhoneNumber) or $toDoNotSms) {
1515 return PEAR
::raiseError(
1516 'Recipient phone number is invalid or recipient does not want to receive SMS',
1522 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1523 $recipient = $smsParams['To'];
1524 $smsParams['contact_id'] = $toID;
1525 $smsParams['parent_activity_id'] = $activityID;
1527 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1528 $sendResult = $providerObj->send($recipient, $smsParams, $message, NULL, $userID);
1529 if (PEAR
::isError($sendResult)) {
1533 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1534 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1537 // add activity target record for every sms that is send
1538 $activityTargetParams = array(
1539 'activity_id' => $activityID,
1540 'contact_id' => $toID,
1541 'record_type_id' => $targetID
1543 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1549 * send the message to a specific contact
1551 * @param string $from the name and email of the sender
1552 * @param int $toID the contact id of the recipient
1553 * @param string $subject the subject of the message
1554 * @param string $message the message contents
1555 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1556 * @param int $activityID the activity ID that tracks the message
1558 * @return boolean true if successfull else false.
1562 static function sendMessage($from,
1570 $attachments = NULL,
1574 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1575 if ($emailAddress) {
1576 $toEmail = trim($emailAddress);
1579 // make sure both email addresses are valid
1580 // and that the recipient wants to receive email
1581 if (empty($toEmail) or $toDoNotEmail) {
1584 if (!trim($toDisplayName)) {
1585 $toDisplayName = $toEmail;
1588 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1589 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1590 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1591 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1593 // create the params array
1594 $mailParams = array(
1595 'groupName' => 'Activity Email Sender',
1597 'toName' => $toDisplayName,
1598 'toEmail' => $toEmail,
1599 'subject' => $subject,
1602 'text' => $text_message,
1603 'html' => $html_message,
1604 'attachments' => $attachments,
1607 if (!CRM_Utils_Mail
::send($mailParams)) {
1611 // add activity target record for every mail that is send
1612 $activityTargetParams = array(
1613 'activity_id' => $activityID,
1614 'contact_id' => $toID,
1615 'record_type_id' => $targetID
1617 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1622 * combine all the importable fields from the lower levels object
1624 * The ordering is important, since currently we do not have a weight
1625 * scheme. Adding weight is super important and should be done in the
1626 * next week or so, before this can be called complete.
1630 * @return array array of importable Fields
1634 static function &importableFields($status = FALSE) {
1635 if (!self
::$_importableFields) {
1636 if (!self
::$_importableFields) {
1637 self
::$_importableFields = array();
1640 $fields = array('' => array('title' => ts('- do not import -')));
1643 $fields = array('' => array('title' => ts('- Activity Fields -')));
1646 $tmpFields = CRM_Activity_DAO_Activity
::import();
1647 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1649 // Using new Dedupe rule.
1650 $ruleParams = array(
1651 'contact_type' => 'Individual',
1652 'used' => 'Unsupervised',
1654 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1656 $tmpConatctField = array();
1657 if (is_array($fieldsArray)) {
1658 foreach ($fieldsArray as $value) {
1659 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1664 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1665 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1666 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1669 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1670 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1671 $fields = array_merge($fields, $tmpConatctField);
1672 $fields = array_merge($fields, $tmpFields);
1673 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1674 self
::$_importableFields = $fields;
1676 return self
::$_importableFields;
1680 * To get the Activities of a target contact
1682 * @param $contactId Integer ContactId of the contact whose activities
1685 * @return array array of activity fields
1688 static function getContactActivity($contactId) {
1689 $activities = array();
1690 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1691 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1692 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1693 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1696 // First look for activities where contactId is one of the targets
1698 SELECT activity_id, record_type_id
1699 FROM civicrm_activity_contact
1700 WHERE contact_id = $contactId
1702 $dao = CRM_Core_DAO
::executeQuery($query);
1703 while ($dao->fetch()) {
1704 if ($dao->record_type_id
== $targetID ) {
1705 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1707 else if ($dao->record_type_id
== $assigneeID) {
1708 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1711 // do source stuff here
1712 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1716 $activityIds = array_keys($activities);
1717 if (count($activityIds) < 1) {
1721 $activityIds = implode(',', $activityIds);
1723 SELECT activity.id as activity_id,
1725 subject, location, activity_date_time, details, status_id
1726 FROM civicrm_activity activity
1727 WHERE activity.id IN ($activityIds)";
1729 $dao = CRM_Core_DAO
::executeQuery($query);
1731 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1732 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1734 while ($dao->fetch()) {
1735 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1736 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1737 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1738 $activities[$dao->activity_id
]['location'] = $dao->location
;
1739 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1740 $activities[$dao->activity_id
]['details'] = $dao->details
;
1741 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1742 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1743 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1745 // set to null if not set
1746 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1747 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1754 * Function to add activity for Membership/Event/Contribution
1756 * @param object $activity (reference) particular component object
1757 * @param string $activityType for Membership Signup or Renewal
1763 static function addActivity(&$activity,
1764 $activityType = 'Membership Signup',
1765 $targetContactID = NULL
1767 if ($activity->__table
== 'civicrm_membership') {
1768 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1770 if (!$membershipType) {
1771 $membershipType = ts('Membership');
1774 $subject = "{$membershipType}";
1776 if (!empty($activity->source
) && $activity->source
!= 'null') {
1777 $subject .= " - {$activity->source}";
1780 if ($activity->owner_membership_id
) {
1783 FROM civicrm_contact, civicrm_membership
1784 WHERE civicrm_contact.id = civicrm_membership.contact_id
1785 AND civicrm_membership.id = $activity->owner_membership_id
1787 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1788 $subject .= " (by {$displayName})";
1791 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1792 // CRM-72097 changed from start date to today
1793 $date = date('YmdHis');
1794 $component = 'Membership';
1796 elseif ($activity->__table
== 'civicrm_participant') {
1797 $event = CRM_Event_BAO_Event
::getEvents(1, $activity->event_id
, TRUE, FALSE);
1799 $roles = CRM_Event_PseudoConstant
::participantRole();
1800 $status = CRM_Event_PseudoConstant
::participantStatus();
1802 $subject = $event[$activity->event_id
];
1803 if (!empty($roles[$activity->role_id
])) {
1804 $subject .= ' - ' . $roles[$activity->role_id
];
1806 if (!empty($status[$activity->status_id
])) {
1807 $subject .= ' - ' . $status[$activity->status_id
];
1809 $date = date('YmdHis');
1810 if ($activityType != 'Email') {
1811 $activityType = 'Event Registration';
1813 $component = 'Event';
1815 elseif ($activity->__table
== 'civicrm_contribution') {
1816 //create activity record only for Completed Contributions
1817 if ($activity->contribution_status_id
!= 1) {
1823 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1824 if (!empty($activity->source
) && $activity->source
!= 'null') {
1825 $subject .= " - {$activity->source}";
1827 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1828 $activityType = $component = 'Contribution';
1830 $activityParams = array(
1831 'source_contact_id' => $activity->contact_id
,
1832 'source_record_id' => $activity->id
,
1833 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1837 'subject' => $subject,
1838 'activity_date_time' => $date,
1839 'is_test' => $activity->is_test
,
1840 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1844 'skipRecentView' => TRUE,
1845 'campaign_id' => $activity->campaign_id
,
1848 // create activity with target contacts
1849 $session = CRM_Core_Session
::singleton();
1850 $id = $session->get('userID');
1852 $activityParams['source_contact_id'] = $id;
1853 $activityParams['target_contact_id'][] = $activity->contact_id
;
1857 if ($targetContactID) {
1858 $activityParams['target_contact_id'][] = $targetContactID;
1860 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1861 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1867 * Function to get Parent activity for currently viewed activity
1869 * @param int $activityId current activity id
1871 * @return int $parentId Id of parent activity otherwise false.
1874 static function getParentActivity($activityId) {
1875 static $parentActivities = array();
1877 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1879 if (!array_key_exists($activityId, $parentActivities)) {
1880 $parentActivities[$activityId] = array();
1882 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1887 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1890 return $parentActivities[$activityId];
1894 * Function to get total count of prior revision of currently viewd activity
1896 * @param int $activityId current activity id
1898 * @return int $params count of prior activities otherwise false.
1901 static function getPriorCount($activityID) {
1902 static $priorCounts = array();
1904 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1906 if (!array_key_exists($activityID, $priorCounts)) {
1907 $priorCounts[$activityID] = array();
1908 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1915 SELECT count( id ) AS cnt
1916 FROM civicrm_activity
1917 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1918 AND is_current_revision = 0
1919 AND id < {$activityID}
1921 $params = array(1 => array($originalID, 'Integer'));
1922 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1924 $priorCounts[$activityID] = $count ?
$count : 0;
1927 return $priorCounts[$activityID];
1931 * Function to get all prior activities of currently viewe
1934 * @param int $activityId current activity id
1936 * @return array $result prior activities info.
1939 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1940 static $priorActivities = array();
1942 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1943 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1945 if (!array_key_exists($index, $priorActivities)) {
1946 $priorActivities[$index] = array();
1948 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1954 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1955 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1956 WHERE (ca.id = %1 OR ca.original_id = %1)
1957 AND cl.entity_table = 'civicrm_activity'
1958 AND cl.entity_id = ca.id
1959 AND cl.modified_id = c.id
1961 if ($onlyPriorRevisions) {
1962 $query .= " AND ca.id < {$activityID}";
1964 $query .= " ORDER BY ca.id DESC";
1966 $params = array(1 => array($originalID, 'Integer'));
1967 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1969 while ($dao->fetch()) {
1970 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1971 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1972 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1977 return $priorActivities[$index];
1981 * Function to find the latest revision of a given activity
1983 * @param int $activityId prior activity id
1985 * @return int $params current activity id.
1988 static function getLatestActivityId($activityID) {
1989 static $latestActivityIds = array();
1991 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1993 if (!array_key_exists($activityID, $latestActivityIds)) {
1994 $latestActivityIds[$activityID] = array();
1996 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2001 $activityID = $originalID;
2003 $params = array(1 => array($activityID, 'Integer'));
2004 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2006 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2009 return $latestActivityIds[$activityID];
2013 * Function to create a follow up a given activity
2015 * @activityId int activity id of parent activity
2017 * @param array $activity details
2021 static function createFollowupActivity($activityId, $params) {
2026 $session = CRM_Core_Session
::singleton();
2028 $followupParams = array();
2029 $followupParams['parent_id'] = $activityId;
2030 $followupParams['source_contact_id'] = $session->get('userID');
2031 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2033 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2034 // Get Subject of Follow-up Activiity, CRM-4491
2035 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2036 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2038 //create target contact for followup
2039 if (!empty($params['target_contact_id'])) {
2040 $followupParams['target_contact_id'] = $params['target_contact_id'];
2043 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2044 $params['followup_date_time']
2046 $followupActivity = self
::create($followupParams);
2048 return $followupActivity;
2052 * Function to get Activity specific File according activity type Id.
2054 * @param int $activityTypeId activity id
2056 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2060 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2061 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2063 if ($activityTypes[$activityTypeId]['name']) {
2064 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2070 global $civicrm_root;
2071 $config = CRM_Core_Config
::singleton();
2072 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2073 if (empty($config->customPHPPathDir
)) {
2076 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2081 return $activityTypeFile;
2085 * Function to restore the activity
2087 * @param array $params associated array
2093 public static function restoreActivity(&$params) {
2094 $activity = new CRM_Activity_DAO_Activity();
2095 $activity->copyValues($params);
2097 $activity->is_deleted
= 0;
2098 $result = $activity->save();
2104 * Get the exportable fields for Activities
2106 * @param string $name if it is called by case $name = Case else $name = Activity
2108 * @return array array of exportable Fields
2112 static function &exportableFields($name = 'Activity') {
2113 if (!isset(self
::$_exportableFields[$name])) {
2114 self
::$_exportableFields[$name] = array();
2116 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2117 // my case hence we have defined fields as case_*
2118 if ($name == 'Activity') {
2119 $exportableFields = CRM_Activity_DAO_Activity
::export();
2120 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2121 $exportableFields['source_contact'] = array(
2122 'title' => ts('Source Contact'),
2123 'type' => CRM_Utils_Type
::T_STRING
,
2127 $Activityfields = array(
2128 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2129 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2131 $fields = array_merge($Activityfields, $exportableFields);
2134 //set title to activity fields
2136 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2137 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2138 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2139 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2140 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2141 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2142 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2143 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2144 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2145 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2148 // add custom data for cases
2149 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2152 // add custom data for case activities
2153 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2155 self
::$_exportableFields[$name] = $fields;
2157 return self
::$_exportableFields[$name];
2161 * Get the allowed profile fields for Activities
2163 * @return array array of activity profile Fields
2166 static function getProfileFields() {
2167 $exportableFields = self
::exportableFields('Activity');
2168 $skipFields = array(
2171 'source_contact_id',
2173 'activity_campaign',
2175 'is_current_revision',
2176 'activity_is_deleted',
2178 $config = CRM_Core_Config
::singleton();
2179 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2180 $skipFields[] = 'activity_engagement_level';
2183 foreach ($skipFields as $field) {
2184 if (isset($exportableFields[$field])) {
2185 unset($exportableFields[$field]);
2189 // hack to use 'activity_type_id' instead of 'activity_type'
2190 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2191 unset($exportableFields['activity_status']);
2193 return $exportableFields;
2197 * This function deletes the activity record related to contact record,
2198 * when there are no target and assignee record w/ other contact.
2200 * @param int $contactId contactId
2205 public static function cleanupActivity($contactId) {
2210 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2211 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2213 $transaction = new CRM_Core_Transaction();
2215 // delete activity if there is no record in civicrm_activity_contact
2216 // pointing to any other contact record
2217 $activityContact = new CRM_Activity_DAO_ActivityContact();
2218 $activityContact->contact_id
= $contactId;
2219 $activityContact->record_type_id
= $sourceID;
2220 $activityContact->find();
2222 while ($activityContact->fetch()) {
2223 // delete activity_contact record for the deleted contact
2224 $activityContact->delete();
2226 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2227 $activityContactOther->activity_id
= $activityContact->activity_id
;
2229 // delete activity only if no other contacts connected
2230 if ( ! $activityContactOther->find(TRUE) ) {
2231 $activityParams = array('id' => $activityContact->activity_id
);
2232 $result = self
::deleteActivity($activityParams);
2235 $activityContactOther->free();
2238 $activityContact->free();
2239 $transaction->commit();
2245 * Does user has sufficient permission for view/edit activity record.
2247 * @param int $activityId activity record id.
2248 * @param int $action edit/view
2250 * @return boolean $allow true/false
2253 public static function checkPermission($activityId, $action) {
2256 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2261 $activity = new CRM_Activity_DAO_Activity();
2262 $activity->id
= $activityId;
2263 if (!$activity->find(TRUE)) {
2267 //component related permissions.
2268 $compPermissions = array(
2269 'CiviCase' => array('administer CiviCase',
2270 'access my cases and activities',
2271 'access all cases and activities',
2273 'CiviMail' => array('access CiviMail'),
2274 'CiviEvent' => array('access CiviEvent'),
2275 'CiviGrant' => array('access CiviGrant'),
2276 'CiviPledge' => array('access CiviPledge'),
2277 'CiviMember' => array('access CiviMember'),
2278 'CiviReport' => array('access CiviReport'),
2279 'CiviContribute' => array('access CiviContribute'),
2280 'CiviCampaign' => array('administer CiviCampaign'),
2283 //return early when it is case activity.
2284 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2285 //check for civicase related permission.
2286 if ($isCaseActivity) {
2288 foreach ($compPermissions['CiviCase'] as $per) {
2289 if (CRM_Core_Permission
::check($per)) {
2295 //check for case specific permissions.
2298 if ($action == CRM_Core_Action
::UPDATE
) {
2301 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2303 $activity->activity_type_id
2310 //first check the component permission.
2313 FROM civicrm_option_value val
2314 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2315 WHERE val.value = %2";
2316 $params = array(1 => array('activity_type', 'String'),
2317 2 => array($activity->activity_type_id
, 'Integer'),
2319 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2322 $componentName = CRM_Core_Component
::getComponentName($componentId);
2323 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2325 //here we are interesting in any single permission.
2326 if (is_array($compPermission)) {
2327 foreach ($compPermission as $per) {
2328 if (CRM_Core_Permission
::check($per)) {
2336 //check for this permission related to contact.
2337 $permission = CRM_Core_Permission
::VIEW
;
2338 if ($action == CRM_Core_Action
::UPDATE
) {
2339 $permission = CRM_Core_Permission
::EDIT
;
2342 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2343 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2344 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2345 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2347 //check for source contact.
2348 if (!$componentId ||
$allow) {
2349 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2350 //account for possibility of activity not having a source contact (as it may have been deleted)
2351 if ( $sourceContactId ) {
2352 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2356 //check for target and assignee contacts.
2358 //first check for supper permission.
2359 $supPermission = 'view all contacts';
2360 if ($action == CRM_Core_Action
::UPDATE
) {
2361 $supPermission = 'edit all contacts';
2363 $allow = CRM_Core_Permission
::check($supPermission);
2365 //user might have sufficient permission, through acls.
2368 //get the target contacts.
2369 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2370 foreach ($targetContacts as $cnt => $contactId) {
2371 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2377 //get the assignee contacts.
2379 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2380 foreach ($assigneeContacts as $cnt => $contactId) {
2381 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2394 * This function is a wrapper for ajax activity selector
2396 * @param array $params associated array for params record id.
2398 * @return array $contactActivities associated array of contact activities
2401 public static function getContactActivitySelector(&$params) {
2402 // format the params
2403 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2404 $params['rowCount'] = $params['rp'];
2405 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2406 $params['caseId'] = NULL;
2407 $context = CRM_Utils_Array
::value('context', $params);
2409 // get contact activities
2410 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2413 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2415 // format params and add links
2416 $contactActivities = array();
2418 if (!empty($activities)) {
2419 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2421 // check logged in user for permission
2422 $page = new CRM_Core_Page();
2423 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2424 $permissions = array($page->_permission
);
2425 if (CRM_Core_Permission
::check('delete activities')) {
2426 $permissions[] = CRM_Core_Permission
::DELETE
;
2429 $mask = CRM_Core_Action
::mask($permissions);
2431 foreach ($activities as $activityId => $values) {
2432 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2433 $contactActivities[$activityId]['subject'] = $values['subject'];
2434 if ($params['contact_id'] == $values['source_contact_id']) {
2435 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2437 elseif ($values['source_contact_id']) {
2438 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'],
2439 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2442 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2445 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2446 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2447 'civicrm/mailing/report/event',
2448 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2450 elseif (!empty($values['recipients'])) {
2451 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2453 elseif (!$values['target_contact_name']) {
2454 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2456 elseif (!empty($values['target_contact_name'])) {
2458 $contactActivities[$activityId]['target_contact'] = '';
2459 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2460 if ($tcID && $count < 5) {
2461 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName,
2462 'civicrm/contact/view', "reset=1&cid={$tcID}");
2465 $contactActivities[$activityId]['target_contact'] .= "; ";
2469 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2476 if (empty($values['assignee_contact_name'])) {
2477 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2479 elseif (!empty($values['assignee_contact_name'])) {
2481 $contactActivities[$activityId]['assignee_contact'] = '';
2482 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2483 if ($acID && $count < 5) {
2484 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2487 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2491 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2498 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2499 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2501 // add class to this row if overdue
2502 $contactActivities[$activityId]['class'] = '';
2503 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2504 && CRM_Utils_Array
::value('status_id', $values) == 1
2506 $contactActivities[$activityId]['class'] = 'status-overdue';
2509 $contactActivities[$activityId]['class'] = 'status-ontime';
2513 $contactActivities[$activityId]['links'] = '';
2514 $accessMailingReport = FALSE;
2515 if (!empty($values['mailingId'])) {
2516 $accessMailingReport = TRUE;
2519 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2520 CRM_Utils_Array
::value('activity_type_id', $values),
2521 CRM_Utils_Array
::value('source_record_id', $values),
2522 $accessMailingReport,
2523 CRM_Utils_Array
::value('activity_id', $values)
2526 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2528 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2531 'id' => $values['activity_id'],
2532 'cid' => $params['contact_id'],
2534 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2540 $values['activity_id']
2545 return $contactActivities;
2549 * Used to copy custom fields and attachments from an existing activity to another.
2550 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2552 static function copyExtendedActivityData($params) {
2553 // attach custom data to the new activity
2554 $customParams = $htmlType = array();
2555 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2557 if (!empty($customValues)) {
2558 $fieldIds = implode(', ', array_keys($customValues));
2559 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2560 $result = CRM_Core_DAO
::executeQuery($sql);
2562 while ($result->fetch()) {
2563 $htmlType[] = $result->id
;
2566 foreach ($customValues as $key => $value) {
2567 if ($value !== NULL) { // CRM-10542
2568 if (in_array($key, $htmlType)) {
2569 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2570 $customParams["custom_{$key}_-1"] = array(
2571 'name' => $fileValues[0],
2572 'path' => $fileValues[1],
2576 $customParams["custom_{$key}_-1"] = $value;
2580 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2581 $params['mainActivityId'], 'Activity'
2585 // copy activity attachments ( if any )
2586 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2589 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2590 $activityContact = new CRM_Activity_BAO_ActivityContact();
2591 $activityContact->activity_id
= $activityId;
2592 if ($recordTypeID) {
2593 $activityContact->record_type_id
= $recordTypeID;
2595 if ($activityContact->find(TRUE)) {
2596 return $activityContact->$column;
2601 public static function getSourceContactID($activityId) {
2602 static $sourceID = NULL;
2604 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2605 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2608 return self
::getActivityContact($activityId, $sourceID);
2611 function setApiFilter(&$params) {
2612 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2614 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2615 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2616 $obj = new CRM_Activity_BAO_ActivityContact();
2617 $params['return.target_contact_id'] = 1;
2618 $this->joinAdd($obj, 'LEFT');
2619 $this->selectAdd('civicrm_activity.*');
2620 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");