3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\ActivityContact
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * This class is for activity functions.
23 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
26 * Activity status types
34 * Static field for all the activity information that we can potentially export.
38 public static $_exportableFields = NULL;
41 * Static field for all the activity information that we can potentially import.
45 public static $_importableFields = NULL;
48 * Check if there is absolute minimum of data to add the object.
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
55 public static function dataExists(&$params) {
56 if (!empty($params['source_contact_id']) ||
!empty($params['id'])) {
65 * Fetch object based on array of properties.
67 * @param array $params
68 * (reference ) an assoc array of name/value pairs.
69 * @param array $defaults
70 * (reference ) an assoc array to hold the flattened values.
72 * @return CRM_Activity_DAO_Activity
74 public static function retrieve(&$params, &$defaults) {
75 // this will bypass acls - use the api instead.
76 // @todo add deprecation logging to this function.
77 $activity = new CRM_Activity_DAO_Activity();
78 $activity->copyValues($params);
80 if ($activity->find(TRUE)) {
81 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
82 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
83 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
84 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
86 // TODO: at some stage we'll have to deal
87 // with multiple values for assignees and targets, but
88 // for now, let's just fetch first row.
89 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
90 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
91 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
92 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
93 if ($activity->activity_type_id
!= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email')) {
94 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
95 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
96 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
98 elseif (CRM_Core_Permission
::check('access CiviMail') ||
99 (CRM_Mailing_Info
::workflowEnabled() &&
100 CRM_Core_Permission
::check('create mailings')
103 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
104 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
108 $defaults['target_contact_value'] = ts('(recipients)');
111 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
112 $defaults['source_contact_id'] = $sourceContactId;
114 if ($sourceContactId &&
115 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
120 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
127 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
129 CRM_Core_DAO
::storeValues($activity, $defaults);
137 * Delete the activity.
139 * @param array $params
140 * @param bool $moveToTrash
144 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
146 if (!empty($params['id']) && !is_array($params['id'])) {
147 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
150 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
153 $transaction = new CRM_Core_Transaction();
154 $sqlWhereParams = $where = [];
155 if (isset($params['source_record_id']) && is_array($params['source_record_id'])) {
156 $sourceRecordIds = implode(',', $params['source_record_id']);
159 $sourceRecordIds = $params['source_record_id'] ??
NULL;
162 if ($sourceRecordIds) {
163 $where[] = 'source_record_id IN ( %1 )';
164 $sqlWhereParams[1] = [$sourceRecordIds, 'CommaSeparatedIntegers'];
168 if (!isset($params['id'])) {
169 if (!empty($params['activity_type_id'])) {
170 $where[] = 'activity_type_id IN ( %2 )';
171 $sqlWhereParams[2] = [implode(',', (array) $params['activity_type_id']), 'CommaSeparatedIntegers'];
173 $query = "DELETE FROM civicrm_activity WHERE " . implode(' AND ', $where);
174 $dao = CRM_Core_DAO
::executeQuery($query, $sqlWhereParams);
177 $activity = new CRM_Activity_DAO_Activity();
178 $activity->copyValues($params);
179 $result = $activity->delete();
182 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
184 // CRM-13994 delete activity entity_tag
185 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = %1";
186 $dao = CRM_Core_DAO
::executeQuery($query, [1 => [$activity->id
, 'Positive']]);
188 CRM_Core_BAO_File
::deleteEntityFile('civicrm_activity', $activity->id
);
192 $activity = new CRM_Activity_DAO_Activity();
193 $activity->copyValues($params);
195 $activity->is_deleted
= 1;
196 $result = $activity->save();
198 // CRM-4525 log activity delete
199 $logMsg = 'Case Activity deleted for';
202 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
203 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
204 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
205 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
206 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
207 if ($sourceContactId) {
208 $msgs[] = " source={$sourceContactId}";
211 // get target contacts.
212 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
213 if (!empty($targetContactIds)) {
214 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
216 // get assignee contacts.
217 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
218 if (!empty($assigneeContactIds)) {
219 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
222 $logMsg .= implode(', ', $msgs);
224 self
::logActivityAction($activity, $logMsg);
227 // delete the recently created Activity
230 'id' => $activity->id
,
231 'type' => 'Activity',
233 CRM_Utils_Recent
::del($activityRecent);
236 $transaction->commit();
237 if (isset($activity)) {
239 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
240 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
247 * Delete activity assignment record.
249 * @param int $activityId
250 * @param int $recordTypeID
252 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
253 $activityContact = new CRM_Activity_BAO_ActivityContact();
254 $activityContact->activity_id
= $activityId;
256 $activityContact->record_type_id
= $recordTypeID;
259 // Let's check if activity contact record exits and then delete.
260 // Looks like delete leads to deadlock when multiple simultaneous
261 // requests are done. CRM-15470
262 if ($activityContact->find()) {
263 $activityContact->delete();
268 * Process the activities.
270 * @param array $params
271 * Associated array of the submitted values.
273 * @throws CRM_Core_Exception
275 * @return CRM_Activity_BAO_Activity|null|object
277 public static function create(&$params) {
278 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
279 unset($params['created_date']);
280 unset($params['modified_date']);
282 // check required params
283 if (!self
::dataExists($params)) {
284 throw new CRM_Core_Exception('Not enough data to create activity object');
287 $activity = new CRM_Activity_DAO_Activity();
289 if (isset($params['id']) && empty($params['id'])) {
290 unset($params['id']);
293 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
294 if (isset($params['activity_date_time']) &&
295 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
297 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed');
300 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
304 // Set priority to Normal for Auto-populated activities (for Cases)
305 if (!isset($params['priority_id']) &&
306 // if not set and not 0
309 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
310 $params['priority_id'] = array_search('Normal', $priority);
313 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
314 $params['target_contact_id'] = array_unique($params['target_contact_id']);
316 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
317 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
320 $action = empty($params['id']) ?
'create' : 'edit';
321 CRM_Utils_Hook
::pre($action, 'Activity', $params['id'] ??
NULL, $params);
323 $activity->copyValues($params);
324 if (isset($params['case_id'])) {
325 // CRM-8708, preserve case ID even though it's not part of the SQL model
326 $activity->case_id
= $params['case_id'];
328 elseif (is_numeric($activity->id
)) {
329 // CRM-8708, preserve case ID even though it's not part of the SQL model
330 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
334 $transaction = new CRM_Core_Transaction();
336 $result = $activity->save();
338 if (is_a($result, 'CRM_Core_Error')) {
339 $transaction->rollback();
343 $activityId = $activity->id
;
344 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
345 $assigneeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Assignees');
346 $targetID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
348 $activityRecordTypes = [
349 'source_contact_id' => 'Activity Source',
350 'assignee_contact_id' => 'Activity Assignees',
351 'target_contact_id' => 'Activity Targets',
353 $activityContacts = array_intersect_key($params, $activityRecordTypes);
355 // Unset any which are a single id - this is just because they have traditionally been updated as
356 // opposed to delete + possible create for the others.
357 // Potentially we should nuance it for the others too....
358 foreach ($activityContacts as $index => $value) {
359 if ($value && !is_array($value)) {
360 unset($activityContacts[$index]);
364 if ($action === 'edit' && !empty($activityContacts)) {
365 $wheres = [['activity_id', '=', $params['id']], ['record_type_id:name', 'IN', array_intersect_key($activityRecordTypes, $activityContacts)]];
366 // Delete all existing records for the types to be updated. Do a quick check to make sure there
367 // is at least one to avoid a delete query if not necessary (delete queries are more likely to cause contention).
368 if (ActivityContact
::get($params['check_permissions'] ??
FALSE)->setLimit(1)->setWhere($wheres)->selectRowCount()->execute()) {
369 ActivityContact
::delete($params['check_permissions'] ??
FALSE)->setWhere($wheres)->execute();
373 if (isset($params['source_contact_id'])) {
375 'activity_id' => $activityId,
376 'contact_id' => $params['source_contact_id'],
377 'record_type_id' => $sourceID,
379 CRM_Activity_BAO_ActivityContact
::create($acParams);
382 // check and attach and files as needed
383 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
385 // attempt to save activity assignment
386 $resultAssignment = NULL;
387 if (!empty($params['assignee_contact_id'])) {
389 $assignmentParams = ['activity_id' => $activityId];
391 if (is_array($params['assignee_contact_id'])) {
392 foreach ($params['assignee_contact_id'] as $acID) {
395 'activity_id' => $activityId,
396 'contact_id' => $acID,
397 'record_type_id' => $assigneeID,
399 CRM_Activity_BAO_ActivityContact
::create($assigneeParams);
404 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
405 $assignmentParams['record_type_id'] = $assigneeID;
406 if (!empty($params['id'])) {
407 $assignment = new CRM_Activity_BAO_ActivityContact();
408 $assignment->activity_id
= $activityId;
409 $assignment->record_type_id
= $assigneeID;
410 $assignment->find(TRUE);
412 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
413 $assignmentParams['id'] = $assignment->id
;
414 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
418 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
423 if (is_a($resultAssignment, 'CRM_Core_Error')) {
424 $transaction->rollback();
425 return $resultAssignment;
428 // attempt to save activity targets
429 if (!empty($params['target_contact_id'])) {
431 $targetParams = ['activity_id' => $activityId];
432 if (is_array($params['target_contact_id'])) {
434 foreach ($params['target_contact_id'] as $tid) {
436 $targetContactParams = [
437 'activity_id' => $activityId,
438 'contact_id' => $tid,
439 'record_type_id' => $targetID,
441 CRM_Activity_BAO_ActivityContact
::create($targetContactParams);
446 $targetParams['contact_id'] = $params['target_contact_id'];
447 $targetParams['record_type_id'] = $targetID;
448 if (!empty($params['id'])) {
449 $target = new CRM_Activity_BAO_ActivityContact();
450 $target->activity_id
= $activityId;
451 $target->record_type_id
= $targetID;
454 if ($target->contact_id
!= $params['target_contact_id']) {
455 $targetParams['id'] = $target->id
;
456 CRM_Activity_BAO_ActivityContact
::create($targetParams);
460 CRM_Activity_BAO_ActivityContact
::create($targetParams);
465 // write to changelog before transaction is committed/rolled
466 // back (and prepare status to display)
467 if (!empty($params['id'])) {
468 $logMsg = "Activity (id: {$result->id} ) updated with ";
471 $logMsg = "Activity created for ";
475 if (isset($params['source_contact_id'])) {
476 $msgs[] = "source={$params['source_contact_id']}";
479 if (!empty($params['target_contact_id'])) {
480 if (is_array($params['target_contact_id']) && !CRM_Utils_Array
::crmIsEmptyArray($params['target_contact_id'])) {
481 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
482 // take only first target
483 // will be used for recently viewed display
484 $t = array_slice($params['target_contact_id'], 0, 1);
485 $recentContactId = $t[0];
487 // Is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
488 // as it may always be an array
489 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
490 $msgs[] = "target={$params['target_contact_id']}";
491 // will be used for recently viewed display
492 $recentContactId = $params['target_contact_id'];
496 // at worst, take source for recently viewed display
497 $recentContactId = $params['source_contact_id'] ??
NULL;
500 if (isset($params['assignee_contact_id'])) {
501 if (is_array($params['assignee_contact_id'])) {
502 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
505 $msgs[] = "assignee={$params['assignee_contact_id']}";
508 $logMsg .= implode(', ', $msgs);
510 self
::logActivityAction($result, $logMsg);
512 if (!empty($params['custom']) &&
513 is_array($params['custom'])
515 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
518 $transaction->commit();
519 if (empty($params['skipRecentView'])) {
521 if (!empty($params['case_id'])) {
522 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
523 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
524 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
528 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home";
529 if ($activity->activity_type_id
!= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email')) {
530 $url = CRM_Utils_System
::url('civicrm/activity', $q);
531 if ($activity->activity_type_id
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Print PDF Letter')) {
532 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
533 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
537 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
538 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
542 if (CRM_Core_Permission
::check("delete activities")) {
543 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
544 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
549 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
550 if (CRM_Core_Permission
::check('delete activities')) {
551 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
552 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
558 if (!isset($activity->parent_id
)) {
559 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
560 // add the recently created Activity
561 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
562 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
565 if (isset($activitySubject)) {
566 $title = $activitySubject . ' - ';
569 $title = $title . $recentContactDisplay;
570 if (!empty($activityTypes[$activity->activity_type_id
])) {
571 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
574 CRM_Utils_Recent
::add($title,
579 $recentContactDisplay,
585 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
587 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
589 $subjectToMatch = $params['subject'] ??
NULL;
590 if (preg_match('/\[case #([0-9a-h]{7})\]/', $subjectToMatch, $matches)) {
591 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
593 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '" . CRM_Core_DAO
::escapeString($hash) . "'";
595 elseif (preg_match('/\[case #(\d+)\]/', $subjectToMatch, $matches)) {
596 $query = "SELECT id FROM civicrm_case WHERE id = '" . CRM_Core_DAO
::escapeString($matches[1]) . "'";
598 if (!empty($matches)) {
600 'activity_id' => $activity->id
,
601 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
603 if ($caseParams['case_id']) {
604 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
607 self
::logActivityAction($activity, "Case details for {$matches[1]} not found while recording an activity on case.");
610 CRM_Utils_Hook
::post($action, 'Activity', $activity->id
, $activity);
615 * Create an activity.
617 * @todo elaborate on what this does.
619 * @param CRM_Activity_DAO_Activity $activity
620 * @param string $logMessage
624 public static function logActivityAction($activity, $logMessage = NULL) {
625 $id = CRM_Core_Session
::getLoggedInContactID();
627 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
628 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
629 $id = self
::getActivityContact($activity->id
, $sourceID);
632 'entity_table' => 'civicrm_activity',
633 'entity_id' => $activity->id
,
634 'modified_id' => $id,
635 'modified_date' => date('YmdHis'),
636 'data' => $logMessage,
638 CRM_Core_BAO_Log
::add($logParams);
643 * Get the list Activities.
645 * @param array $params
646 * Array of parameters.
648 * - contact_id int contact_id whose activities we want to retrieve
649 * - offset int which row to start from ?
650 * - rowCount int how many rows to fetch
651 * - sort object|array object or array describing sort order for sql query.
652 * - admin boolean if contact is admin
653 * - caseId int case ID
654 * - context string page on which selector is build
655 * - activity_type_id int|string the activitiy types we want to restrict by
658 * Relevant data object values of open activities
659 * @throws \CiviCRM_API3_Exception
661 public static function getActivities($params) {
664 // Activity.Get API params
665 $activityParams = self
::getActivityParamsForDashboardFunctions($params);
667 if (!empty($params['rowCount']) &&
668 $params['rowCount'] > 0
670 $activityParams['options']['limit'] = $params['rowCount'];
673 if (!empty($params['sort'])) {
674 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
675 $order = $params['sort']->orderBy();
677 elseif (trim($params['sort'])) {
678 $order = CRM_Utils_Type
::escape($params['sort'], 'String');
682 $activityParams['options']['sort'] = empty($order) ?
"activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
684 $activityParams['return'] = [
685 'activity_date_time',
688 'source_contact_name',
689 'assignee_contact_id',
690 'assignee_contact_name',
698 // Q. What does the code below achieve? case_id and campaign_id are already
699 // in the array, defined above, and this code adds them in again if their
700 // component is enabled? @fixme remove case_id and campaign_id from the array above?
701 foreach (['case_id' => 'CiviCase', 'campaign_id' => 'CiviCampaign'] as $attr => $component) {
702 if (in_array($component, self
::activityComponents())) {
703 $activityParams['return'][] = $attr;
706 $result = civicrm_api3('Activity', 'Get', $activityParams)['values'];
708 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
709 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
711 // CRM-3553, need to check user has access to target groups.
712 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
713 $accessCiviMail = ((CRM_Core_Permission
::check('access CiviMail')) ||
714 (CRM_Mailing_Info
::workflowEnabled() && CRM_Core_Permission
::check('create mailings'))
717 // @todo - get rid of this & just handle in the array declaration like we do with 'subject' etc.
719 'source_record_id' => 'source_record_id',
720 'activity_type_id' => 'activity_type_id',
721 'status_id' => 'status_id',
722 'campaign_id' => 'campaign_id',
723 'case_id' => 'case_id',
726 if (empty($result)) {
730 $targetCount = CRM_Core_DAO
::executeQuery('
731 SELECT activity_id, count(*) as target_contact_count
732 FROM civicrm_activity_contact
733 INNER JOIN civicrm_contact c ON contact_id = c.id AND c.is_deleted = 0
734 WHERE activity_id IN (' . implode(',', array_keys($result)) . ')
735 AND record_type_id = %1
736 GROUP BY activity_id', [
738 CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'),
743 foreach ($targetCount as $activityTarget) {
744 $result[$activityTarget['activity_id']]['target_contact_count'] = $activityTarget['target_contact_count'];
746 // Iterate through & do basic mappings & determine which ones we want to retrieve target count for.
747 foreach ($result as $id => $activity) {
749 'activity_id' => $activity['id'],
750 'activity_date_time' => $activity['activity_date_time'] ??
NULL,
751 'subject' => $activity['subject'] ??
NULL,
752 'assignee_contact_name' => $activity['assignee_contact_sort_name'] ??
[],
753 'source_contact_id' => $activity['source_contact_id'] ??
NULL,
754 'source_contact_name' => $activity['source_contact_sort_name'] ??
NULL,
756 $activities[$id]['activity_type_name'] = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $activity['activity_type_id']);
757 $activities[$id]['activity_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $activity['activity_type_id']);
758 $activities[$id]['target_contact_count'] = $activity['target_contact_count'] ??
0;
759 if (!empty($activity['target_contact_count'])) {
760 $displayedTarget = civicrm_api3('ActivityContact', 'get', [
761 'activity_id' => $id,
762 'check_permissions' => TRUE,
763 'options' => ['limit' => 1],
764 'record_type_id' => 'Activity Targets',
765 'return' => ['contact_id.sort_name', 'contact_id'],
768 if (empty($displayedTarget[0])) {
769 $activities[$id]['target_contact_name'] = [];
772 $activities[$id]['target_contact_name'] = [$displayedTarget[0]['contact_id'] => $displayedTarget[0]['contact_id.sort_name']];
775 if ($activities[$id]['activity_type_name'] === 'Bulk Email') {
776 $bulkActivities[] = $id;
777 // Get the total without permissions being passed but only display names after permissioning.
778 $activities[$id]['recipients'] = ts('(%1 recipients)', [1 => $activities[$id]['target_contact_count']]);
782 // Eventually this second iteration should just handle the target contacts. It's a bit muddled at
783 // the moment as the bulk activity stuff needs unravelling & test coverage.
785 foreach ($result as $id => $activity) {
786 $isBulkActivity = (!$bulkActivityTypeID ||
($bulkActivityTypeID === $activity['activity_type_id']));
787 foreach ($mappingParams as $apiKey => $expectedName) {
788 if (in_array($apiKey, [
789 'target_contact_name',
792 if ($isBulkActivity) {
793 // @todo - how is this used? Couldn't we use 'is_bulk' or something clearer?
794 // or the calling function could handle
795 $activities[$id]['mailingId'] = FALSE;
796 if ($accessCiviMail &&
797 ($mailingIDs === TRUE ||
in_array($activity['source_record_id'], $mailingIDs))
799 $activities[$id]['mailingId'] = TRUE;
803 // case related fields
804 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
805 $activities[$id][$expectedName] = $activity[$apiKey] ??
NULL;
807 // fetch case subject for case ID found
808 if (!empty($activity['case_id'])) {
809 // Store cases; we'll look them up in one query below. We convert
810 // to int here so we can trust it for SQL.
811 $caseIds[$id] = (int) current($activity['case_id']);
815 // @todo this generic assign could just be handled in array declaration earlier.
816 $activities[$id][$expectedName] = $activity[$apiKey] ??
NULL;
817 if ($apiKey == 'campaign_id') {
818 $activities[$id]['campaign'] = $allCampaigns[$activities[$id][$expectedName]] ??
NULL;
822 // if deleted, wrap in <del>
823 if (!empty($activity['source_contact_id']) &&
824 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
826 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
828 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getParentFor($id, 'civicrm_activity');
831 // Look up any case subjects we need in a single query and add them in the relevant activities under 'case_subject'
833 $subjects = CRM_Core_DAO
::executeQuery('SELECT id, subject FROM civicrm_case WHERE id IN (' . implode(',', array_unique($caseIds)) . ')')
834 ->fetchMap('id', 'subject');
835 foreach ($caseIds as $activityId => $caseId) {
836 $result[$activityId]['case_subject'] = $subjects[$caseId];
844 * Filter the activity types to only return the ones we actually asked for
845 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
848 * @return array|null (Use in Activity.get API activity_type_id)
850 public static function filterActivityTypes($params) {
853 // If no activity types are specified, get all the active ones
854 if (empty($params['activity_type_id'])) {
855 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'get');
858 // If no activity types are specified or excluded, return the list of all active ones
859 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
860 if (!empty($activityTypes)) {
861 return ['IN' => array_keys($activityTypes)];
866 // If we have specified activity types, build a list to return, excluding the ones we don't want.
867 if (!empty($params['activity_type_id'])) {
868 if (!is_array($params['activity_type_id'])) {
869 // Turn it into array if only one specified, so we don't duplicate processing below
870 $params['activity_type_id'] = [$params['activity_type_id'] => $params['activity_type_id']];
872 foreach ($params['activity_type_id'] as $value) {
873 // Add each activity type that was specified to list
874 $value = CRM_Utils_Type
::escape($value, 'Positive');
875 $activityTypes[$value] = $value;
879 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
880 if (!empty($params['activity_type_exclude_id'])) {
881 if (!is_array($params['activity_type_exclude_id'])) {
882 // Turn it into array if only one specified, so we don't duplicate processing below
883 $params['activity_type_exclude_id'] = [$params['activity_type_exclude_id'] => $params['activity_type_exclude_id']];
885 foreach ($params['activity_type_exclude_id'] as $value) {
886 // Remove each activity type from list if it should be excluded
887 $value = CRM_Utils_Type
::escape($value, 'Positive');
888 if (array_key_exists($value, $activityTypes)) {
889 unset($activityTypes[$value]);
894 return ['IN' => array_keys($activityTypes)];
900 public function addSelectWhereClause() {
902 $permittedActivityTypeIDs = self
::getPermittedActivityTypes();
903 $allActivityTypes = self
::buildOptions('activity_type_id');
904 if (empty($permittedActivityTypeIDs)) {
905 // This just prevents a mysql fail if they have no access - should be extremely edge case.
906 $permittedActivityTypeIDs = [0];
908 if (array_keys($allActivityTypes) !== array_keys($permittedActivityTypeIDs)) {
909 $clauses['activity_type_id'] = ('IN (' . implode(', ', $permittedActivityTypeIDs) . ')');
912 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
913 if ($contactClause) {
914 $contactClause = implode(' AND contact_id ', $contactClause);
915 $clauses['id'][] = "IN (SELECT activity_id FROM civicrm_activity_contact WHERE contact_id $contactClause)";
917 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
922 * Get an array of components that are accessible by the currenct user.
924 * This means checking if they are enabled and if the user has appropriate permission.
926 * For most components the permission is access component (e.g 'access CiviContribute').
927 * Exceptions as CiviCampaign (administer CiviCampaign) and CiviCase
928 * (accesses a case function which enforces edit all cases or edit my cases. Case
929 * permissions are also handled on a per activity basis).
931 * Checks whether logged in user has permission to the component.
933 * @param bool $excludeComponentHandledActivities
934 * Should we exclude components whose display is handled in the components.
935 * In practice this means should we include CiviCase in the results. Presumbaly
936 * at the time it was decided case activities should be shown in the case framework and
937 * that this concept might be extended later. In practice most places that
938 * call this then re-add CiviCase in some way so it's all a bit... odd.
941 * Array of component id and name.
943 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
945 $compInfo = CRM_Core_Component
::getEnabledComponents();
946 foreach ($compInfo as $compObj) {
947 $includeComponent = !$excludeComponentHandledActivities ||
!empty($compObj->info
['showActivitiesInCore']);
948 if ($includeComponent) {
949 if ($compObj->info
['name'] == 'CiviCampaign') {
950 $componentPermission = "administer {$compObj->name}";
953 $componentPermission = "access {$compObj->name}";
955 if ($compObj->info
['name'] == 'CiviCase') {
956 if (CRM_Case_BAO_Case
::accessCiviCase()) {
957 $components[$compObj->componentID
] = $compObj->info
['name'];
960 elseif (CRM_Core_Permission
::check($componentPermission)) {
961 $components[$compObj->componentID
] = $compObj->info
['name'];
970 * Get the activity Count.
972 * @param array $input
973 * Array of parameters.
975 * - contact_id int contact_id whose activities we want to retrieve
976 * - admin boolean if contact is admin
977 * - caseId int case ID
978 * - context string page on which selector is build
979 * - activity_type_id int|string the activity types we want to restrict by
982 * count of activities
984 public static function getActivitiesCount($input) {
985 $activityParams = self
::getActivityParamsForDashboardFunctions($input);
986 return civicrm_api3('Activity', 'getcount', $activityParams);
990 * @param int $sourceContactID
991 * The contact ID of the email "from".
992 * @param string $subject
993 * @param string $html
994 * @param string $text
995 * @param string $additionalDetails
996 * The additional information of CC and BCC appended to the activity details.
997 * @param int $campaignID
998 * @param array $attachments
1002 * The created activity ID
1003 * @throws \CRM_Core_Exception
1005 public static function createEmailActivity($sourceContactID, $subject, $html, $text, $additionalDetails, $campaignID, $attachments, $caseID) {
1006 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
1008 // CRM-6265: save both text and HTML parts in details (if present)
1009 if ($html and $text) {
1010 $details = "-ALTERNATIVE ITEM 0-\n{$html}{$additionalDetails}\n-ALTERNATIVE ITEM 1-\n{$text}{$additionalDetails}\n-ALTERNATIVE END-\n";
1013 $details = $html ?
$html : $text;
1014 $details .= $additionalDetails;
1018 'source_contact_id' => $sourceContactID,
1019 'activity_type_id' => $activityTypeID,
1020 'activity_date_time' => date('YmdHis'),
1021 'subject' => $subject,
1022 'details' => $details,
1023 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1024 'campaign_id' => $campaignID,
1026 if (!empty($caseID)) {
1027 $activityParams['case_id'] = $caseID;
1030 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1031 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1033 // add the attachments to activity params here
1035 // first process them
1036 $activityParams = array_merge($activityParams, $attachments);
1039 $activity = civicrm_api3('Activity', 'create', $activityParams);
1041 return $activity['id'];
1045 * Send the message to all the contacts.
1047 * Also insert a contact activity in each contacts record.
1049 * @param array $contactDetails
1050 * The array of contact details to send the email.
1051 * @param string $subject
1052 * The subject of the message.
1055 * @param string $emailAddress
1056 * Use this 'to' email address instead of the default Primary address.
1057 * @param int $userID
1058 * Use this userID if set.
1059 * @param string $from
1060 * @param array $attachments
1061 * The array of attachments if any.
1064 * @param string $bcc
1066 * @param array $contactIds
1068 * @param string $additionalDetails
1069 * The additional information of CC and BCC appended to the activity Details.
1070 * @param array $contributionIds
1071 * @param int $campaignId
1072 * @param int $caseId
1075 * ( sent, activityId) if any email is sent and activityId
1076 * @throws \CRM_Core_Exception
1077 * @throws \CiviCRM_API3_Exception
1079 public static function sendEmail(
1087 $attachments = NULL,
1091 $additionalDetails = NULL,
1092 $contributionIds = NULL,
1096 // get the contact details of logged in contact, which we set as from email
1097 if ($userID == NULL) {
1098 $userID = CRM_Core_Session
::getLoggedInContactID();
1101 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1103 return [count($contactDetails), 0, count($contactDetails)];
1105 if (!trim($fromDisplayName)) {
1106 $fromDisplayName = $fromEmail;
1110 // token replacement of addressee/email/postal greetings
1111 // get the tokens added in subject and message
1112 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1113 $messageToken = CRM_Utils_Token
::getTokens($text);
1114 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1115 $allTokens = array_merge($messageToken, $subjectToken);
1118 $from = "$fromDisplayName <$fromEmail>";
1121 //create the meta level record first ( email activity )
1122 $activityID = self
::createEmailActivity($userID, $subject, $html, $text, $additionalDetails, $campaignId, $attachments, $caseId);
1124 $returnProperties = [];
1125 if (isset($messageToken['contact'])) {
1126 foreach ($messageToken['contact'] as $key => $value) {
1127 $returnProperties[$value] = 1;
1131 if (isset($subjectToken['contact'])) {
1132 foreach ($subjectToken['contact'] as $key => $value) {
1133 if (!isset($returnProperties[$value])) {
1134 $returnProperties[$value] = 1;
1139 // get token details for contacts, call only if tokens are used
1141 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1142 list($details) = CRM_Utils_Token
::getTokenDetails(
1147 'CRM_Activity_BAO_Activity'
1153 CRM_Utils_Hook
::tokens($tokens);
1154 $categories = array_keys($tokens);
1156 $escapeSmarty = FALSE;
1157 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1158 $smarty = CRM_Core_Smarty
::singleton();
1159 $escapeSmarty = TRUE;
1162 $contributionDetails = [];
1163 if (!empty($contributionIds)) {
1164 $contributionDetails = CRM_Contribute_BAO_Contribution
::replaceContributionTokens(
1175 $sent = $notSent = [];
1176 foreach ($contactDetails as $values) {
1177 $contactId = $values['contact_id'];
1178 $emailAddress = $values['email'];
1180 if (!empty($contributionDetails)) {
1181 $subject = $contributionDetails[$contactId]['subject'];
1182 $text = $contributionDetails[$contactId]['text'];
1183 $html = $contributionDetails[$contactId]['html'];
1186 if (!empty($details) && is_array($details["{$contactId}"])) {
1187 // unset email from details since it always returns primary email address
1188 unset($details["{$contactId}"]['email']);
1189 unset($details["{$contactId}"]['email_id']);
1190 $values = array_merge($values, $details["{$contactId}"]);
1193 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1194 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1197 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1198 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1199 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1205 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1206 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1207 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1214 $tokenSubject = CRM_Utils_Token
::replaceCaseTokens($caseId, $tokenSubject, $subjectToken, $escapeSmarty);
1215 $tokenText = CRM_Utils_Token
::replaceCaseTokens($caseId, $tokenText, $messageToken, $escapeSmarty);
1216 $tokenHtml = CRM_Utils_Token
::replaceCaseTokens($caseId, $tokenHtml, $messageToken, $escapeSmarty);
1219 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1220 // also add the contact tokens to the template
1221 $smarty->assign_by_ref('contact', $values);
1223 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1224 $tokenText = $smarty->fetch("string:$tokenText");
1225 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1229 if (self
::sendMessage(
1238 // get the set of attachments from where they are stored
1239 CRM_Core_BAO_File
::getEntityFile('civicrm_activity', $activityID),
1248 return [$sent, $activityID];
1252 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1254 * @param array $contactDetails
1255 * @param array $activityParams
1256 * @param array $smsProviderParams
1257 * @param array $contactIds
1258 * @param int $sourceContactId This is the source contact Id
1260 * @return array(bool $sent, int $activityId, int $success)
1261 * @throws CRM_Core_Exception
1263 public static function sendSMS(
1264 &$contactDetails = NULL,
1266 &$smsProviderParams = [],
1267 &$contactIds = NULL,
1268 $sourceContactId = NULL
1270 if (!CRM_Core_Permission
::check('send SMS')) {
1271 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1274 if (!isset($contactDetails) && !isset($contactIds)) {
1275 throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1277 // Populate $contactDetails and $contactIds if only one is set
1278 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1279 foreach ($contactIds as $id) {
1281 $contactDetails[] = civicrm_api3('Contact', 'getsingle', ['contact_id' => $id]);
1283 catch (Exception
$e) {
1284 // Contact Id doesn't exist
1288 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1289 foreach ($contactDetails as $contact) {
1290 $contactIds[] = $contact['contact_id'];
1294 // Get logged in User Id
1295 if (empty($sourceContactId)) {
1296 $sourceContactId = CRM_Core_Session
::getLoggedInContactID();
1299 $text = &$activityParams['sms_text_message'];
1301 // Create the meta level record first ( sms activity )
1303 'source_contact_id' => $sourceContactId,
1304 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
1305 'activity_date_time' => date('YmdHis'),
1306 'subject' => $activityParams['activity_subject'],
1308 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1310 $activity = self
::create($activityParams);
1311 $activityID = $activity->id
;
1314 // token replacement of addressee/email/postal greetings
1315 // get the tokens added in subject and message
1316 $messageToken = CRM_Utils_Token
::getTokens($text);
1317 $returnProperties = [];
1318 if (isset($messageToken['contact'])) {
1319 foreach ($messageToken['contact'] as $key => $value) {
1320 $returnProperties[$value] = 1;
1325 CRM_Utils_Hook
::tokens($tokens);
1326 $categories = array_keys($tokens);
1327 // get token details for contacts, call only if tokens are used
1329 if (!empty($returnProperties) ||
!empty($tokens)) {
1330 list($tokenDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
1334 'CRM_Activity_BAO_Activity'
1340 foreach ($contactDetails as $contact) {
1341 $contactId = $contact['contact_id'];
1344 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
1345 // unset phone from details since it always returns primary number
1346 unset($tokenDetails["{$contactId}"]['phone']);
1347 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1348 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
1350 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1351 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1353 // Only send if the phone is of type mobile
1354 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1355 $smsProviderParams['To'] = $contact['phone'];
1358 $smsProviderParams['To'] = '';
1361 $doNotSms = $contact['do_not_sms'] ??
0;
1364 $errMsgs[] = PEAR
::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN
);
1368 $sendResult = self
::sendSMSMessage(
1377 catch (CRM_Core_Exception
$e) {
1378 $errMsgs[] = $e->getMessage();
1383 // If at least one message was sent and no errors
1384 // were generated then return a boolean value of TRUE.
1385 // Otherwise, return FALSE (no messages sent) or
1386 // and array of 1 or more PEAR_Error objects.
1388 if ($success > 0 && count($errMsgs) == 0) {
1391 elseif (count($errMsgs) > 0) {
1395 return [$sent, $activity->id
, $success];
1399 * Send the sms message to a specific contact.
1402 * The contact id of the recipient.
1404 * @param array $smsProviderParams
1405 * The params used for sending sms.
1406 * @param int $activityID
1407 * The activity ID that tracks the message.
1408 * @param int $sourceContactID
1410 * @return bool true on success
1411 * @throws CRM_Core_Exception
1413 public static function sendSMSMessage(
1416 $smsProviderParams = [],
1418 $sourceContactID = NULL
1420 $toPhoneNumber = NULL;
1421 if ($smsProviderParams['To']) {
1422 // If phone number is specified use it
1423 $toPhoneNumber = trim($smsProviderParams['To']);
1426 // No phone number specified, so find a suitable one for the contact
1427 $filters = ['is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0];
1428 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1429 // To get primary mobile phonenumber, if not get the first mobile phonenumber
1430 if (!empty($toPhoneNumbers)) {
1431 $toPhoneNumberDetails = reset($toPhoneNumbers);
1432 $toPhoneNumber = $toPhoneNumberDetails['phone'] ??
NULL;
1433 // Contact allows to send sms
1437 // make sure both phone are valid
1438 // and that the recipient wants to receive sms
1439 if (empty($toPhoneNumber)) {
1440 throw new CRM_Core_Exception('Recipient phone number is invalid or recipient does not want to receive SMS');
1443 $recipient = $toPhoneNumber;
1444 $smsProviderParams['contact_id'] = $toID;
1445 $smsProviderParams['parent_activity_id'] = $activityID;
1447 $providerObj = CRM_SMS_Provider
::singleton(['provider_id' => $smsProviderParams['provider_id']]);
1448 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
1449 if (PEAR
::isError($sendResult)) {
1450 throw new CRM_Core_Exception($sendResult->getMessage());
1453 // add activity target record for every sms that is sent
1454 $targetID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
1455 $activityTargetParams = [
1456 'activity_id' => $activityID,
1457 'contact_id' => $toID,
1458 'record_type_id' => $targetID,
1460 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1466 * Send the message to a specific contact.
1468 * @param string $from
1469 * The name and email of the sender.
1470 * @param int $fromID
1472 * The contact id of the recipient.
1473 * @param string $subject
1474 * The subject of the message.
1475 * @param $text_message
1476 * @param $html_message
1477 * @param string $emailAddress
1478 * Use this 'to' email address instead of the default Primary address.
1479 * @param int $activityID
1480 * The activity ID that tracks the message.
1481 * @param null $attachments
1486 * TRUE if successful else FALSE.
1488 public static function sendMessage(
1497 $attachments = NULL,
1501 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1502 if ($emailAddress) {
1503 $toEmail = trim($emailAddress);
1506 // make sure both email addresses are valid
1507 // and that the recipient wants to receive email
1508 if (empty($toEmail) or $toDoNotEmail) {
1511 if (!trim($toDisplayName)) {
1512 $toDisplayName = $toEmail;
1515 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1516 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1518 // create the params array
1520 'groupName' => 'Activity Email Sender',
1522 'toName' => $toDisplayName,
1523 'toEmail' => $toEmail,
1524 'subject' => $subject,
1527 'text' => $text_message,
1528 'html' => $html_message,
1529 'attachments' => $attachments,
1532 if (!CRM_Utils_Mail
::send($mailParams)) {
1536 // add activity target record for every mail that is send
1537 $activityTargetParams = [
1538 'activity_id' => $activityID,
1539 'contact_id' => $toID,
1540 'record_type_id' => $targetID,
1542 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1547 * Combine all the importable fields from the lower levels object.
1549 * The ordering is important, since currently we do not have a weight
1550 * scheme. Adding weight is super important and should be done in the
1551 * next week or so, before this can be called complete.
1553 * @param bool $status
1556 * array of importable Fields
1558 public static function &importableFields($status = FALSE) {
1559 if (!self
::$_importableFields) {
1560 if (!self
::$_importableFields) {
1561 self
::$_importableFields = [];
1564 $fields = ['' => ['title' => ts('- do not import -')]];
1567 $fields = ['' => ['title' => ts('- Activity Fields -')]];
1570 $tmpFields = CRM_Activity_DAO_Activity
::import();
1571 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1573 // Using new Dedupe rule.
1575 'contact_type' => 'Individual',
1576 'used' => 'Unsupervised',
1578 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1580 $tmpConatctField = [];
1581 if (is_array($fieldsArray)) {
1582 foreach ($fieldsArray as $value) {
1583 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1588 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1589 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1590 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1593 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1594 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1595 $fields = array_merge($fields, $tmpConatctField);
1596 $fields = array_merge($fields, $tmpFields);
1597 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1598 self
::$_importableFields = $fields;
1600 return self
::$_importableFields;
1604 * @deprecated - use the api instead.
1606 * Get the Activities of a target contact.
1608 * @param int $contactId
1609 * Id of the contact whose activities need to find.
1612 * array of activity fields
1614 public static function getContactActivity($contactId) {
1615 // @todo remove this function entirely.
1617 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1618 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1619 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1620 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1622 // First look for activities where contactId is one of the targets
1624 SELECT activity_id, record_type_id
1625 FROM civicrm_activity_contact
1626 WHERE contact_id = $contactId
1628 $dao = CRM_Core_DAO
::executeQuery($query);
1629 while ($dao->fetch()) {
1630 if ($dao->record_type_id
== $targetID) {
1631 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1633 elseif ($dao->record_type_id
== $assigneeID) {
1634 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1637 // do source stuff here
1638 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1642 $activityIds = array_keys($activities);
1643 if (count($activityIds) < 1) {
1647 $activityIds = implode(',', $activityIds);
1649 SELECT activity.id as activity_id,
1651 subject, location, activity_date_time, details, status_id
1652 FROM civicrm_activity activity
1653 WHERE activity.id IN ($activityIds)";
1655 $dao = CRM_Core_DAO
::executeQuery($query);
1657 while ($dao->fetch()) {
1658 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1659 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1660 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1661 $activities[$dao->activity_id
]['location'] = $dao->location
;
1662 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1663 $activities[$dao->activity_id
]['details'] = $dao->details
;
1664 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1665 $activities[$dao->activity_id
]['activity_name'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id
);
1666 $activities[$dao->activity_id
]['status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id
);
1668 // set to null if not set
1669 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1670 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1677 * Add activity for Membership/Event/Contribution.
1679 * @param object $activity
1680 * particular component object.
1681 * @param string $activityType
1682 * For Membership Signup or Renewal.
1683 * @param int $targetContactID
1684 * @param array $params
1685 * Activity params to override.
1689 public static function addActivity(
1692 $targetContactID = NULL,
1695 $date = date('YmdHis');
1696 if ($activity->__table
== 'civicrm_contribution') {
1697 // create activity record only for Completed Contributions
1698 $contributionCompletedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1699 if ($activity->contribution_status_id
!= $contributionCompletedStatusId) {
1700 //For onbehalf payments, create a scheduled activity.
1701 if (empty($params['on_behalf'])) {
1704 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
1707 // retrieve existing activity based on source_record_id and activity_type
1708 if (empty($params['id'])) {
1709 $params['id'] = CRM_Utils_Array
::value('id', civicrm_api3('Activity', 'Get', [
1710 'source_record_id' => $activity->id
,
1711 'activity_type_id' => $activityType,
1714 if (!empty($params['id'])) {
1715 // CRM-13237 : if activity record found, update it with campaign id of contribution
1716 $params['campaign_id'] = $activity->campaign_id
;
1719 $date = $activity->receive_date
;
1723 'source_contact_id' => $activity->contact_id
,
1724 'source_record_id' => $activity->id
,
1725 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1726 'activity_date_time' => $date,
1727 'is_test' => $activity->is_test
,
1728 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1729 'skipRecentView' => TRUE,
1730 'campaign_id' => $activity->campaign_id
,
1732 $activityParams = array_merge($activityParams, $params);
1734 if (empty($activityParams['subject'])) {
1735 $activityParams['subject'] = self
::getActivitySubject($activity);
1738 if (!empty($activity->activity_id
)) {
1739 $activityParams['id'] = $activity->activity_id
;
1741 // create activity with target contacts
1742 $id = CRM_Core_Session
::getLoggedInContactID();
1744 $activityParams['source_contact_id'] = $id;
1745 $activityParams['target_contact_id'][] = $activity->contact_id
;
1749 if (property_exists($activity, 'details')) {
1750 $activityParams['details'] = $activity->details
;
1753 if ($targetContactID) {
1754 $activityParams['target_contact_id'][] = $targetContactID;
1756 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
1757 // deal with any exceptions.
1758 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1759 throw new CRM_Core_Exception("Failed creating Activity of type $activityType for entity id {$activity->id}");
1764 * Get activity subject on basis of component object.
1766 * @param object $entityObj
1767 * particular component object.
1770 * @throws \CRM_Core_Exception
1772 public static function getActivitySubject($entityObj) {
1773 // @todo determine the subject on the appropriate entity rather than from the activity.
1774 switch ($entityObj->__table
) {
1775 case 'civicrm_membership':
1776 $membershipType = CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $entityObj->membership_type_id
);
1777 $subject = $membershipType ?
: ts('Membership');
1779 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
1780 $subject .= " - {$entityObj->source}";
1783 if ($entityObj->owner_membership_id
) {
1784 list($displayName) = CRM_Contact_BAO_Contact
::getDisplayAndImage(CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id
, 'contact_id'));
1785 $subject .= sprintf(' (by %s)', $displayName);
1788 $subject .= ' - Status: ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'status_id', $entityObj->status_id
);
1791 case 'civicrm_participant':
1792 $event = CRM_Event_BAO_Event
::getEvents(1, $entityObj->event_id
, TRUE, FALSE);
1793 $roles = CRM_Event_PseudoConstant
::participantRole();
1794 $status = CRM_Event_PseudoConstant
::participantStatus();
1795 $subject = $event[$entityObj->event_id
];
1797 if (!empty($roles[$entityObj->role_id
])) {
1798 $subject .= ' - ' . $roles[$entityObj->role_id
];
1800 if (!empty($status[$entityObj->status_id
])) {
1801 $subject .= ' - ' . $status[$entityObj->status_id
];
1806 case 'civicrm_contribution':
1807 $subject = CRM_Utils_Money
::format($entityObj->total_amount
, $entityObj->currency
);
1808 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
1809 $subject .= " - {$entityObj->source}";
1812 // Amount and source could exceed max length of subject column.
1813 return CRM_Utils_String
::ellipsify($subject, 255);
1818 * Get Parent activity for currently viewed activity.
1820 * @param int $activityId
1821 * Current activity id.
1824 * Id of parent activity otherwise false.
1825 * @throws \CRM_Core_Exception
1827 public static function getParentActivity($activityId) {
1828 static $parentActivities = [];
1830 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1832 if (!array_key_exists($activityId, $parentActivities)) {
1833 $parentActivities[$activityId] = [];
1835 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1840 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1843 return $parentActivities[$activityId];
1847 * Get total count of prior revision of currently viewed activity.
1849 * @param $activityID
1850 * Current activity id.
1853 * $params count of prior activities otherwise false.
1854 * @throws \CRM_Core_Exception
1856 public static function getPriorCount($activityID) {
1857 CRM_Core_Error
::deprecatedFunctionWarning('unused function to be removed');
1858 static $priorCounts = [];
1860 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1862 if (!array_key_exists($activityID, $priorCounts)) {
1863 $priorCounts[$activityID] = [];
1864 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1871 SELECT count( id ) AS cnt
1872 FROM civicrm_activity
1873 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1874 AND is_current_revision = 0
1875 AND id < {$activityID}
1877 $params = [1 => [$originalID, 'Integer']];
1878 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1880 $priorCounts[$activityID] = $count ?
$count : 0;
1883 return $priorCounts[$activityID];
1887 * Get all prior activities of currently viewed activity.
1889 * @param $activityID
1890 * Current activity id.
1891 * @param bool $onlyPriorRevisions
1894 * prior activities info.
1895 * @throws \CRM_Core_Exception
1897 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1898 static $priorActivities = [];
1900 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1901 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1903 if (!array_key_exists($index, $priorActivities)) {
1904 $priorActivities[$index] = [];
1906 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1911 $originalID = $activityID;
1915 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1916 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1917 WHERE (ca.id = %1 OR ca.original_id = %1)
1918 AND cl.entity_table = 'civicrm_activity'
1919 AND cl.entity_id = ca.id
1920 AND cl.modified_id = c.id
1922 if ($onlyPriorRevisions) {
1923 $query .= " AND ca.id < {$activityID}";
1925 $query .= " ORDER BY ca.id DESC";
1927 $params = [1 => [$originalID, 'Integer']];
1928 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1930 while ($dao->fetch()) {
1931 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1932 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1933 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1937 return $priorActivities[$index];
1941 * Find the latest revision of a given activity.
1943 * @param int $activityID
1944 * Prior activity id.
1947 * current activity id.
1949 * @throws \CRM_Core_Exception
1951 public static function getLatestActivityId($activityID) {
1952 static $latestActivityIds = [];
1954 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1956 if (!array_key_exists($activityID, $latestActivityIds)) {
1957 $latestActivityIds[$activityID] = [];
1959 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1964 $activityID = $originalID;
1966 $params = [1 => [$activityID, 'Integer']];
1967 $query = 'SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1';
1969 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
1972 return $latestActivityIds[$activityID];
1976 * Create a follow up a given activity.
1978 * @param int $activityId
1979 * activity id of parent activity.
1980 * @param array $params
1982 * @return CRM_Activity_BAO_Activity|null|object
1984 * @throws \CRM_Core_Exception
1986 public static function createFollowupActivity($activityId, $params) {
1991 $followupParams = [];
1992 $followupParams['parent_id'] = $activityId;
1993 $followupParams['source_contact_id'] = CRM_Core_Session
::getLoggedInContactID();
1994 $followupParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
1996 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1997 // Get Subject of Follow-up Activiity, CRM-4491
1998 $followupParams['subject'] = $params['followup_activity_subject'] ??
NULL;
1999 $followupParams['assignee_contact_id'] = $params['followup_assignee_contact_id'] ??
NULL;
2001 // Create target contact for followup.
2002 if (!empty($params['target_contact_id'])) {
2003 $followupParams['target_contact_id'] = $params['target_contact_id'];
2006 $followupParams['activity_date_time'] = $params['followup_date'];
2007 $followupActivity = self
::create($followupParams);
2009 return $followupActivity;
2013 * Get Activity specific File according activity type Id.
2015 * @param int $activityTypeId
2017 * @param string $crmDir
2019 * @return string|bool
2020 * if file exists returns $activityTypeFile activity filename otherwise false.
2022 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2023 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2025 if ($activityTypes[$activityTypeId]['name']) {
2026 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2032 global $civicrm_root;
2033 $config = CRM_Core_Config
::singleton();
2034 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2035 if (empty($config->customPHPPathDir
)) {
2038 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2043 return $activityTypeFile;
2047 * Restore the activity.
2049 * @param array $params
2051 * @return CRM_Activity_DAO_Activity
2053 public static function restoreActivity(&$params) {
2054 $activity = new CRM_Activity_DAO_Activity();
2055 $activity->copyValues($params);
2057 $activity->is_deleted
= 0;
2058 $result = $activity->save();
2064 * Return list of activity statuses of a given type.
2066 * Note: activity status options use the "grouping" field to distinguish status types.
2067 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2072 * @throws \CiviCRM_API3_Exception
2074 public static function getStatusesByType($type) {
2075 if (!isset(Civi
::$statics[__CLASS__
][__FUNCTION__
])) {
2076 $statuses = civicrm_api3('OptionValue', 'get', [
2077 'option_group_id' => 'activity_status',
2078 'return' => ['value', 'name', 'filter'],
2079 'options' => ['limit' => 0],
2081 Civi
::$statics[__CLASS__
][__FUNCTION__
] = $statuses['values'];
2084 foreach (Civi
::$statics[__CLASS__
][__FUNCTION__
] as $status) {
2085 if ($status['filter'] == $type) {
2086 $ret[$status['value']] = $status['name'];
2093 * Check if activity is overdue.
2095 * @param array $activity
2098 * @throws \CiviCRM_API3_Exception
2100 public static function isOverdue($activity) {
2101 return array_key_exists($activity['status_id'], self
::getStatusesByType(self
::INCOMPLETE
)) && CRM_Utils_Date
::overdue($activity['activity_date_time']);
2105 * Get the exportable fields for Activities.
2107 * @param string $name
2108 * If it is called by case $name = Case else $name = Activity.
2111 * array of exportable Fields
2113 public static function exportableFields($name = 'Activity') {
2114 self
::$_exportableFields[$name] = [];
2116 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2117 $exportableFields = CRM_Activity_DAO_Activity
::export();
2118 $exportableFields['source_contact_id'] = [
2119 'title' => ts('Source Contact ID'),
2120 'type' => CRM_Utils_Type
::T_INT
,
2122 $exportableFields['source_contact'] = [
2123 'title' => ts('Source Contact'),
2124 'type' => CRM_Utils_Type
::T_STRING
,
2127 // @todo - remove these - they are added by CRM_Core_DAO::appendPseudoConstantsToFields
2128 // below. That search label stuff is referenced in search builder but is likely just
2129 // a hack that duplicates, maybe differently, other functionality.
2131 'activity_type' => [
2132 'title' => ts('Activity Type'),
2133 'name' => 'activity_type',
2134 'type' => CRM_Utils_Type
::T_STRING
,
2135 'searchByLabel' => TRUE,
2137 'activity_status' => [
2138 'title' => ts('Activity Status'),
2139 'name' => 'activity_status',
2140 'type' => CRM_Utils_Type
::T_STRING
,
2141 'searchByLabel' => TRUE,
2143 'activity_priority' => [
2144 'title' => ts('Activity Priority'),
2145 'name' => 'activity_priority',
2146 'type' => CRM_Utils_Type
::T_STRING
,
2147 'searchByLabel' => TRUE,
2150 $fields = array_merge($activityFields, $exportableFields);
2151 $fields['activity_priority_id'] = $fields['priority_id'];
2153 if ($name === 'Case') {
2154 // Now add "case_activity" fields
2155 // Set title to activity fields.
2156 $caseActivityFields = [
2157 'case_source_contact_id' => [
2158 'title' => ts('Activity Reporter'),
2159 'type' => CRM_Utils_Type
::T_STRING
,
2161 'case_activity_date_time' => [
2162 'title' => ts('Activity Date'),
2163 'type' => CRM_Utils_Type
::T_DATE
,
2165 'case_activity_type' => [
2166 'title' => ts('Activity Type'),
2167 'type' => CRM_Utils_Type
::T_STRING
,
2169 'case_activity_medium_id' => [
2170 'title' => ts('Activity Medium'),
2171 'type' => CRM_Utils_Type
::T_INT
,
2173 'case_activity_is_auto' => [
2174 'title' => ts('Activity Auto-generated?'),
2175 'type' => CRM_Utils_Type
::T_BOOLEAN
,
2178 $caseStandardFields = ['activity_subject', 'activity_status', 'activity_duration', 'activity_details'];
2179 foreach ($caseStandardFields as $key) {
2180 $caseActivityFields['case_' . $key] = $fields[$key];
2182 $fields = $caseActivityFields;
2185 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2186 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
2187 self
::$_exportableFields[$name] = $fields;
2188 return self
::$_exportableFields[$name];
2192 * Get the allowed profile fields for Activities.
2195 * array of activity profile Fields
2197 public static function getProfileFields() {
2198 $exportableFields = self
::exportableFields('Activity');
2202 'source_contact_id',
2204 'activity_campaign',
2206 'is_current_revision',
2207 'activity_is_deleted',
2209 $config = CRM_Core_Config
::singleton();
2210 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2211 $skipFields[] = 'activity_engagement_level';
2214 foreach ($skipFields as $field) {
2215 if (isset($exportableFields[$field])) {
2216 unset($exportableFields[$field]);
2220 // hack to use 'activity_type_id' instead of 'activity_type'
2221 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2222 unset($exportableFields['activity_status']);
2224 return $exportableFields;
2228 * This function deletes the activity record related to contact record.
2230 * This is conditional on there being no target and assignee record
2231 * with other contacts.
2233 * @param int $contactId
2238 public static function cleanupActivity($contactId) {
2243 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2244 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2246 $transaction = new CRM_Core_Transaction();
2248 // delete activity if there is no record in civicrm_activity_contact
2249 // pointing to any other contact record
2250 $activityContact = new CRM_Activity_DAO_ActivityContact();
2251 $activityContact->contact_id
= $contactId;
2252 $activityContact->record_type_id
= $sourceID;
2253 $activityContact->find();
2255 while ($activityContact->fetch()) {
2256 // delete activity_contact record for the deleted contact
2257 $activityContact->delete();
2259 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2260 $activityContactOther->activity_id
= $activityContact->activity_id
;
2262 // delete activity only if no other contacts connected
2263 if (!$activityContactOther->find(TRUE)) {
2264 $activityParams = ['id' => $activityContact->activity_id
];
2265 $result = self
::deleteActivity($activityParams);
2270 $transaction->commit();
2276 * Does user has sufficient permission for view/edit activity record.
2278 * @param int $activityId
2279 * Activity record id.
2280 * @param int $action
2285 public static function checkPermission($activityId, $action) {
2288 !in_array($action, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
])
2293 $activity = new CRM_Activity_DAO_Activity();
2294 $activity->id
= $activityId;
2295 if (!$activity->find(TRUE)) {
2299 if (!self
::hasPermissionForActivityType($activity->activity_type_id
)) {
2300 // this check is redundant for api access / anything that calls the selectWhereClause
2301 // to determine ACLs.
2304 // Return early when it is case activity.
2305 // Check for CiviCase related permission.
2306 if (CRM_Case_BAO_Case
::isCaseActivity($activityId)) {
2307 return self
::isContactPermittedAccessToCaseActivity($activityId, $action, $activity->activity_type_id
);
2310 // Check for this permission related to contact.
2311 $permission = CRM_Core_Permission
::VIEW
;
2312 if ($action == CRM_Core_Action
::UPDATE
) {
2313 $permission = CRM_Core_Permission
::EDIT
;
2316 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2317 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2318 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2319 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2321 // Check for source contact.
2322 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2323 // Account for possibility of activity not having a source contact (as it may have been deleted).
2324 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission) : TRUE;
2329 // Check for target and assignee contacts.
2330 // First check for supper permission.
2331 $supPermission = 'view all contacts';
2332 if ($action == CRM_Core_Action
::UPDATE
) {
2333 $supPermission = 'edit all contacts';
2335 $allow = CRM_Core_Permission
::check($supPermission);
2337 // User might have sufficient permission, through acls.
2340 // Get the target contacts.
2341 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2342 foreach ($targetContacts as $cnt => $contactId) {
2343 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2349 // Get the assignee contacts.
2351 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2352 foreach ($assigneeContacts as $cnt => $contactId) {
2353 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2365 * Check if the logged in user has permission for the given case activity.
2367 * @param int $activityId
2368 * @param int $action
2369 * @param int $activityTypeID
2373 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
2375 if ($action == CRM_Core_Action
::UPDATE
) {
2378 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2387 * Check if the logged in user has permission to access the given activity type.
2389 * @param int $activityTypeID
2393 protected static function hasPermissionForActivityType($activityTypeID) {
2394 $permittedActivityTypes = self
::getPermittedActivityTypes();
2395 return isset($permittedActivityTypes[$activityTypeID]);
2399 * Get the activity types the user is permitted to access.
2401 * The types are filtered by the components they have access to. ie. a user
2402 * with access CiviContribute but not CiviMember will see contribution related
2403 * activities and activities with no component (e.g meetings) but not member related ones.
2407 protected static function getPermittedActivityTypes() {
2408 $userID = (int) CRM_Core_Session
::getLoggedInContactID();
2409 if (!isset(Civi
::$statics[__CLASS__
]['permitted_activity_types'][$userID])) {
2410 $permittedActivityTypes = [];
2411 $components = self
::activityComponents(FALSE);
2412 $componentClause = empty($components) ?
'' : (' OR component_id IN (' . implode(', ', array_keys($components)) . ')');
2414 $types = CRM_Core_DAO
::executeQuery(
2416 SELECT option_value.value activity_type_id
2417 FROM civicrm_option_value option_value
2418 INNER JOIN civicrm_option_group grp ON (grp.id = option_group_id AND grp.name = 'activity_type')
2419 WHERE component_id IS NULL $componentClause")->fetchAll();
2420 foreach ($types as $type) {
2421 $permittedActivityTypes[$type['activity_type_id']] = (int) $type['activity_type_id'];
2423 asort($permittedActivityTypes);
2424 Civi
::$statics[__CLASS__
]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2426 return Civi
::$statics[__CLASS__
]['permitted_activity_types'][$userID];
2433 protected static function getActivityParamsForDashboardFunctions($params) {
2436 'is_current_revision' => 1,
2438 'contact_id' => $params['contact_id'] ??
NULL,
2439 'activity_date_time' => $params['activity_date_time'] ??
NULL,
2440 'check_permissions' => 1,
2442 'offset' => $params['offset'] ??
0,
2446 if (!empty($params['activity_status_id'])) {
2447 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2450 $activityParams['activity_type_id'] = self
::filterActivityTypes($params);
2451 $enabledComponents = self
::activityComponents();
2452 // @todo - this appears to be duplicating the activity api.
2453 if (!in_array('CiviCase', $enabledComponents)) {
2454 $activityParams['case_id'] = ['IS NULL' => 1];
2456 return $activityParams;
2460 * Checks if user has permissions to edit inbound e-mails, either basic info
2461 * or both basic information and content.
2465 public static function checkEditInboundEmailsPermissions() {
2466 if (CRM_Core_Permission
::check('edit inbound email basic information')
2467 || CRM_Core_Permission
::check('edit inbound email basic information and content')
2476 * Get the list of view only activities
2480 public static function getViewOnlyActivityTypeIDs() {
2481 $viewOnlyActivities = [
2482 'Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
2484 if (self
::checkEditInboundEmailsPermissions()) {
2485 $viewOnlyActivities['Inbound Email'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
2487 return $viewOnlyActivities;
2491 * Wrapper for ajax activity selector.
2493 * @param array $params
2494 * Associated array for params record id.
2497 * Associated array of contact activities
2499 public static function getContactActivitySelector(&$params) {
2500 // Format the params.
2501 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2502 $params['rowCount'] = $params['rp'];
2503 $params['sort'] = $params['sortBy'] ??
NULL;
2504 $params['caseId'] = NULL;
2505 $context = $params['context'] ??
NULL;
2506 $showContactOverlay = !CRM_Utils_String
::startsWith($context, "dashlet");
2507 $activityTypeInfo = civicrm_api3('OptionValue', 'get', [
2508 'option_group_id' => "activity_type",
2509 'options' => ['limit' => 0],
2511 $activityIcons = [];
2512 foreach ($activityTypeInfo['values'] as $type) {
2513 if (!empty($type['icon'])) {
2514 $activityIcons[$type['value']] = $type['icon'];
2517 CRM_Utils_Date
::convertFormDateToApiFormat($params, 'activity_date_time');
2519 // Get contact activities.
2520 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2523 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2525 // Format params and add links.
2526 $contactActivities = [];
2528 // View-only activity types
2529 $viewOnlyCaseActivityTypeIDs = array_flip(CRM_Activity_BAO_Activity
::getViewOnlyActivityTypeIDs());
2531 if (!empty($activities)) {
2532 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2534 // Check logged in user for permission.
2535 $page = new CRM_Core_Page();
2536 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2537 $permissions = [$page->_permission
];
2538 if (CRM_Core_Permission
::check('delete activities')) {
2539 $permissions[] = CRM_Core_Permission
::DELETE
;
2542 $mask = CRM_Core_Action
::mask($permissions);
2543 $userID = CRM_Core_Session
::getLoggedInContactID();
2545 foreach ($activities as $activityId => $values) {
2546 $activity = ['source_contact_name' => '', 'target_contact_name' => ''];
2547 $activity['DT_RowId'] = $activityId;
2548 // Add class to this row if overdue.
2549 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2550 if (self
::isOverdue($values)) {
2551 $activity['DT_RowClass'] .= ' status-overdue';
2554 $activity['DT_RowClass'] .= ' status-ontime';
2557 $activity['DT_RowAttr'] = [];
2558 $activity['DT_RowAttr']['data-entity'] = 'activity';
2559 $activity['DT_RowAttr']['data-id'] = $activityId;
2561 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ?
'<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '" aria-hidden="true"></span> ' : '') . $values['activity_type'];
2562 $activity['subject'] = $values['subject'];
2564 if ($params['contact_id'] == $values['source_contact_id']) {
2565 $activity['source_contact_name'] = $values['source_contact_name'];
2567 elseif ($values['source_contact_id']) {
2569 if ($showContactOverlay) {
2570 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2571 CRM_Contact_BAO_Contact
::getContactType($values['source_contact_id']),
2573 $values['source_contact_id']);
2575 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System
::href($values['source_contact_name'],
2576 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2579 $activity['source_contact_name'] = '<em>n/a</em>';
2582 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2583 $activity['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2584 'civicrm/mailing/report/event',
2585 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2587 elseif (!empty($values['recipients'])) {
2588 $activity['target_contact_name'] = $values['recipients'];
2590 elseif (isset($values['target_contact_count']) && $values['target_contact_count']) {
2591 $activity['target_contact_name'] = '';
2592 $firstTargetName = reset($values['target_contact_name']);
2593 $firstTargetContactID = key($values['target_contact_name']);
2595 // The first target may not be accessable to the logged in user dev/core#1052
2596 if ($firstTargetName) {
2597 $targetLink = CRM_Utils_System
::href($firstTargetName, 'civicrm/contact/view', "reset=1&cid={$firstTargetContactID}");
2598 if ($showContactOverlay) {
2599 $targetTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2600 CRM_Contact_BAO_Contact
::getContactType($firstTargetContactID),
2602 $firstTargetContactID);
2603 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2606 $activity['target_contact_name'] .= $targetLink;
2609 if ($extraCount = $values['target_contact_count'] - 1) {
2610 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', [1 => $extraCount]) . ")";
2612 if ($showContactOverlay) {
2613 $activity['target_contact_name'] .= "</div> ";
2617 elseif (!$values['target_contact_name']) {
2618 $activity['target_contact_name'] = '<em>n/a</em>';
2621 $activity['assignee_contact_name'] = '';
2622 if (empty($values['assignee_contact_name'])) {
2623 $activity['assignee_contact_name'] = '<em>n/a</em>';
2625 elseif (!empty($values['assignee_contact_name'])) {
2627 $activity['assignee_contact_name'] = '';
2628 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2629 if ($acID && $count < 5) {
2630 $assigneeTypeImage = "";
2631 $assigneeLink = CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2632 if ($showContactOverlay) {
2633 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2634 CRM_Contact_BAO_Contact
::getContactType($acID),
2637 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2640 $activity['assignee_contact_name'] .= $assigneeLink;
2645 $activity['assignee_contact_name'] .= "; ";
2647 if ($showContactOverlay) {
2648 $activity['assignee_contact_name'] .= "</div> ";
2652 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2659 $activity['activity_date_time'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2660 $activity['status_id'] = $activityStatus[$values['status_id']];
2663 $activity['links'] = '';
2664 $accessMailingReport = FALSE;
2665 if (!empty($values['mailingId'])) {
2666 $accessMailingReport = TRUE;
2669 // Get action links.
2671 // If this is a case activity, then we hand off to Case's actionLinks instead.
2672 if (!empty($values['case_id']) && Civi
::settings()->get('civicaseShowCaseActivities')) {
2673 // This activity belongs to a case.
2674 $caseId = current($values['case_id']);
2676 $activity['subject'] = $values['subject'];
2678 // Get the view and edit (update) links:
2680 $actionLinks = array_intersect_key(
2681 CRM_Case_Selector_Search
::actionLinks(),
2682 array_fill_keys([CRM_Core_Action
::VIEW
, CRM_Core_Action
::UPDATE
], NULL));
2684 // Create a Manage Case link (using ADVANCED as can't use two VIEW ones)
2685 $actionLinks[CRM_Core_Action
::ADVANCED
] = [
2686 "name" => 'Manage Case',
2687 "url" => 'civicrm/contact/view/case',
2688 'qs' => 'reset=1&id=%%caseid%%&cid=%%cid%%&action=view&context=&selectedChild=case',
2689 "title" => ts('Manage Case %1', [1 => $caseId]),
2690 'class' => 'no-popup',
2694 'aid' => $activityId,
2695 'caseid' => $caseId,
2696 'cid' => current(CRM_Case_BAO_Case
::getCaseClients($caseId) ??
[]),
2697 // Unlike other 'context' params, this 'ctx' param is appended raw to the URL.
2701 $caseActivityPermissions = CRM_Core_Action
::VIEW | CRM_Core_Action
::ADVANCED
;
2702 // Allow Edit link if:
2703 // 1. Activity type is NOT view-only type. CRM-5871
2704 // 2. User has edit permission.
2705 if (!isset($viewOnlyCaseActivityTypeIDs[$values['activity_type_id']])
2706 && CRM_Case_BAO_Case
::checkPermission($activityId, 'edit', $values['activity_type_id'], $userID)) {
2707 // We're allowed to edit.
2708 $caseActivityPermissions |
= CRM_Core_Action
::UPDATE
;
2711 $activity['links'] = CRM_Core_Action
::formLink($actionLinks,
2712 $caseActivityPermissions,
2718 $values['activity_id']
2722 // Non-case activity
2723 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2724 CRM_Utils_Array
::value('activity_type_id', $values),
2725 CRM_Utils_Array
::value('source_record_id', $values),
2726 $accessMailingReport,
2727 CRM_Utils_Array
::value('activity_id', $values)
2729 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2731 $activity['links'] = CRM_Core_Action
::formLink($actionLinks,
2734 'id' => $values['activity_id'],
2735 'cid' => $params['contact_id'],
2743 $values['activity_id']
2747 if ($values['is_recurring_activity']) {
2748 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2751 array_push($contactActivities, $activity);
2756 $activitiesDT['data'] = $contactActivities;
2757 $activitiesDT['recordsTotal'] = $params['total'];
2758 $activitiesDT['recordsFiltered'] = $params['total'];
2760 return $activitiesDT;
2764 * Copy custom fields and attachments from an existing activity to another.
2766 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2768 * @param array $params
2770 public static function copyExtendedActivityData($params) {
2771 // attach custom data to the new activity
2772 $customParams = $htmlType = [];
2773 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2775 if (!empty($customValues)) {
2776 $fieldIds = implode(', ', array_keys($customValues));
2777 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2778 $result = CRM_Core_DAO
::executeQuery($sql);
2780 while ($result->fetch()) {
2781 $htmlType[] = $result->id
;
2784 foreach ($customValues as $key => $value) {
2785 if ($value !== NULL) {
2787 if (in_array($key, $htmlType)) {
2788 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2789 $customParams["custom_{$key}_-1"] = [
2790 'name' => $fileValues[0],
2791 'type' => $fileValues[1],
2795 $customParams["custom_{$key}_-1"] = $value;
2799 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_activity',
2800 $params['mainActivityId'], 'Activity'
2804 // copy activity attachments ( if any )
2805 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2809 * Get activity contact.
2811 * @param int $activityId
2812 * @param int $recordTypeID
2813 * @param string $column
2817 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2818 $activityContact = new CRM_Activity_BAO_ActivityContact();
2819 $activityContact->activity_id
= $activityId;
2820 if ($recordTypeID) {
2821 $activityContact->record_type_id
= $recordTypeID;
2823 if ($activityContact->find(TRUE)) {
2824 return $activityContact->$column;
2830 * Get source contact id.
2832 * @param int $activityId
2836 public static function getSourceContactID($activityId) {
2837 static $sourceID = NULL;
2839 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2840 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2843 return self
::getActivityContact($activityId, $sourceID);
2849 * @todo Document what this is for.
2851 * @param array $params
2853 public function setApiFilter(&$params) {
2854 if (!empty($params['target_contact_id'])) {
2856 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2857 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2858 $obj = new CRM_Activity_BAO_ActivityContact();
2859 $params['return.target_contact_id'] = 1;
2860 $this->joinAdd($obj, 'LEFT');
2861 $this->selectAdd('civicrm_activity.*');
2862 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
2867 * Send activity as attachment.
2869 * @param object $activity
2870 * @param array $mailToContacts
2871 * @param array $params
2875 public static function sendToAssignee($activity, $mailToContacts, $params = []) {
2876 if (!CRM_Utils_Array
::crmIsEmptyArray($mailToContacts)) {
2877 $clientID = $params['client_id'] ??
NULL;
2878 $caseID = $params['case_id'] ??
NULL;
2880 $ics = new CRM_Activity_BAO_ICalendar($activity);
2881 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity', $activity->id
);
2882 $ics->addAttachment($attachments, $mailToContacts);
2884 $result = CRM_Case_BAO_Case
::sendActivityCopy($clientID, $activity->id
, $mailToContacts, $attachments, $caseID);
2894 public static function getEntityRefFilters() {
2896 ['key' => 'activity_type_id', 'value' => ts('Activity Type')],
2897 ['key' => 'status_id', 'value' => ts('Activity Status')],