Merge pull request #18536 from eileenmcnaughton/main
[civicrm-core.git] / CRM / Activity / BAO / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 use Civi\Api4\ActivityContact;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19
20 /**
21 * This class is for activity functions.
22 */
23 class CRM_Activity_BAO_Activity extends CRM_Activity_DAO_Activity {
24
25 /**
26 * Activity status types
27 */
28 const
29 INCOMPLETE = 0,
30 COMPLETED = 1,
31 CANCELLED = 2;
32
33 /**
34 * Static field for all the activity information that we can potentially export.
35 *
36 * @var array
37 */
38 public static $_exportableFields = NULL;
39
40 /**
41 * Static field for all the activity information that we can potentially import.
42 *
43 * @var array
44 */
45 public static $_importableFields = NULL;
46
47 /**
48 * Check if there is absolute minimum of data to add the object.
49 *
50 * @param array $params
51 * (reference ) an assoc array of name/value pairs.
52 *
53 * @return bool
54 */
55 public static function dataExists(&$params) {
56 if (!empty($params['source_contact_id']) || !empty($params['id'])) {
57 return TRUE;
58 }
59 return FALSE;
60 }
61
62 /**
63 * @deprecated
64 *
65 * Fetch object based on array of properties.
66 *
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.
71 *
72 * @return CRM_Activity_DAO_Activity
73 */
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);
79
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);
85
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);
97 }
98 elseif (CRM_Core_Permission::check('access CiviMail') ||
99 (CRM_Mailing_Info::workflowEnabled() &&
100 CRM_Core_Permission::check('create mailings')
101 )
102 ) {
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"
105 );
106 }
107 else {
108 $defaults['target_contact_value'] = ts('(recipients)');
109 }
110
111 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
112 $defaults['source_contact_id'] = $sourceContactId;
113
114 if ($sourceContactId &&
115 !CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
116 $sourceContactId,
117 'is_deleted'
118 )
119 ) {
120 $defaults['source_contact'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
121 $sourceContactId,
122 'sort_name'
123 );
124 }
125
126 // Get case subject.
127 $defaults['case_subject'] = CRM_Case_BAO_Case::getCaseSubject($activity->id);
128
129 CRM_Core_DAO::storeValues($activity, $defaults);
130
131 return $activity;
132 }
133 return NULL;
134 }
135
136 /**
137 * Delete the activity.
138 *
139 * @param array $params
140 * @param bool $moveToTrash
141 *
142 * @return mixed
143 */
144 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
145 // CRM-9137
146 if (!empty($params['id']) && !is_array($params['id'])) {
147 CRM_Utils_Hook::pre('delete', 'Activity', $params['id'], $params);
148 }
149 else {
150 CRM_Utils_Hook::pre('delete', 'Activity', NULL, $params);
151 }
152
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']);
157 }
158 else {
159 $sourceRecordIds = $params['source_record_id'] ?? NULL;
160 }
161
162 if ($sourceRecordIds) {
163 $where[] = 'source_record_id IN ( %1 )';
164 $sqlWhereParams[1] = [$sourceRecordIds, 'CommaSeparatedIntegers'];
165 }
166 $result = NULL;
167 if (!$moveToTrash) {
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'];
172 }
173 $query = "DELETE FROM civicrm_activity WHERE " . implode(' AND ', $where);
174 $dao = CRM_Core_DAO::executeQuery($query, $sqlWhereParams);
175 }
176 else {
177 $activity = new CRM_Activity_DAO_Activity();
178 $activity->copyValues($params);
179 $result = $activity->delete();
180
181 // CRM-8708
182 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
183
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']]);
187
188 CRM_Core_BAO_File::deleteEntityFile('civicrm_activity', $activity->id);
189 }
190 }
191 else {
192 $activity = new CRM_Activity_DAO_Activity();
193 $activity->copyValues($params);
194
195 $activity->is_deleted = 1;
196 $result = $activity->save();
197
198 // CRM-4525 log activity delete
199 $logMsg = 'Case Activity deleted for';
200 $msgs = [];
201
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}";
209 }
210
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));
215 }
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));
220 }
221
222 $logMsg .= implode(', ', $msgs);
223
224 self::logActivityAction($activity, $logMsg);
225 }
226
227 // delete the recently created Activity
228 if ($result) {
229 $activityRecent = [
230 'id' => $activity->id,
231 'type' => 'Activity',
232 ];
233 CRM_Utils_Recent::del($activityRecent);
234 }
235
236 $transaction->commit();
237 if (isset($activity)) {
238 // CRM-8708
239 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
240 CRM_Utils_Hook::post('delete', 'Activity', $activity->id, $activity);
241 }
242
243 return $result;
244 }
245
246 /**
247 * Delete activity assignment record.
248 *
249 * @param int $activityId
250 * @param int $recordTypeID
251 */
252 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
253 $activityContact = new CRM_Activity_BAO_ActivityContact();
254 $activityContact->activity_id = $activityId;
255 if ($recordTypeID) {
256 $activityContact->record_type_id = $recordTypeID;
257 }
258
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();
264 }
265 }
266
267 /**
268 * Process the activities.
269 *
270 * @param array $params
271 * Associated array of the submitted values.
272 *
273 * @throws CRM_Core_Exception
274 *
275 * @return CRM_Activity_BAO_Activity|null|object
276 */
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']);
281
282 // check required params
283 if (!self::dataExists($params)) {
284 throw new CRM_Core_Exception('Not enough data to create activity object');
285 }
286
287 $activity = new CRM_Activity_DAO_Activity();
288
289 if (isset($params['id']) && empty($params['id'])) {
290 unset($params['id']);
291 }
292
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)
296 ) {
297 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed');
298 }
299 else {
300 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
301 }
302 }
303
304 // Set priority to Normal for Auto-populated activities (for Cases)
305 if (!isset($params['priority_id']) &&
306 // if not set and not 0
307 empty($params['id'])
308 ) {
309 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
310 $params['priority_id'] = array_search('Normal', $priority);
311 }
312
313 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
314 $params['target_contact_id'] = array_unique($params['target_contact_id']);
315 }
316 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
317 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
318 }
319
320 $action = empty($params['id']) ? 'create' : 'edit';
321 CRM_Utils_Hook::pre($action, 'Activity', $params['id'] ?? NULL, $params);
322
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'];
327 }
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);
331 }
332
333 // start transaction
334 $transaction = new CRM_Core_Transaction();
335
336 $result = $activity->save();
337
338 if (is_a($result, 'CRM_Core_Error')) {
339 $transaction->rollback();
340 return $result;
341 }
342
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');
347
348 $activityRecordTypes = [
349 'source_contact_id' => 'Activity Source',
350 'assignee_contact_id' => 'Activity Assignees',
351 'target_contact_id' => 'Activity Targets',
352 ];
353 $activityContacts = array_intersect_key($params, $activityRecordTypes);
354
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]);
361 }
362 }
363
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();
370 }
371 }
372
373 if (isset($params['source_contact_id'])) {
374 $acParams = [
375 'activity_id' => $activityId,
376 'contact_id' => $params['source_contact_id'],
377 'record_type_id' => $sourceID,
378 ];
379 CRM_Activity_BAO_ActivityContact::create($acParams);
380 }
381
382 // check and attach and files as needed
383 CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
384
385 // attempt to save activity assignment
386 $resultAssignment = NULL;
387 if (!empty($params['assignee_contact_id'])) {
388
389 $assignmentParams = ['activity_id' => $activityId];
390
391 if (is_array($params['assignee_contact_id'])) {
392 foreach ($params['assignee_contact_id'] as $acID) {
393 if ($acID) {
394 $assigneeParams = [
395 'activity_id' => $activityId,
396 'contact_id' => $acID,
397 'record_type_id' => $assigneeID,
398 ];
399 CRM_Activity_BAO_ActivityContact::create($assigneeParams);
400 }
401 }
402 }
403 else {
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);
411
412 if ($assignment->contact_id != $params['assignee_contact_id']) {
413 $assignmentParams['id'] = $assignment->id;
414 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
415 }
416 }
417 else {
418 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
419 }
420 }
421 }
422
423 if (is_a($resultAssignment, 'CRM_Core_Error')) {
424 $transaction->rollback();
425 return $resultAssignment;
426 }
427
428 // attempt to save activity targets
429 if (!empty($params['target_contact_id'])) {
430
431 $targetParams = ['activity_id' => $activityId];
432 if (is_array($params['target_contact_id'])) {
433
434 foreach ($params['target_contact_id'] as $tid) {
435 if ($tid) {
436 $targetContactParams = [
437 'activity_id' => $activityId,
438 'contact_id' => $tid,
439 'record_type_id' => $targetID,
440 ];
441 CRM_Activity_BAO_ActivityContact::create($targetContactParams);
442 }
443 }
444 }
445 else {
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;
452 $target->find(TRUE);
453
454 if ($target->contact_id != $params['target_contact_id']) {
455 $targetParams['id'] = $target->id;
456 CRM_Activity_BAO_ActivityContact::create($targetParams);
457 }
458 }
459 else {
460 CRM_Activity_BAO_ActivityContact::create($targetParams);
461 }
462 }
463 }
464
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 ";
469 }
470 else {
471 $logMsg = "Activity created for ";
472 }
473
474 $msgs = [];
475 if (isset($params['source_contact_id'])) {
476 $msgs[] = "source={$params['source_contact_id']}";
477 }
478
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];
486 }
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'];
493 }
494 }
495 else {
496 // at worst, take source for recently viewed display
497 $recentContactId = $params['source_contact_id'] ?? NULL;
498 }
499
500 if (isset($params['assignee_contact_id'])) {
501 if (is_array($params['assignee_contact_id'])) {
502 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
503 }
504 else {
505 $msgs[] = "assignee={$params['assignee_contact_id']}";
506 }
507 }
508 $logMsg .= implode(', ', $msgs);
509
510 self::logActivityAction($result, $logMsg);
511
512 if (!empty($params['custom']) &&
513 is_array($params['custom'])
514 ) {
515 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
516 }
517
518 $transaction->commit();
519 if (empty($params['skipRecentView'])) {
520 $recentOther = [];
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"
525 );
526 }
527 else {
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"
534 );
535 }
536 else {
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"
539 );
540 }
541
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"
545 );
546 }
547 }
548 else {
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"
553 );
554 }
555 }
556 }
557
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');
563
564 $title = "";
565 if (isset($activitySubject)) {
566 $title = $activitySubject . ' - ';
567 }
568
569 $title = $title . $recentContactDisplay;
570 if (!empty($activityTypes[$activity->activity_type_id])) {
571 $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')';
572 }
573
574 CRM_Utils_Recent::add($title,
575 $url,
576 $activity->id,
577 'Activity',
578 $recentContactId,
579 $recentContactDisplay,
580 $recentOther
581 );
582 }
583 }
584
585 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
586
587 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
588 $matches = [];
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);
592 $hash = $matches[1];
593 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '" . CRM_Core_DAO::escapeString($hash) . "'";
594 }
595 elseif (preg_match('/\[case #(\d+)\]/', $subjectToMatch, $matches)) {
596 $query = "SELECT id FROM civicrm_case WHERE id = '" . CRM_Core_DAO::escapeString($matches[1]) . "'";
597 }
598 if (!empty($matches)) {
599 $caseParams = [
600 'activity_id' => $activity->id,
601 'case_id' => CRM_Core_DAO::singleValueQuery($query),
602 ];
603 if ($caseParams['case_id']) {
604 CRM_Case_BAO_Case::processCaseActivity($caseParams);
605 }
606 else {
607 self::logActivityAction($activity, "Case details for {$matches[1]} not found while recording an activity on case.");
608 }
609 }
610 CRM_Utils_Hook::post($action, 'Activity', $activity->id, $activity);
611 return $result;
612 }
613
614 /**
615 * Create an activity.
616 *
617 * @todo elaborate on what this does.
618 *
619 * @param CRM_Activity_DAO_Activity $activity
620 * @param string $logMessage
621 *
622 * @return bool
623 */
624 public static function logActivityAction($activity, $logMessage = NULL) {
625 $id = CRM_Core_Session::getLoggedInContactID();
626 if (!$id) {
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);
630 }
631 $logParams = [
632 'entity_table' => 'civicrm_activity',
633 'entity_id' => $activity->id,
634 'modified_id' => $id,
635 'modified_date' => date('YmdHis'),
636 'data' => $logMessage,
637 ];
638 CRM_Core_BAO_Log::add($logParams);
639 return TRUE;
640 }
641
642 /**
643 * Get the list Activities.
644 *
645 * @param array $params
646 * Array of parameters.
647 * Keys include
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
656 *
657 * @return array
658 * Relevant data object values of open activities
659 * @throws \CiviCRM_API3_Exception
660 */
661 public static function getActivities($params) {
662 $activities = [];
663
664 // Activity.Get API params
665 $activityParams = self::getActivityParamsForDashboardFunctions($params);
666
667 if (!empty($params['rowCount']) &&
668 $params['rowCount'] > 0
669 ) {
670 $activityParams['options']['limit'] = $params['rowCount'];
671 }
672
673 if (!empty($params['sort'])) {
674 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
675 $order = $params['sort']->orderBy();
676 }
677 elseif (trim($params['sort'])) {
678 $order = CRM_Utils_Type::escape($params['sort'], 'String');
679 }
680 }
681
682 $activityParams['options']['sort'] = empty($order) ? "activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
683
684 $activityParams['return'] = [
685 'activity_date_time',
686 'source_record_id',
687 'source_contact_id',
688 'source_contact_name',
689 'assignee_contact_id',
690 'assignee_contact_name',
691 'status_id',
692 'subject',
693 'activity_type_id',
694 'activity_type',
695 'case_id',
696 'campaign_id',
697 ];
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;
704 }
705 }
706 $result = civicrm_api3('Activity', 'Get', $activityParams)['values'];
707
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);
710
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'))
715 );
716
717 // @todo - get rid of this & just handle in the array declaration like we do with 'subject' etc.
718 $mappingParams = [
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',
724 ];
725
726 if (empty($result)) {
727 $targetCount = [];
728 }
729 else {
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', [
737 1 => [
738 CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'),
739 'Integer',
740 ],
741 ])->fetchAll();
742 }
743 foreach ($targetCount as $activityTarget) {
744 $result[$activityTarget['activity_id']]['target_contact_count'] = $activityTarget['target_contact_count'];
745 }
746 // Iterate through & do basic mappings & determine which ones we want to retrieve target count for.
747 foreach ($result as $id => $activity) {
748 $activities[$id] = [
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,
755 ];
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'],
766 'sequential' => 1,
767 ])['values'];
768 if (empty($displayedTarget[0])) {
769 $activities[$id]['target_contact_name'] = [];
770 }
771 else {
772 $activities[$id]['target_contact_name'] = [$displayedTarget[0]['contact_id'] => $displayedTarget[0]['contact_id.sort_name']];
773 }
774 }
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']]);
779 }
780 }
781
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.
784 $caseIds = [];
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',
790 ])) {
791
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))
798 ) {
799 $activities[$id]['mailingId'] = TRUE;
800 }
801 }
802 }
803 // case related fields
804 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
805 $activities[$id][$expectedName] = $activity[$apiKey] ?? NULL;
806
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']);
812 }
813 }
814 else {
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;
819 }
820 }
821 }
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')
825 ) {
826 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
827 }
828 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getParentFor($id, 'civicrm_activity');
829 }
830
831 // Look up any case subjects we need in a single query and add them in the relevant activities under 'case_subject'
832 if ($caseIds) {
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];
837 }
838 }
839
840 return $activities;
841 }
842
843 /**
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']
846 *
847 * @param $params
848 * @return array|null (Use in Activity.get API activity_type_id)
849 */
850 public static function filterActivityTypes($params) {
851 $activityTypes = [];
852
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');
856 }
857
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)];
862 }
863 return NULL;
864 }
865
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']];
871 }
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;
876 }
877 }
878
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']];
884 }
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]);
890 }
891 }
892 }
893
894 return ['IN' => array_keys($activityTypes)];
895 }
896
897 /**
898 * @inheritDoc
899 */
900 public function addSelectWhereClause() {
901 $clauses = [];
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];
907 }
908 if (array_keys($allActivityTypes) !== array_keys($permittedActivityTypeIDs)) {
909 $clauses['activity_type_id'] = ('IN (' . implode(', ', $permittedActivityTypeIDs) . ')');
910 }
911
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)";
916 }
917 CRM_Utils_Hook::selectWhereClause($this, $clauses);
918 return $clauses;
919 }
920
921 /**
922 * Get an array of components that are accessible by the currenct user.
923 *
924 * This means checking if they are enabled and if the user has appropriate permission.
925 *
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).
930 *
931 * Checks whether logged in user has permission to the component.
932 *
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.
939 *
940 * @return array
941 * Array of component id and name.
942 */
943 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
944 $components = [];
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}";
951 }
952 else {
953 $componentPermission = "access {$compObj->name}";
954 }
955 if ($compObj->info['name'] == 'CiviCase') {
956 if (CRM_Case_BAO_Case::accessCiviCase()) {
957 $components[$compObj->componentID] = $compObj->info['name'];
958 }
959 }
960 elseif (CRM_Core_Permission::check($componentPermission)) {
961 $components[$compObj->componentID] = $compObj->info['name'];
962 }
963 }
964 }
965
966 return $components;
967 }
968
969 /**
970 * Get the activity Count.
971 *
972 * @param array $input
973 * Array of parameters.
974 * Keys include
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
980 *
981 * @return int
982 * count of activities
983 */
984 public static function getActivitiesCount($input) {
985 $activityParams = self::getActivityParamsForDashboardFunctions($input);
986 return civicrm_api3('Activity', 'getcount', $activityParams);
987 }
988
989 /**
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
999 * @param int $caseID
1000 *
1001 * @return int
1002 * The created activity ID
1003 * @throws \CRM_Core_Exception
1004 */
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');
1007
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";
1011 }
1012 else {
1013 $details = $html ? $html : $text;
1014 $details .= $additionalDetails;
1015 }
1016
1017 $activityParams = [
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,
1025 ];
1026 if (!empty($caseID)) {
1027 $activityParams['case_id'] = $caseID;
1028 }
1029
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']);
1032
1033 // add the attachments to activity params here
1034 if ($attachments) {
1035 // first process them
1036 $activityParams = array_merge($activityParams, $attachments);
1037 }
1038
1039 $activity = civicrm_api3('Activity', 'create', $activityParams);
1040
1041 return $activity['id'];
1042 }
1043
1044 /**
1045 * Send the message to all the contacts.
1046 *
1047 * Also insert a contact activity in each contacts record.
1048 *
1049 * @param array $contactDetails
1050 * The array of contact details to send the email.
1051 * @param string $subject
1052 * The subject of the message.
1053 * @param $text
1054 * @param $html
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.
1062 * @param string $cc
1063 * Cc recipient.
1064 * @param string $bcc
1065 * Bcc recipient.
1066 * @param array $contactIds
1067 * Contact ids.
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
1073 *
1074 * @return array
1075 * ( sent, activityId) if any email is sent and activityId
1076 * @throws \CRM_Core_Exception
1077 * @throws \CiviCRM_API3_Exception
1078 */
1079 public static function sendEmail(
1080 $contactDetails,
1081 $subject,
1082 $text,
1083 $html,
1084 $emailAddress,
1085 $userID = NULL,
1086 $from = NULL,
1087 $attachments = NULL,
1088 $cc = NULL,
1089 $bcc = NULL,
1090 $contactIds = NULL,
1091 $additionalDetails = NULL,
1092 $contributionIds = NULL,
1093 $campaignId = NULL,
1094 $caseId = NULL
1095 ) {
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();
1099 }
1100
1101 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1102 if (!$fromEmail) {
1103 return [count($contactDetails), 0, count($contactDetails)];
1104 }
1105 if (!trim($fromDisplayName)) {
1106 $fromDisplayName = $fromEmail;
1107 }
1108
1109 // CRM-4575
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);
1116
1117 if (!$from) {
1118 $from = "$fromDisplayName <$fromEmail>";
1119 }
1120
1121 //create the meta level record first ( email activity )
1122 $activityID = self::createEmailActivity($userID, $subject, $html, $text, $additionalDetails, $campaignId, $attachments, $caseId);
1123
1124 $returnProperties = [];
1125 if (isset($messageToken['contact'])) {
1126 foreach ($messageToken['contact'] as $key => $value) {
1127 $returnProperties[$value] = 1;
1128 }
1129 }
1130
1131 if (isset($subjectToken['contact'])) {
1132 foreach ($subjectToken['contact'] as $key => $value) {
1133 if (!isset($returnProperties[$value])) {
1134 $returnProperties[$value] = 1;
1135 }
1136 }
1137 }
1138
1139 // get token details for contacts, call only if tokens are used
1140 $details = [];
1141 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
1142 list($details) = CRM_Utils_Token::getTokenDetails(
1143 $contactIds,
1144 $returnProperties,
1145 NULL, NULL, FALSE,
1146 $allTokens,
1147 'CRM_Activity_BAO_Activity'
1148 );
1149 }
1150
1151 // call token hook
1152 $tokens = [];
1153 CRM_Utils_Hook::tokens($tokens);
1154 $categories = array_keys($tokens);
1155
1156 $escapeSmarty = FALSE;
1157 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1158 $smarty = CRM_Core_Smarty::singleton();
1159 $escapeSmarty = TRUE;
1160 }
1161
1162 $contributionDetails = [];
1163 if (!empty($contributionIds)) {
1164 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1165 $contributionIds,
1166 $subject,
1167 $subjectToken,
1168 $text,
1169 $html,
1170 $messageToken,
1171 $escapeSmarty
1172 );
1173 }
1174
1175 $sent = $notSent = [];
1176 foreach ($contactDetails as $values) {
1177 $contactId = $values['contact_id'];
1178 $emailAddress = $values['email'];
1179
1180 if (!empty($contributionDetails)) {
1181 $subject = $contributionDetails[$contactId]['subject'];
1182 $text = $contributionDetails[$contactId]['text'];
1183 $html = $contributionDetails[$contactId]['html'];
1184 }
1185
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}"]);
1191 }
1192
1193 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1194 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1195
1196 // CRM-4539
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);
1200 }
1201 else {
1202 $tokenText = NULL;
1203 }
1204
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);
1208 }
1209 else {
1210 $tokenHtml = NULL;
1211 }
1212
1213 if ($caseId) {
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);
1217 }
1218
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);
1222
1223 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1224 $tokenText = $smarty->fetch("string:$tokenText");
1225 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1226 }
1227
1228 $sent = FALSE;
1229 if (self::sendMessage(
1230 $from,
1231 $userID,
1232 $contactId,
1233 $tokenSubject,
1234 $tokenText,
1235 $tokenHtml,
1236 $emailAddress,
1237 $activityID,
1238 // get the set of attachments from where they are stored
1239 CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activityID),
1240 $cc,
1241 $bcc
1242 )
1243 ) {
1244 $sent = TRUE;
1245 }
1246 }
1247
1248 return [$sent, $activityID];
1249 }
1250
1251 /**
1252 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1253 *
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
1259 *
1260 * @return array(bool $sent, int $activityId, int $success)
1261 * @throws CRM_Core_Exception
1262 */
1263 public static function sendSMS(
1264 &$contactDetails = NULL,
1265 &$activityParams,
1266 &$smsProviderParams = [],
1267 &$contactIds = NULL,
1268 $sourceContactId = NULL
1269 ) {
1270 if (!CRM_Core_Permission::check('send SMS')) {
1271 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1272 }
1273
1274 if (!isset($contactDetails) && !isset($contactIds)) {
1275 throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1276 }
1277 // Populate $contactDetails and $contactIds if only one is set
1278 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1279 foreach ($contactIds as $id) {
1280 try {
1281 $contactDetails[] = civicrm_api3('Contact', 'getsingle', ['contact_id' => $id]);
1282 }
1283 catch (Exception $e) {
1284 // Contact Id doesn't exist
1285 }
1286 }
1287 }
1288 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1289 foreach ($contactDetails as $contact) {
1290 $contactIds[] = $contact['contact_id'];
1291 }
1292 }
1293
1294 // Get logged in User Id
1295 if (empty($sourceContactId)) {
1296 $sourceContactId = CRM_Core_Session::getLoggedInContactID();
1297 }
1298
1299 $text = &$activityParams['sms_text_message'];
1300
1301 // Create the meta level record first ( sms activity )
1302 $activityParams = [
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'],
1307 'details' => $text,
1308 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1309 ];
1310 $activity = self::create($activityParams);
1311 $activityID = $activity->id;
1312
1313 // Process Tokens
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;
1321 }
1322 }
1323 // Call tokens hook
1324 $tokens = [];
1325 CRM_Utils_Hook::tokens($tokens);
1326 $categories = array_keys($tokens);
1327 // get token details for contacts, call only if tokens are used
1328 $tokenDetails = [];
1329 if (!empty($returnProperties) || !empty($tokens)) {
1330 list($tokenDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
1331 $returnProperties,
1332 NULL, NULL, FALSE,
1333 $messageToken,
1334 'CRM_Activity_BAO_Activity'
1335 );
1336 }
1337
1338 $success = 0;
1339 $errMsgs = [];
1340 foreach ($contactDetails as $contact) {
1341 $contactId = $contact['contact_id'];
1342
1343 // Replace tokens
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}"]);
1349 }
1350 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1351 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1352
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'];
1356 }
1357 else {
1358 $smsProviderParams['To'] = '';
1359 }
1360
1361 $doNotSms = $contact['do_not_sms'] ?? 0;
1362
1363 if ($doNotSms) {
1364 $errMsgs[] = PEAR::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN);
1365 }
1366 else {
1367 try {
1368 $sendResult = self::sendSMSMessage(
1369 $contactId,
1370 $tokenText,
1371 $smsProviderParams,
1372 $activityID,
1373 $sourceContactId
1374 );
1375 $success++;
1376 }
1377 catch (CRM_Core_Exception $e) {
1378 $errMsgs[] = $e->getMessage();
1379 }
1380 }
1381 }
1382
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.
1387 $sent = FALSE;
1388 if ($success > 0 && count($errMsgs) == 0) {
1389 $sent = TRUE;
1390 }
1391 elseif (count($errMsgs) > 0) {
1392 $sent = $errMsgs;
1393 }
1394
1395 return [$sent, $activity->id, $success];
1396 }
1397
1398 /**
1399 * Send the sms message to a specific contact.
1400 *
1401 * @param int $toID
1402 * The contact id of the recipient.
1403 * @param $tokenText
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
1409 *
1410 * @return bool true on success
1411 * @throws CRM_Core_Exception
1412 */
1413 public static function sendSMSMessage(
1414 $toID,
1415 &$tokenText,
1416 $smsProviderParams = [],
1417 $activityID,
1418 $sourceContactID = NULL
1419 ) {
1420 $toPhoneNumber = NULL;
1421 if ($smsProviderParams['To']) {
1422 // If phone number is specified use it
1423 $toPhoneNumber = trim($smsProviderParams['To']);
1424 }
1425 elseif ($toID) {
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
1434 }
1435 }
1436
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');
1441 }
1442
1443 $recipient = $toPhoneNumber;
1444 $smsProviderParams['contact_id'] = $toID;
1445 $smsProviderParams['parent_activity_id'] = $activityID;
1446
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());
1451 }
1452
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,
1459 ];
1460 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1461
1462 return TRUE;
1463 }
1464
1465 /**
1466 * Send the message to a specific contact.
1467 *
1468 * @param string $from
1469 * The name and email of the sender.
1470 * @param int $fromID
1471 * @param int $toID
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
1482 * @param null $cc
1483 * @param null $bcc
1484 *
1485 * @return bool
1486 * TRUE if successful else FALSE.
1487 */
1488 public static function sendMessage(
1489 $from,
1490 $fromID,
1491 $toID,
1492 &$subject,
1493 &$text_message,
1494 &$html_message,
1495 $emailAddress,
1496 $activityID,
1497 $attachments = NULL,
1498 $cc = NULL,
1499 $bcc = NULL
1500 ) {
1501 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1502 if ($emailAddress) {
1503 $toEmail = trim($emailAddress);
1504 }
1505
1506 // make sure both email addresses are valid
1507 // and that the recipient wants to receive email
1508 if (empty($toEmail) or $toDoNotEmail) {
1509 return FALSE;
1510 }
1511 if (!trim($toDisplayName)) {
1512 $toDisplayName = $toEmail;
1513 }
1514
1515 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1516 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1517
1518 // create the params array
1519 $mailParams = [
1520 'groupName' => 'Activity Email Sender',
1521 'from' => $from,
1522 'toName' => $toDisplayName,
1523 'toEmail' => $toEmail,
1524 'subject' => $subject,
1525 'cc' => $cc,
1526 'bcc' => $bcc,
1527 'text' => $text_message,
1528 'html' => $html_message,
1529 'attachments' => $attachments,
1530 ];
1531
1532 if (!CRM_Utils_Mail::send($mailParams)) {
1533 return FALSE;
1534 }
1535
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,
1541 ];
1542 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1543 return TRUE;
1544 }
1545
1546 /**
1547 * Combine all the importable fields from the lower levels object.
1548 *
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.
1552 *
1553 * @param bool $status
1554 *
1555 * @return array
1556 * array of importable Fields
1557 */
1558 public static function &importableFields($status = FALSE) {
1559 if (!self::$_importableFields) {
1560 if (!self::$_importableFields) {
1561 self::$_importableFields = [];
1562 }
1563 if (!$status) {
1564 $fields = ['' => ['title' => ts('- do not import -')]];
1565 }
1566 else {
1567 $fields = ['' => ['title' => ts('- Activity Fields -')]];
1568 }
1569
1570 $tmpFields = CRM_Activity_DAO_Activity::import();
1571 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1572
1573 // Using new Dedupe rule.
1574 $ruleParams = [
1575 'contact_type' => 'Individual',
1576 'used' => 'Unsupervised',
1577 ];
1578 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1579
1580 $tmpConatctField = [];
1581 if (is_array($fieldsArray)) {
1582 foreach ($fieldsArray as $value) {
1583 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1584 $value,
1585 'id',
1586 'column_name'
1587 );
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)";
1591 }
1592 }
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;
1599 }
1600 return self::$_importableFields;
1601 }
1602
1603 /**
1604 * @deprecated - use the api instead.
1605 *
1606 * Get the Activities of a target contact.
1607 *
1608 * @param int $contactId
1609 * Id of the contact whose activities need to find.
1610 *
1611 * @return array
1612 * array of activity fields
1613 */
1614 public static function getContactActivity($contactId) {
1615 // @todo remove this function entirely.
1616 $activities = [];
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);
1621
1622 // First look for activities where contactId is one of the targets
1623 $query = "
1624 SELECT activity_id, record_type_id
1625 FROM civicrm_activity_contact
1626 WHERE contact_id = $contactId
1627 ";
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;
1632 }
1633 elseif ($dao->record_type_id == $assigneeID) {
1634 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1635 }
1636 else {
1637 // do source stuff here
1638 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
1639 }
1640 }
1641
1642 $activityIds = array_keys($activities);
1643 if (count($activityIds) < 1) {
1644 return [];
1645 }
1646
1647 $activityIds = implode(',', $activityIds);
1648 $query = "
1649 SELECT activity.id as activity_id,
1650 activity_type_id,
1651 subject, location, activity_date_time, details, status_id
1652 FROM civicrm_activity activity
1653 WHERE activity.id IN ($activityIds)";
1654
1655 $dao = CRM_Core_DAO::executeQuery($query);
1656
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);
1667
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;
1671 }
1672 }
1673 return $activities;
1674 }
1675
1676 /**
1677 * Add activity for Membership/Event/Contribution.
1678 *
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.
1686 *
1687 * @return bool|NULL
1688 */
1689 public static function addActivity(
1690 $activity,
1691 $activityType,
1692 $targetContactID = NULL,
1693 $params = []
1694 ) {
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'])) {
1702 return NULL;
1703 }
1704 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
1705 }
1706
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,
1712 ]));
1713 }
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;
1717 }
1718
1719 $date = $activity->receive_date;
1720 }
1721
1722 $activityParams = [
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,
1731 ];
1732 $activityParams = array_merge($activityParams, $params);
1733
1734 if (empty($activityParams['subject'])) {
1735 $activityParams['subject'] = self::getActivitySubject($activity);
1736 }
1737
1738 if (!empty($activity->activity_id)) {
1739 $activityParams['id'] = $activity->activity_id;
1740 }
1741 // create activity with target contacts
1742 $id = CRM_Core_Session::getLoggedInContactID();
1743 if ($id) {
1744 $activityParams['source_contact_id'] = $id;
1745 $activityParams['target_contact_id'][] = $activity->contact_id;
1746 }
1747
1748 // CRM-14945
1749 if (property_exists($activity, 'details')) {
1750 $activityParams['details'] = $activity->details;
1751 }
1752 //CRM-4027
1753 if ($targetContactID) {
1754 $activityParams['target_contact_id'][] = $targetContactID;
1755 }
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}");
1760 }
1761 }
1762
1763 /**
1764 * Get activity subject on basis of component object.
1765 *
1766 * @param object $entityObj
1767 * particular component object.
1768 *
1769 * @return string
1770 * @throws \CRM_Core_Exception
1771 */
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');
1778
1779 if (!CRM_Utils_System::isNull($entityObj->source)) {
1780 $subject .= " - {$entityObj->source}";
1781 }
1782
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);
1786 }
1787
1788 $subject .= ' - Status: ' . CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'status_id', $entityObj->status_id);
1789 return $subject;
1790
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];
1796
1797 if (!empty($roles[$entityObj->role_id])) {
1798 $subject .= ' - ' . $roles[$entityObj->role_id];
1799 }
1800 if (!empty($status[$entityObj->status_id])) {
1801 $subject .= ' - ' . $status[$entityObj->status_id];
1802 }
1803
1804 return $subject;
1805
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}";
1810 }
1811
1812 // Amount and source could exceed max length of subject column.
1813 return CRM_Utils_String::ellipsify($subject, 255);
1814 }
1815 }
1816
1817 /**
1818 * Get Parent activity for currently viewed activity.
1819 *
1820 * @param int $activityId
1821 * Current activity id.
1822 *
1823 * @return int
1824 * Id of parent activity otherwise false.
1825 * @throws \CRM_Core_Exception
1826 */
1827 public static function getParentActivity($activityId) {
1828 static $parentActivities = [];
1829
1830 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1831
1832 if (!array_key_exists($activityId, $parentActivities)) {
1833 $parentActivities[$activityId] = [];
1834
1835 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1836 $activityId,
1837 'parent_id'
1838 );
1839
1840 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1841 }
1842
1843 return $parentActivities[$activityId];
1844 }
1845
1846 /**
1847 * Get total count of prior revision of currently viewed activity.
1848 *
1849 * @param $activityID
1850 * Current activity id.
1851 * @deprecated
1852 * @return int
1853 * $params count of prior activities otherwise false.
1854 * @throws \CRM_Core_Exception
1855 */
1856 public static function getPriorCount($activityID) {
1857 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
1858 static $priorCounts = [];
1859
1860 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1861
1862 if (!array_key_exists($activityID, $priorCounts)) {
1863 $priorCounts[$activityID] = [];
1864 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1865 $activityID,
1866 'original_id'
1867 );
1868 $count = 0;
1869 if ($originalID) {
1870 $query = "
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}
1876 ";
1877 $params = [1 => [$originalID, 'Integer']];
1878 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1879 }
1880 $priorCounts[$activityID] = $count ? $count : 0;
1881 }
1882
1883 return $priorCounts[$activityID];
1884 }
1885
1886 /**
1887 * Get all prior activities of currently viewed activity.
1888 *
1889 * @param $activityID
1890 * Current activity id.
1891 * @param bool $onlyPriorRevisions
1892 *
1893 * @return array
1894 * prior activities info.
1895 * @throws \CRM_Core_Exception
1896 */
1897 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1898 static $priorActivities = [];
1899
1900 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1901 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1902
1903 if (!array_key_exists($index, $priorActivities)) {
1904 $priorActivities[$index] = [];
1905
1906 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1907 $activityID,
1908 'original_id'
1909 );
1910 if (!$originalID) {
1911 $originalID = $activityID;
1912 }
1913 if ($originalID) {
1914 $query = "
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
1921 ";
1922 if ($onlyPriorRevisions) {
1923 $query .= " AND ca.id < {$activityID}";
1924 }
1925 $query .= " ORDER BY ca.id DESC";
1926
1927 $params = [1 => [$originalID, 'Integer']];
1928 $dao = CRM_Core_DAO::executeQuery($query, $params);
1929
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;
1934 }
1935 }
1936 }
1937 return $priorActivities[$index];
1938 }
1939
1940 /**
1941 * Find the latest revision of a given activity.
1942 *
1943 * @param int $activityID
1944 * Prior activity id.
1945 *
1946 * @return int
1947 * current activity id.
1948 *
1949 * @throws \CRM_Core_Exception
1950 */
1951 public static function getLatestActivityId($activityID) {
1952 static $latestActivityIds = [];
1953
1954 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1955
1956 if (!array_key_exists($activityID, $latestActivityIds)) {
1957 $latestActivityIds[$activityID] = [];
1958
1959 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1960 $activityID,
1961 'original_id'
1962 );
1963 if ($originalID) {
1964 $activityID = $originalID;
1965 }
1966 $params = [1 => [$activityID, 'Integer']];
1967 $query = 'SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1';
1968
1969 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
1970 }
1971
1972 return $latestActivityIds[$activityID];
1973 }
1974
1975 /**
1976 * Create a follow up a given activity.
1977 *
1978 * @param int $activityId
1979 * activity id of parent activity.
1980 * @param array $params
1981 *
1982 * @return CRM_Activity_BAO_Activity|null|object
1983 *
1984 * @throws \CRM_Core_Exception
1985 */
1986 public static function createFollowupActivity($activityId, $params) {
1987 if (!$activityId) {
1988 return NULL;
1989 }
1990
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');
1995
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;
2000
2001 // Create target contact for followup.
2002 if (!empty($params['target_contact_id'])) {
2003 $followupParams['target_contact_id'] = $params['target_contact_id'];
2004 }
2005
2006 $followupParams['activity_date_time'] = $params['followup_date'];
2007 $followupActivity = self::create($followupParams);
2008
2009 return $followupActivity;
2010 }
2011
2012 /**
2013 * Get Activity specific File according activity type Id.
2014 *
2015 * @param int $activityTypeId
2016 * Activity id.
2017 * @param string $crmDir
2018 *
2019 * @return string|bool
2020 * if file exists returns $activityTypeFile activity filename otherwise false.
2021 */
2022 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2023 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2024
2025 if ($activityTypes[$activityTypeId]['name']) {
2026 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2027 }
2028 else {
2029 return FALSE;
2030 }
2031
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)) {
2036 return FALSE;
2037 }
2038 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2039 return FALSE;
2040 }
2041 }
2042
2043 return $activityTypeFile;
2044 }
2045
2046 /**
2047 * Restore the activity.
2048 *
2049 * @param array $params
2050 *
2051 * @return CRM_Activity_DAO_Activity
2052 */
2053 public static function restoreActivity(&$params) {
2054 $activity = new CRM_Activity_DAO_Activity();
2055 $activity->copyValues($params);
2056
2057 $activity->is_deleted = 0;
2058 $result = $activity->save();
2059
2060 return $result;
2061 }
2062
2063 /**
2064 * Return list of activity statuses of a given type.
2065 *
2066 * Note: activity status options use the "grouping" field to distinguish status types.
2067 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2068 *
2069 * @param int $type
2070 *
2071 * @return array
2072 * @throws \CiviCRM_API3_Exception
2073 */
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],
2080 ]);
2081 Civi::$statics[__CLASS__][__FUNCTION__] = $statuses['values'];
2082 }
2083 $ret = [];
2084 foreach (Civi::$statics[__CLASS__][__FUNCTION__] as $status) {
2085 if ($status['filter'] == $type) {
2086 $ret[$status['value']] = $status['name'];
2087 }
2088 }
2089 return $ret;
2090 }
2091
2092 /**
2093 * Check if activity is overdue.
2094 *
2095 * @param array $activity
2096 *
2097 * @return bool
2098 * @throws \CiviCRM_API3_Exception
2099 */
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']);
2102 }
2103
2104 /**
2105 * Get the exportable fields for Activities.
2106 *
2107 * @param string $name
2108 * If it is called by case $name = Case else $name = Activity.
2109 *
2110 * @return array
2111 * array of exportable Fields
2112 */
2113 public static function exportableFields($name = 'Activity') {
2114 self::$_exportableFields[$name] = [];
2115
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,
2121 ];
2122 $exportableFields['source_contact'] = [
2123 'title' => ts('Source Contact'),
2124 'type' => CRM_Utils_Type::T_STRING,
2125 ];
2126
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.
2130 $activityFields = [
2131 'activity_type' => [
2132 'title' => ts('Activity Type'),
2133 'name' => 'activity_type',
2134 'type' => CRM_Utils_Type::T_STRING,
2135 'searchByLabel' => TRUE,
2136 ],
2137 'activity_status' => [
2138 'title' => ts('Activity Status'),
2139 'name' => 'activity_status',
2140 'type' => CRM_Utils_Type::T_STRING,
2141 'searchByLabel' => TRUE,
2142 ],
2143 'activity_priority' => [
2144 'title' => ts('Activity Priority'),
2145 'name' => 'activity_priority',
2146 'type' => CRM_Utils_Type::T_STRING,
2147 'searchByLabel' => TRUE,
2148 ],
2149 ];
2150 $fields = array_merge($activityFields, $exportableFields);
2151 $fields['activity_priority_id'] = $fields['priority_id'];
2152
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,
2160 ],
2161 'case_activity_date_time' => [
2162 'title' => ts('Activity Date'),
2163 'type' => CRM_Utils_Type::T_DATE,
2164 ],
2165 'case_activity_type' => [
2166 'title' => ts('Activity Type'),
2167 'type' => CRM_Utils_Type::T_STRING,
2168 ],
2169 'case_activity_medium_id' => [
2170 'title' => ts('Activity Medium'),
2171 'type' => CRM_Utils_Type::T_INT,
2172 ],
2173 'case_activity_is_auto' => [
2174 'title' => ts('Activity Auto-generated?'),
2175 'type' => CRM_Utils_Type::T_BOOLEAN,
2176 ],
2177 ];
2178 $caseStandardFields = ['activity_subject', 'activity_status', 'activity_duration', 'activity_details'];
2179 foreach ($caseStandardFields as $key) {
2180 $caseActivityFields['case_' . $key] = $fields[$key];
2181 }
2182 $fields = $caseActivityFields;
2183 }
2184 // Add custom data
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];
2189 }
2190
2191 /**
2192 * Get the allowed profile fields for Activities.
2193 *
2194 * @return array
2195 * array of activity profile Fields
2196 */
2197 public static function getProfileFields() {
2198 $exportableFields = self::exportableFields('Activity');
2199 $skipFields = [
2200 'activity_id',
2201 'activity_type',
2202 'source_contact_id',
2203 'source_contact',
2204 'activity_campaign',
2205 'activity_is_test',
2206 'is_current_revision',
2207 'activity_is_deleted',
2208 ];
2209 $config = CRM_Core_Config::singleton();
2210 if (!in_array('CiviCampaign', $config->enableComponents)) {
2211 $skipFields[] = 'activity_engagement_level';
2212 }
2213
2214 foreach ($skipFields as $field) {
2215 if (isset($exportableFields[$field])) {
2216 unset($exportableFields[$field]);
2217 }
2218 }
2219
2220 // hack to use 'activity_type_id' instead of 'activity_type'
2221 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2222 unset($exportableFields['activity_status']);
2223
2224 return $exportableFields;
2225 }
2226
2227 /**
2228 * This function deletes the activity record related to contact record.
2229 *
2230 * This is conditional on there being no target and assignee record
2231 * with other contacts.
2232 *
2233 * @param int $contactId
2234 * ContactId.
2235 *
2236 * @return true/null
2237 */
2238 public static function cleanupActivity($contactId) {
2239 $result = NULL;
2240 if (!$contactId) {
2241 return $result;
2242 }
2243 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2244 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2245
2246 $transaction = new CRM_Core_Transaction();
2247
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();
2254
2255 while ($activityContact->fetch()) {
2256 // delete activity_contact record for the deleted contact
2257 $activityContact->delete();
2258
2259 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2260 $activityContactOther->activity_id = $activityContact->activity_id;
2261
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);
2266 }
2267
2268 }
2269
2270 $transaction->commit();
2271
2272 return $result;
2273 }
2274
2275 /**
2276 * Does user has sufficient permission for view/edit activity record.
2277 *
2278 * @param int $activityId
2279 * Activity record id.
2280 * @param int $action
2281 * Edit/view.
2282 *
2283 * @return bool
2284 */
2285 public static function checkPermission($activityId, $action) {
2286
2287 if (!$activityId ||
2288 !in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW])
2289 ) {
2290 return FALSE;
2291 }
2292
2293 $activity = new CRM_Activity_DAO_Activity();
2294 $activity->id = $activityId;
2295 if (!$activity->find(TRUE)) {
2296 return FALSE;
2297 }
2298
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.
2302 return FALSE;
2303 }
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);
2308 }
2309
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;
2314 }
2315
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);
2320
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;
2325 if (!$allow) {
2326 return FALSE;
2327 }
2328
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';
2334 }
2335 $allow = CRM_Core_Permission::check($supPermission);
2336
2337 // User might have sufficient permission, through acls.
2338 if (!$allow) {
2339 $allow = TRUE;
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)) {
2344 $allow = FALSE;
2345 break;
2346 }
2347 }
2348
2349 // Get the assignee contacts.
2350 if ($allow) {
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)) {
2354 $allow = FALSE;
2355 break;
2356 }
2357 }
2358 }
2359 }
2360
2361 return $allow;
2362 }
2363
2364 /**
2365 * Check if the logged in user has permission for the given case activity.
2366 *
2367 * @param int $activityId
2368 * @param int $action
2369 * @param int $activityTypeID
2370 *
2371 * @return bool
2372 */
2373 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
2374 $oper = 'view';
2375 if ($action == CRM_Core_Action::UPDATE) {
2376 $oper = 'edit';
2377 }
2378 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2379 $oper,
2380 $activityTypeID
2381 );
2382
2383 return $allow;
2384 }
2385
2386 /**
2387 * Check if the logged in user has permission to access the given activity type.
2388 *
2389 * @param int $activityTypeID
2390 *
2391 * @return bool
2392 */
2393 protected static function hasPermissionForActivityType($activityTypeID) {
2394 $permittedActivityTypes = self::getPermittedActivityTypes();
2395 return isset($permittedActivityTypes[$activityTypeID]);
2396 }
2397
2398 /**
2399 * Get the activity types the user is permitted to access.
2400 *
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.
2404 *
2405 * @return array
2406 */
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)) . ')');
2413
2414 $types = CRM_Core_DAO::executeQuery(
2415 "
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'];
2422 }
2423 asort($permittedActivityTypes);
2424 Civi::$statics[__CLASS__]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2425 }
2426 return Civi::$statics[__CLASS__]['permitted_activity_types'][$userID];
2427 }
2428
2429 /**
2430 * @param $params
2431 * @return array
2432 */
2433 protected static function getActivityParamsForDashboardFunctions($params) {
2434 $activityParams = [
2435 'is_deleted' => 0,
2436 'is_current_revision' => 1,
2437 'is_test' => 0,
2438 'contact_id' => $params['contact_id'] ?? NULL,
2439 'activity_date_time' => $params['activity_date_time'] ?? NULL,
2440 'check_permissions' => 1,
2441 'options' => [
2442 'offset' => $params['offset'] ?? 0,
2443 ],
2444 ];
2445
2446 if (!empty($params['activity_status_id'])) {
2447 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2448 }
2449
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];
2455 }
2456 return $activityParams;
2457 }
2458
2459 /**
2460 * Checks if user has permissions to edit inbound e-mails, either basic info
2461 * or both basic information and content.
2462 *
2463 * @return bool
2464 */
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')
2468 ) {
2469 return TRUE;
2470 }
2471
2472 return FALSE;
2473 }
2474
2475 /**
2476 * Get the list of view only activities
2477 *
2478 * @return array
2479 */
2480 public static function getViewOnlyActivityTypeIDs() {
2481 $viewOnlyActivities = [
2482 'Email' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
2483 ];
2484 if (self::checkEditInboundEmailsPermissions()) {
2485 $viewOnlyActivities['Inbound Email'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
2486 }
2487 return $viewOnlyActivities;
2488 }
2489
2490 /**
2491 * Wrapper for ajax activity selector.
2492 *
2493 * @param array $params
2494 * Associated array for params record id.
2495 *
2496 * @return array
2497 * Associated array of contact activities
2498 */
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],
2510 ]);
2511 $activityIcons = [];
2512 foreach ($activityTypeInfo['values'] as $type) {
2513 if (!empty($type['icon'])) {
2514 $activityIcons[$type['value']] = $type['icon'];
2515 }
2516 }
2517 CRM_Utils_Date::convertFormDateToApiFormat($params, 'activity_date_time');
2518
2519 // Get contact activities.
2520 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2521
2522 // Add total.
2523 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2524
2525 // Format params and add links.
2526 $contactActivities = [];
2527
2528 // View-only activity types
2529 $viewOnlyCaseActivityTypeIDs = array_flip(CRM_Activity_BAO_Activity::getViewOnlyActivityTypeIDs());
2530
2531 if (!empty($activities)) {
2532 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2533
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;
2540 }
2541
2542 $mask = CRM_Core_Action::mask($permissions);
2543 $userID = CRM_Core_Session::getLoggedInContactID();
2544
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';
2552 }
2553 else {
2554 $activity['DT_RowClass'] .= ' status-ontime';
2555 }
2556
2557 $activity['DT_RowAttr'] = [];
2558 $activity['DT_RowAttr']['data-entity'] = 'activity';
2559 $activity['DT_RowAttr']['data-id'] = $activityId;
2560
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'];
2563
2564 if ($params['contact_id'] == $values['source_contact_id']) {
2565 $activity['source_contact_name'] = $values['source_contact_name'];
2566 }
2567 elseif ($values['source_contact_id']) {
2568 $srcTypeImage = "";
2569 if ($showContactOverlay) {
2570 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2571 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2572 FALSE,
2573 $values['source_contact_id']);
2574 }
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']}");
2577 }
2578 else {
2579 $activity['source_contact_name'] = '<em>n/a</em>';
2580 }
2581
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");
2586 }
2587 elseif (!empty($values['recipients'])) {
2588 $activity['target_contact_name'] = $values['recipients'];
2589 }
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']);
2594
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),
2601 FALSE,
2602 $firstTargetContactID);
2603 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2604 }
2605 else {
2606 $activity['target_contact_name'] .= $targetLink;
2607 }
2608
2609 if ($extraCount = $values['target_contact_count'] - 1) {
2610 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', [1 => $extraCount]) . ")";
2611 }
2612 if ($showContactOverlay) {
2613 $activity['target_contact_name'] .= "</div> ";
2614 }
2615 }
2616 }
2617 elseif (!$values['target_contact_name']) {
2618 $activity['target_contact_name'] = '<em>n/a</em>';
2619 }
2620
2621 $activity['assignee_contact_name'] = '';
2622 if (empty($values['assignee_contact_name'])) {
2623 $activity['assignee_contact_name'] = '<em>n/a</em>';
2624 }
2625 elseif (!empty($values['assignee_contact_name'])) {
2626 $count = 0;
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),
2635 FALSE,
2636 $acID);
2637 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2638 }
2639 else {
2640 $activity['assignee_contact_name'] .= $assigneeLink;
2641 }
2642
2643 $count++;
2644 if ($count) {
2645 $activity['assignee_contact_name'] .= ";&nbsp;";
2646 }
2647 if ($showContactOverlay) {
2648 $activity['assignee_contact_name'] .= "</div> ";
2649 }
2650
2651 if ($count == 4) {
2652 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2653 break;
2654 }
2655 }
2656 }
2657 }
2658
2659 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2660 $activity['status_id'] = $activityStatus[$values['status_id']];
2661
2662 // build links
2663 $activity['links'] = '';
2664 $accessMailingReport = FALSE;
2665 if (!empty($values['mailingId'])) {
2666 $accessMailingReport = TRUE;
2667 }
2668
2669 // Get action links.
2670
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']);
2675
2676 $activity['subject'] = $values['subject'];
2677
2678 // Get the view and edit (update) links:
2679 $caseActionLinks =
2680 $actionLinks = array_intersect_key(
2681 CRM_Case_Selector_Search::actionLinks(),
2682 array_fill_keys([CRM_Core_Action::VIEW, CRM_Core_Action::UPDATE], NULL));
2683
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',
2691 ];
2692
2693 $caseLinkValues = [
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.
2698 'cxt' => '',
2699 ];
2700
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;
2709 }
2710
2711 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2712 $caseActivityPermissions,
2713 $caseLinkValues,
2714 ts('more'),
2715 FALSE,
2716 'activity.tab.row',
2717 'Activity',
2718 $values['activity_id']
2719 );
2720 }
2721 else {
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)
2728 );
2729 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2730
2731 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2732 $actionMask,
2733 [
2734 'id' => $values['activity_id'],
2735 'cid' => $params['contact_id'],
2736 'cxt' => $context,
2737 'caseid' => NULL,
2738 ],
2739 ts('more'),
2740 FALSE,
2741 'activity.tab.row',
2742 'Activity',
2743 $values['activity_id']
2744 );
2745 }
2746
2747 if ($values['is_recurring_activity']) {
2748 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2749 }
2750
2751 array_push($contactActivities, $activity);
2752 }
2753 }
2754
2755 $activitiesDT = [];
2756 $activitiesDT['data'] = $contactActivities;
2757 $activitiesDT['recordsTotal'] = $params['total'];
2758 $activitiesDT['recordsFiltered'] = $params['total'];
2759
2760 return $activitiesDT;
2761 }
2762
2763 /**
2764 * Copy custom fields and attachments from an existing activity to another.
2765 *
2766 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2767 *
2768 * @param array $params
2769 */
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');
2774
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);
2779
2780 while ($result->fetch()) {
2781 $htmlType[] = $result->id;
2782 }
2783
2784 foreach ($customValues as $key => $value) {
2785 if ($value !== NULL) {
2786 // CRM-10542
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],
2792 ];
2793 }
2794 else {
2795 $customParams["custom_{$key}_-1"] = $value;
2796 }
2797 }
2798 }
2799 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
2800 $params['mainActivityId'], 'Activity'
2801 );
2802 }
2803
2804 // copy activity attachments ( if any )
2805 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2806 }
2807
2808 /**
2809 * Get activity contact.
2810 *
2811 * @param int $activityId
2812 * @param int $recordTypeID
2813 * @param string $column
2814 *
2815 * @return null
2816 */
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;
2822 }
2823 if ($activityContact->find(TRUE)) {
2824 return $activityContact->$column;
2825 }
2826 return NULL;
2827 }
2828
2829 /**
2830 * Get source contact id.
2831 *
2832 * @param int $activityId
2833 *
2834 * @return null
2835 */
2836 public static function getSourceContactID($activityId) {
2837 static $sourceID = NULL;
2838 if (!$sourceID) {
2839 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2840 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2841 }
2842
2843 return self::getActivityContact($activityId, $sourceID);
2844 }
2845
2846 /**
2847 * Set api filter.
2848 *
2849 * @todo Document what this is for.
2850 *
2851 * @param array $params
2852 */
2853 public function setApiFilter(&$params) {
2854 if (!empty($params['target_contact_id'])) {
2855 $this->selectAdd();
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}");
2863 }
2864 }
2865
2866 /**
2867 * Send activity as attachment.
2868 *
2869 * @param object $activity
2870 * @param array $mailToContacts
2871 * @param array $params
2872 *
2873 * @return bool
2874 */
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;
2879
2880 $ics = new CRM_Activity_BAO_ICalendar($activity);
2881 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
2882 $ics->addAttachment($attachments, $mailToContacts);
2883
2884 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
2885 $ics->cleanup();
2886 return $result;
2887 }
2888 return FALSE;
2889 }
2890
2891 /**
2892 * @return array
2893 */
2894 public static function getEntityRefFilters() {
2895 return [
2896 ['key' => 'activity_type_id', 'value' => ts('Activity Type')],
2897 ['key' => 'status_id', 'value' => ts('Activity Status')],
2898 ];
2899 }
2900
2901 }