Merge pull request #17919 from seamuslee001/nfc_locale_documentation
[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 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class is for activity functions.
20 */
21 class CRM_Activity_BAO_Activity extends CRM_Activity_DAO_Activity {
22
23 /**
24 * Activity status types
25 */
26 const
27 INCOMPLETE = 0,
28 COMPLETED = 1,
29 CANCELLED = 2;
30
31 /**
32 * Static field for all the activity information that we can potentially export.
33 *
34 * @var array
35 */
36 public static $_exportableFields = NULL;
37
38 /**
39 * Static field for all the activity information that we can potentially import.
40 *
41 * @var array
42 */
43 public static $_importableFields = NULL;
44
45 /**
46 * Check if there is absolute minimum of data to add the object.
47 *
48 * @param array $params
49 * (reference ) an assoc array of name/value pairs.
50 *
51 * @return bool
52 */
53 public static function dataExists(&$params) {
54 if (!empty($params['source_contact_id']) || !empty($params['id'])) {
55 return TRUE;
56 }
57 return FALSE;
58 }
59
60 /**
61 * @deprecated
62 *
63 * Fetch object based on array of properties.
64 *
65 * @param array $params
66 * (reference ) an assoc array of name/value pairs.
67 * @param array $defaults
68 * (reference ) an assoc array to hold the flattened values.
69 *
70 * @return CRM_Activity_DAO_Activity
71 */
72 public static function retrieve(&$params, &$defaults) {
73 // this will bypass acls - use the api instead.
74 // @todo add deprecation logging to this function.
75 $activity = new CRM_Activity_DAO_Activity();
76 $activity->copyValues($params);
77
78 if ($activity->find(TRUE)) {
79 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
80 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
81 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
82 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
83
84 // TODO: at some stage we'll have to deal
85 // with multiple values for assignees and targets, but
86 // for now, let's just fetch first row.
87 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
88 $assignee_contact_names = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $assigneeID);
89 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
90 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
91 if ($activity->activity_type_id != CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email')) {
92 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
93 $target_contact_names = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $targetID);
94 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
95 }
96 elseif (CRM_Core_Permission::check('access CiviMail') ||
97 (CRM_Mailing_Info::workflowEnabled() &&
98 CRM_Core_Permission::check('create mailings')
99 )
100 ) {
101 $defaults['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report',
102 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
103 );
104 }
105 else {
106 $defaults['target_contact_value'] = ts('(recipients)');
107 }
108
109 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
110 $defaults['source_contact_id'] = $sourceContactId;
111
112 if ($sourceContactId &&
113 !CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
114 $sourceContactId,
115 'is_deleted'
116 )
117 ) {
118 $defaults['source_contact'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
119 $sourceContactId,
120 'sort_name'
121 );
122 }
123
124 // Get case subject.
125 $defaults['case_subject'] = CRM_Case_BAO_Case::getCaseSubject($activity->id);
126
127 CRM_Core_DAO::storeValues($activity, $defaults);
128
129 return $activity;
130 }
131 return NULL;
132 }
133
134 /**
135 * Delete the activity.
136 *
137 * @param array $params
138 * @param bool $moveToTrash
139 *
140 * @return mixed
141 */
142 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
143 // CRM-9137
144 if (!empty($params['id']) && !is_array($params['id'])) {
145 CRM_Utils_Hook::pre('delete', 'Activity', $params['id'], $params);
146 }
147 else {
148 CRM_Utils_Hook::pre('delete', 'Activity', NULL, $params);
149 }
150
151 $transaction = new CRM_Core_Transaction();
152 $sqlWhereParams = $where = [];
153 if (isset($params['source_record_id']) && is_array($params['source_record_id'])) {
154 $sourceRecordIds = implode(',', $params['source_record_id']);
155 }
156 else {
157 $sourceRecordIds = $params['source_record_id'] ?? NULL;
158 }
159
160 if ($sourceRecordIds) {
161 $where[] = 'source_record_id IN ( %1 )';
162 $sqlWhereParams[1] = [$sourceRecordIds, 'CommaSeparatedIntegers'];
163 }
164 $result = NULL;
165 if (!$moveToTrash) {
166 if (!isset($params['id'])) {
167 if (!empty($params['activity_type_id'])) {
168 $where[] = 'activity_type_id IN ( %2 )';
169 $sqlWhereParams[2] = [implode(',', (array) $params['activity_type_id']), 'CommaSeparatedIntegers'];
170 }
171 $query = "DELETE FROM civicrm_activity WHERE " . implode(' AND ', $where);
172 $dao = CRM_Core_DAO::executeQuery($query, $sqlWhereParams);
173 }
174 else {
175 $activity = new CRM_Activity_DAO_Activity();
176 $activity->copyValues($params);
177 $result = $activity->delete();
178
179 // CRM-8708
180 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
181
182 // CRM-13994 delete activity entity_tag
183 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = %1";
184 $dao = CRM_Core_DAO::executeQuery($query, [1 => [$activity->id, 'Positive']]);
185
186 CRM_Core_BAO_File::deleteEntityFile('civicrm_activity', $activity->id);
187 }
188 }
189 else {
190 $activity = new CRM_Activity_DAO_Activity();
191 $activity->copyValues($params);
192
193 $activity->is_deleted = 1;
194 $result = $activity->save();
195
196 // CRM-4525 log activity delete
197 $logMsg = 'Case Activity deleted for';
198 $msgs = [];
199
200 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
201 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
202 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
203 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
204 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
205 if ($sourceContactId) {
206 $msgs[] = " source={$sourceContactId}";
207 }
208
209 // get target contacts.
210 $targetContactIds = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $targetID);
211 if (!empty($targetContactIds)) {
212 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
213 }
214 // get assignee contacts.
215 $assigneeContactIds = CRM_Activity_BAO_ActivityContact::getNames($activity->id, $assigneeID);
216 if (!empty($assigneeContactIds)) {
217 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
218 }
219
220 $logMsg .= implode(', ', $msgs);
221
222 self::logActivityAction($activity, $logMsg);
223 }
224
225 // delete the recently created Activity
226 if ($result) {
227 $activityRecent = [
228 'id' => $activity->id,
229 'type' => 'Activity',
230 ];
231 CRM_Utils_Recent::del($activityRecent);
232 }
233
234 $transaction->commit();
235 if (isset($activity)) {
236 // CRM-8708
237 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
238 CRM_Utils_Hook::post('delete', 'Activity', $activity->id, $activity);
239 }
240
241 return $result;
242 }
243
244 /**
245 * Delete activity assignment record.
246 *
247 * @param int $activityId
248 * @param int $recordTypeID
249 */
250 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
251 $activityContact = new CRM_Activity_BAO_ActivityContact();
252 $activityContact->activity_id = $activityId;
253 if ($recordTypeID) {
254 $activityContact->record_type_id = $recordTypeID;
255 }
256
257 // Let's check if activity contact record exits and then delete.
258 // Looks like delete leads to deadlock when multiple simultaneous
259 // requests are done. CRM-15470
260 if ($activityContact->find()) {
261 $activityContact->delete();
262 }
263 }
264
265 /**
266 * Process the activities.
267 *
268 * @param array $params
269 * Associated array of the submitted values.
270 *
271 * @throws CRM_Core_Exception
272 *
273 * @return CRM_Activity_BAO_Activity|null|object
274 */
275 public static function create(&$params) {
276 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
277 unset($params['created_date']);
278 unset($params['modified_date']);
279
280 // check required params
281 if (!self::dataExists($params)) {
282 throw new CRM_Core_Exception('Not enough data to create activity object');
283 }
284
285 $activity = new CRM_Activity_DAO_Activity();
286
287 if (isset($params['id']) && empty($params['id'])) {
288 unset($params['id']);
289 }
290
291 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
292 if (isset($params['activity_date_time']) &&
293 strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)
294 ) {
295 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed');
296 }
297 else {
298 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
299 }
300 }
301
302 // Set priority to Normal for Auto-populated activities (for Cases)
303 if (!isset($params['priority_id']) &&
304 // if not set and not 0
305 empty($params['id'])
306 ) {
307 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
308 $params['priority_id'] = array_search('Normal', $priority);
309 }
310
311 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
312 $params['target_contact_id'] = array_unique($params['target_contact_id']);
313 }
314 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
315 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
316 }
317
318 // CRM-9137
319 if (!empty($params['id'])) {
320 CRM_Utils_Hook::pre('edit', 'Activity', $params['id'], $params);
321 }
322 else {
323 CRM_Utils_Hook::pre('create', 'Activity', NULL, $params);
324 }
325
326 $activity->copyValues($params);
327 if (isset($params['case_id'])) {
328 // CRM-8708, preserve case ID even though it's not part of the SQL model
329 $activity->case_id = $params['case_id'];
330 }
331 elseif (is_numeric($activity->id)) {
332 // CRM-8708, preserve case ID even though it's not part of the SQL model
333 $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
334 }
335
336 // start transaction
337 $transaction = new CRM_Core_Transaction();
338
339 $result = $activity->save();
340
341 if (is_a($result, 'CRM_Core_Error')) {
342 $transaction->rollback();
343 return $result;
344 }
345
346 $activityId = $activity->id;
347 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
348 $assigneeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Assignees');
349 $targetID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
350
351 if (isset($params['source_contact_id'])) {
352 $acParams = [
353 'activity_id' => $activityId,
354 'contact_id' => $params['source_contact_id'],
355 'record_type_id' => $sourceID,
356 ];
357 self::deleteActivityContact($activityId, $sourceID);
358 CRM_Activity_BAO_ActivityContact::create($acParams);
359 }
360
361 // check and attach and files as needed
362 CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
363
364 // attempt to save activity assignment
365 $resultAssignment = NULL;
366 if (!empty($params['assignee_contact_id'])) {
367
368 $assignmentParams = ['activity_id' => $activityId];
369
370 if (is_array($params['assignee_contact_id'])) {
371 if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
372 // first delete existing assignments if any
373 self::deleteActivityContact($activityId, $assigneeID);
374 }
375
376 foreach ($params['assignee_contact_id'] as $acID) {
377 if ($acID) {
378 $assigneeParams = [
379 'activity_id' => $activityId,
380 'contact_id' => $acID,
381 'record_type_id' => $assigneeID,
382 ];
383 CRM_Activity_BAO_ActivityContact::create($assigneeParams);
384 }
385 }
386 }
387 else {
388 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
389 $assignmentParams['record_type_id'] = $assigneeID;
390 if (!empty($params['id'])) {
391 $assignment = new CRM_Activity_BAO_ActivityContact();
392 $assignment->activity_id = $activityId;
393 $assignment->record_type_id = $assigneeID;
394 $assignment->find(TRUE);
395
396 if ($assignment->contact_id != $params['assignee_contact_id']) {
397 $assignmentParams['id'] = $assignment->id;
398 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
399 }
400 }
401 else {
402 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
403 }
404 }
405 }
406 else {
407 if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
408 self::deleteActivityContact($activityId, $assigneeID);
409 }
410 }
411
412 if (is_a($resultAssignment, 'CRM_Core_Error')) {
413 $transaction->rollback();
414 return $resultAssignment;
415 }
416
417 // attempt to save activity targets
418 $resultTarget = NULL;
419 if (!empty($params['target_contact_id'])) {
420
421 $targetParams = ['activity_id' => $activityId];
422 $resultTarget = [];
423 if (is_array($params['target_contact_id'])) {
424 if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
425 // first delete existing targets if any
426 self::deleteActivityContact($activityId, $targetID);
427 }
428
429 foreach ($params['target_contact_id'] as $tid) {
430 if ($tid) {
431 $targetContactParams = [
432 'activity_id' => $activityId,
433 'contact_id' => $tid,
434 'record_type_id' => $targetID,
435 ];
436 CRM_Activity_BAO_ActivityContact::create($targetContactParams);
437 }
438 }
439 }
440 else {
441 $targetParams['contact_id'] = $params['target_contact_id'];
442 $targetParams['record_type_id'] = $targetID;
443 if (!empty($params['id'])) {
444 $target = new CRM_Activity_BAO_ActivityContact();
445 $target->activity_id = $activityId;
446 $target->record_type_id = $targetID;
447 $target->find(TRUE);
448
449 if ($target->contact_id != $params['target_contact_id']) {
450 $targetParams['id'] = $target->id;
451 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
452 }
453 }
454 else {
455 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
456 }
457 }
458 }
459 else {
460 if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
461 self::deleteActivityContact($activityId, $targetID);
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 if (!empty($params['id'])) {
611 CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
612 }
613 else {
614 CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
615 }
616
617 return $result;
618 }
619
620 /**
621 * Create an activity.
622 *
623 * @todo elaborate on what this does.
624 *
625 * @param CRM_Activity_DAO_Activity $activity
626 * @param string $logMessage
627 *
628 * @return bool
629 */
630 public static function logActivityAction($activity, $logMessage = NULL) {
631 $id = CRM_Core_Session::getLoggedInContactID();
632 if (!$id) {
633 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
634 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
635 $id = self::getActivityContact($activity->id, $sourceID);
636 }
637 $logParams = [
638 'entity_table' => 'civicrm_activity',
639 'entity_id' => $activity->id,
640 'modified_id' => $id,
641 'modified_date' => date('YmdHis'),
642 'data' => $logMessage,
643 ];
644 CRM_Core_BAO_Log::add($logParams);
645 return TRUE;
646 }
647
648 /**
649 * Get the list Activities.
650 *
651 * @param array $params
652 * Array of parameters.
653 * Keys include
654 * - contact_id int contact_id whose activities we want to retrieve
655 * - offset int which row to start from ?
656 * - rowCount int how many rows to fetch
657 * - sort object|array object or array describing sort order for sql query.
658 * - admin boolean if contact is admin
659 * - caseId int case ID
660 * - context string page on which selector is build
661 * - activity_type_id int|string the activitiy types we want to restrict by
662 *
663 * @return array
664 * Relevant data object values of open activities
665 * @throws \CiviCRM_API3_Exception
666 */
667 public static function getActivities($params) {
668 $activities = [];
669
670 // Activity.Get API params
671 $activityParams = self::getActivityParamsForDashboardFunctions($params);
672
673 if (!empty($params['rowCount']) &&
674 $params['rowCount'] > 0
675 ) {
676 $activityParams['options']['limit'] = $params['rowCount'];
677 }
678
679 if (!empty($params['sort'])) {
680 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
681 $order = $params['sort']->orderBy();
682 }
683 elseif (trim($params['sort'])) {
684 $order = CRM_Utils_Type::escape($params['sort'], 'String');
685 }
686 }
687
688 $activityParams['options']['sort'] = empty($order) ? "activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
689
690 $activityParams['return'] = [
691 'activity_date_time',
692 'source_record_id',
693 'source_contact_id',
694 'source_contact_name',
695 'assignee_contact_id',
696 'assignee_contact_name',
697 'status_id',
698 'subject',
699 'activity_type_id',
700 'activity_type',
701 'case_id',
702 'campaign_id',
703 ];
704 // Q. What does the code below achieve? case_id and campaign_id are already
705 // in the array, defined above, and this code adds them in again if their
706 // component is enabled? @fixme remove case_id and campaign_id from the array above?
707 foreach (['case_id' => 'CiviCase', 'campaign_id' => 'CiviCampaign'] as $attr => $component) {
708 if (in_array($component, self::activityComponents())) {
709 $activityParams['return'][] = $attr;
710 }
711 }
712 $result = civicrm_api3('Activity', 'Get', $activityParams)['values'];
713
714 $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
715 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
716
717 // CRM-3553, need to check user has access to target groups.
718 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
719 $accessCiviMail = ((CRM_Core_Permission::check('access CiviMail')) ||
720 (CRM_Mailing_Info::workflowEnabled() && CRM_Core_Permission::check('create mailings'))
721 );
722
723 // @todo - get rid of this & just handle in the array declaration like we do with 'subject' etc.
724 $mappingParams = [
725 'source_record_id' => 'source_record_id',
726 'activity_type_id' => 'activity_type_id',
727 'status_id' => 'status_id',
728 'campaign_id' => 'campaign_id',
729 'case_id' => 'case_id',
730 ];
731
732 if (empty($result)) {
733 $targetCount = [];
734 }
735 else {
736 $targetCount = CRM_Core_DAO::executeQuery('
737 SELECT activity_id, count(*) as target_contact_count
738 FROM civicrm_activity_contact
739 INNER JOIN civicrm_contact c ON contact_id = c.id AND c.is_deleted = 0
740 WHERE activity_id IN (' . implode(',', array_keys($result)) . ')
741 AND record_type_id = %1
742 GROUP BY activity_id', [
743 1 => [
744 CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets'),
745 'Integer',
746 ],
747 ])->fetchAll();
748 }
749 foreach ($targetCount as $activityTarget) {
750 $result[$activityTarget['activity_id']]['target_contact_count'] = $activityTarget['target_contact_count'];
751 }
752 // Iterate through & do basic mappings & determine which ones we want to retrieve target count for.
753 foreach ($result as $id => $activity) {
754 $activities[$id] = [
755 'activity_id' => $activity['id'],
756 'activity_date_time' => $activity['activity_date_time'] ?? NULL,
757 'subject' => $activity['subject'] ?? NULL,
758 'assignee_contact_name' => $activity['assignee_contact_sort_name'] ?? [],
759 'source_contact_id' => $activity['source_contact_id'] ?? NULL,
760 'source_contact_name' => $activity['source_contact_sort_name'] ?? NULL,
761 ];
762 $activities[$id]['activity_type_name'] = CRM_Core_PseudoConstant::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $activity['activity_type_id']);
763 $activities[$id]['activity_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $activity['activity_type_id']);
764 $activities[$id]['target_contact_count'] = $activity['target_contact_count'] ?? 0;
765 if (!empty($activity['target_contact_count'])) {
766 $displayedTarget = civicrm_api3('ActivityContact', 'get', [
767 'activity_id' => $id,
768 'check_permissions' => TRUE,
769 'options' => ['limit' => 1],
770 'record_type_id' => 'Activity Targets',
771 'return' => ['contact_id.sort_name', 'contact_id'],
772 'sequential' => 1,
773 ])['values'];
774 if (empty($displayedTarget[0])) {
775 $activities[$id]['target_contact_name'] = [];
776 }
777 else {
778 $activities[$id]['target_contact_name'] = [$displayedTarget[0]['contact_id'] => $displayedTarget[0]['contact_id.sort_name']];
779 }
780 }
781 if ($activities[$id]['activity_type_name'] === 'Bulk Email') {
782 $bulkActivities[] = $id;
783 // Get the total without permissions being passed but only display names after permissioning.
784 $activities[$id]['recipients'] = ts('(%1 recipients)', [1 => $activities[$id]['target_contact_count']]);
785 }
786 }
787
788 // Eventually this second iteration should just handle the target contacts. It's a bit muddled at
789 // the moment as the bulk activity stuff needs unravelling & test coverage.
790 $caseIds = [];
791 foreach ($result as $id => $activity) {
792 $isBulkActivity = (!$bulkActivityTypeID || ($bulkActivityTypeID === $activity['activity_type_id']));
793 foreach ($mappingParams as $apiKey => $expectedName) {
794 if (in_array($apiKey, [
795 'target_contact_name',
796 ])) {
797
798 if ($isBulkActivity) {
799 // @todo - how is this used? Couldn't we use 'is_bulk' or something clearer?
800 // or the calling function could handle
801 $activities[$id]['mailingId'] = FALSE;
802 if ($accessCiviMail &&
803 ($mailingIDs === TRUE || in_array($activity['source_record_id'], $mailingIDs))
804 ) {
805 $activities[$id]['mailingId'] = TRUE;
806 }
807 }
808 }
809 // case related fields
810 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
811 $activities[$id][$expectedName] = $activity[$apiKey] ?? NULL;
812
813 // fetch case subject for case ID found
814 if (!empty($activity['case_id'])) {
815 // Store cases; we'll look them up in one query below. We convert
816 // to int here so we can trust it for SQL.
817 $caseIds[$id] = (int) current($activity['case_id']);
818 }
819 }
820 else {
821 // @todo this generic assign could just be handled in array declaration earlier.
822 $activities[$id][$expectedName] = $activity[$apiKey] ?? NULL;
823 if ($apiKey == 'campaign_id') {
824 $activities[$id]['campaign'] = $allCampaigns[$activities[$id][$expectedName]] ?? NULL;
825 }
826 }
827 }
828 // if deleted, wrap in <del>
829 if (!empty($activity['source_contact_id']) &&
830 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
831 ) {
832 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
833 }
834 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getParentFor($id, 'civicrm_activity');
835 }
836
837 // Look up any case subjects we need in a single query and add them in the relevant activities under 'case_subject'
838 if ($caseIds) {
839 $subjects = CRM_Core_DAO::executeQuery('SELECT id, subject FROM civicrm_case WHERE id IN (' . implode(',', array_unique($caseIds)) . ')')
840 ->fetchMap('id', 'subject');
841 foreach ($caseIds as $activityId => $caseId) {
842 $result[$activityId]['case_subject'] = $subjects[$caseId];
843 }
844 }
845
846 return $activities;
847 }
848
849 /**
850 * Filter the activity types to only return the ones we actually asked for
851 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
852 *
853 * @param $params
854 * @return array|null (Use in Activity.get API activity_type_id)
855 */
856 public static function filterActivityTypes($params) {
857 $activityTypes = [];
858
859 // If no activity types are specified, get all the active ones
860 if (empty($params['activity_type_id'])) {
861 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'get');
862 }
863
864 // If no activity types are specified or excluded, return the list of all active ones
865 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
866 if (!empty($activityTypes)) {
867 return ['IN' => array_keys($activityTypes)];
868 }
869 return NULL;
870 }
871
872 // If we have specified activity types, build a list to return, excluding the ones we don't want.
873 if (!empty($params['activity_type_id'])) {
874 if (!is_array($params['activity_type_id'])) {
875 // Turn it into array if only one specified, so we don't duplicate processing below
876 $params['activity_type_id'] = [$params['activity_type_id'] => $params['activity_type_id']];
877 }
878 foreach ($params['activity_type_id'] as $value) {
879 // Add each activity type that was specified to list
880 $value = CRM_Utils_Type::escape($value, 'Positive');
881 $activityTypes[$value] = $value;
882 }
883 }
884
885 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
886 if (!empty($params['activity_type_exclude_id'])) {
887 if (!is_array($params['activity_type_exclude_id'])) {
888 // Turn it into array if only one specified, so we don't duplicate processing below
889 $params['activity_type_exclude_id'] = [$params['activity_type_exclude_id'] => $params['activity_type_exclude_id']];
890 }
891 foreach ($params['activity_type_exclude_id'] as $value) {
892 // Remove each activity type from list if it should be excluded
893 $value = CRM_Utils_Type::escape($value, 'Positive');
894 if (array_key_exists($value, $activityTypes)) {
895 unset($activityTypes[$value]);
896 }
897 }
898 }
899
900 return ['IN' => array_keys($activityTypes)];
901 }
902
903 /**
904 * @inheritDoc
905 */
906 public function addSelectWhereClause() {
907 $clauses = [];
908 $permittedActivityTypeIDs = self::getPermittedActivityTypes();
909 $allActivityTypes = self::buildOptions('activity_type_id');
910 if (empty($permittedActivityTypeIDs)) {
911 // This just prevents a mysql fail if they have no access - should be extremely edge case.
912 $permittedActivityTypeIDs = [0];
913 }
914 if (array_keys($allActivityTypes) !== array_keys($permittedActivityTypeIDs)) {
915 $clauses['activity_type_id'] = ('IN (' . implode(', ', $permittedActivityTypeIDs) . ')');
916 }
917
918 $contactClause = CRM_Utils_SQL::mergeSubquery('Contact');
919 if ($contactClause) {
920 $contactClause = implode(' AND contact_id ', $contactClause);
921 $clauses['id'][] = "IN (SELECT activity_id FROM civicrm_activity_contact WHERE contact_id $contactClause)";
922 }
923 CRM_Utils_Hook::selectWhereClause($this, $clauses);
924 return $clauses;
925 }
926
927 /**
928 * Get an array of components that are accessible by the currenct user.
929 *
930 * This means checking if they are enabled and if the user has appropriate permission.
931 *
932 * For most components the permission is access component (e.g 'access CiviContribute').
933 * Exceptions as CiviCampaign (administer CiviCampaign) and CiviCase
934 * (accesses a case function which enforces edit all cases or edit my cases. Case
935 * permissions are also handled on a per activity basis).
936 *
937 * Checks whether logged in user has permission to the component.
938 *
939 * @param bool $excludeComponentHandledActivities
940 * Should we exclude components whose display is handled in the components.
941 * In practice this means should we include CiviCase in the results. Presumbaly
942 * at the time it was decided case activities should be shown in the case framework and
943 * that this concept might be extended later. In practice most places that
944 * call this then re-add CiviCase in some way so it's all a bit... odd.
945 *
946 * @return array
947 * Array of component id and name.
948 */
949 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
950 $components = [];
951 $compInfo = CRM_Core_Component::getEnabledComponents();
952 foreach ($compInfo as $compObj) {
953 $includeComponent = !$excludeComponentHandledActivities || !empty($compObj->info['showActivitiesInCore']);
954 if ($includeComponent) {
955 if ($compObj->info['name'] == 'CiviCampaign') {
956 $componentPermission = "administer {$compObj->name}";
957 }
958 else {
959 $componentPermission = "access {$compObj->name}";
960 }
961 if ($compObj->info['name'] == 'CiviCase') {
962 if (CRM_Case_BAO_Case::accessCiviCase()) {
963 $components[$compObj->componentID] = $compObj->info['name'];
964 }
965 }
966 elseif (CRM_Core_Permission::check($componentPermission)) {
967 $components[$compObj->componentID] = $compObj->info['name'];
968 }
969 }
970 }
971
972 return $components;
973 }
974
975 /**
976 * Get the activity Count.
977 *
978 * @param array $input
979 * Array of parameters.
980 * Keys include
981 * - contact_id int contact_id whose activities we want to retrieve
982 * - admin boolean if contact is admin
983 * - caseId int case ID
984 * - context string page on which selector is build
985 * - activity_type_id int|string the activity types we want to restrict by
986 *
987 * @return int
988 * count of activities
989 */
990 public static function getActivitiesCount($input) {
991 $activityParams = self::getActivityParamsForDashboardFunctions($input);
992 return civicrm_api3('Activity', 'getcount', $activityParams);
993 }
994
995 /**
996 * @param int $sourceContactID
997 * The contact ID of the email "from".
998 * @param string $subject
999 * @param string $html
1000 * @param string $text
1001 * @param string $additionalDetails
1002 * The additional information of CC and BCC appended to the activity details.
1003 * @param int $campaignID
1004 * @param array $attachments
1005 * @param int $caseID
1006 *
1007 * @return int
1008 * The created activity ID
1009 * @throws \CRM_Core_Exception
1010 */
1011 public static function createEmailActivity($sourceContactID, $subject, $html, $text, $additionalDetails, $campaignID, $attachments, $caseID) {
1012 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
1013
1014 // CRM-6265: save both text and HTML parts in details (if present)
1015 if ($html and $text) {
1016 $details = "-ALTERNATIVE ITEM 0-\n{$html}{$additionalDetails}\n-ALTERNATIVE ITEM 1-\n{$text}{$additionalDetails}\n-ALTERNATIVE END-\n";
1017 }
1018 else {
1019 $details = $html ? $html : $text;
1020 $details .= $additionalDetails;
1021 }
1022
1023 $activityParams = [
1024 'source_contact_id' => $sourceContactID,
1025 'activity_type_id' => $activityTypeID,
1026 'activity_date_time' => date('YmdHis'),
1027 'subject' => $subject,
1028 'details' => $details,
1029 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1030 'campaign_id' => $campaignID,
1031 ];
1032 if (!empty($caseID)) {
1033 $activityParams['case_id'] = $caseID;
1034 }
1035
1036 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1037 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1038
1039 // add the attachments to activity params here
1040 if ($attachments) {
1041 // first process them
1042 $activityParams = array_merge($activityParams, $attachments);
1043 }
1044
1045 $activity = civicrm_api3('Activity', 'create', $activityParams);
1046
1047 return $activity['id'];
1048 }
1049
1050 /**
1051 * Send the message to all the contacts.
1052 *
1053 * Also insert a contact activity in each contacts record.
1054 *
1055 * @param array $contactDetails
1056 * The array of contact details to send the email.
1057 * @param string $subject
1058 * The subject of the message.
1059 * @param $text
1060 * @param $html
1061 * @param string $emailAddress
1062 * Use this 'to' email address instead of the default Primary address.
1063 * @param int $userID
1064 * Use this userID if set.
1065 * @param string $from
1066 * @param array $attachments
1067 * The array of attachments if any.
1068 * @param string $cc
1069 * Cc recipient.
1070 * @param string $bcc
1071 * Bcc recipient.
1072 * @param array $contactIds
1073 * Contact ids.
1074 * @param string $additionalDetails
1075 * The additional information of CC and BCC appended to the activity Details.
1076 * @param array $contributionIds
1077 * @param int $campaignId
1078 * @param int $caseId
1079 *
1080 * @return array
1081 * ( sent, activityId) if any email is sent and activityId
1082 * @throws \CRM_Core_Exception
1083 * @throws \CiviCRM_API3_Exception
1084 */
1085 public static function sendEmail(
1086 $contactDetails,
1087 $subject,
1088 $text,
1089 $html,
1090 $emailAddress,
1091 $userID = NULL,
1092 $from = NULL,
1093 $attachments = NULL,
1094 $cc = NULL,
1095 $bcc = NULL,
1096 $contactIds = NULL,
1097 $additionalDetails = NULL,
1098 $contributionIds = NULL,
1099 $campaignId = NULL,
1100 $caseId = NULL
1101 ) {
1102 // get the contact details of logged in contact, which we set as from email
1103 if ($userID == NULL) {
1104 $userID = CRM_Core_Session::getLoggedInContactID();
1105 }
1106
1107 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1108 if (!$fromEmail) {
1109 return [count($contactDetails), 0, count($contactDetails)];
1110 }
1111 if (!trim($fromDisplayName)) {
1112 $fromDisplayName = $fromEmail;
1113 }
1114
1115 // CRM-4575
1116 // token replacement of addressee/email/postal greetings
1117 // get the tokens added in subject and message
1118 $subjectToken = CRM_Utils_Token::getTokens($subject);
1119 $messageToken = CRM_Utils_Token::getTokens($text);
1120 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1121 $allTokens = array_merge($messageToken, $subjectToken);
1122
1123 if (!$from) {
1124 $from = "$fromDisplayName <$fromEmail>";
1125 }
1126
1127 //create the meta level record first ( email activity )
1128 $activityID = self::createEmailActivity($userID, $subject, $html, $text, $additionalDetails, $campaignId, $attachments, $caseId);
1129
1130 $returnProperties = [];
1131 if (isset($messageToken['contact'])) {
1132 foreach ($messageToken['contact'] as $key => $value) {
1133 $returnProperties[$value] = 1;
1134 }
1135 }
1136
1137 if (isset($subjectToken['contact'])) {
1138 foreach ($subjectToken['contact'] as $key => $value) {
1139 if (!isset($returnProperties[$value])) {
1140 $returnProperties[$value] = 1;
1141 }
1142 }
1143 }
1144
1145 // get token details for contacts, call only if tokens are used
1146 $details = [];
1147 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
1148 list($details) = CRM_Utils_Token::getTokenDetails(
1149 $contactIds,
1150 $returnProperties,
1151 NULL, NULL, FALSE,
1152 $allTokens,
1153 'CRM_Activity_BAO_Activity'
1154 );
1155 }
1156
1157 // call token hook
1158 $tokens = [];
1159 CRM_Utils_Hook::tokens($tokens);
1160 $categories = array_keys($tokens);
1161
1162 $escapeSmarty = FALSE;
1163 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1164 $smarty = CRM_Core_Smarty::singleton();
1165 $escapeSmarty = TRUE;
1166 }
1167
1168 $contributionDetails = [];
1169 if (!empty($contributionIds)) {
1170 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1171 $contributionIds,
1172 $subject,
1173 $subjectToken,
1174 $text,
1175 $html,
1176 $messageToken,
1177 $escapeSmarty
1178 );
1179 }
1180
1181 $sent = $notSent = [];
1182 foreach ($contactDetails as $values) {
1183 $contactId = $values['contact_id'];
1184 $emailAddress = $values['email'];
1185
1186 if (!empty($contributionDetails)) {
1187 $subject = $contributionDetails[$contactId]['subject'];
1188 $text = $contributionDetails[$contactId]['text'];
1189 $html = $contributionDetails[$contactId]['html'];
1190 }
1191
1192 if (!empty($details) && is_array($details["{$contactId}"])) {
1193 // unset email from details since it always returns primary email address
1194 unset($details["{$contactId}"]['email']);
1195 unset($details["{$contactId}"]['email_id']);
1196 $values = array_merge($values, $details["{$contactId}"]);
1197 }
1198
1199 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1200 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1201
1202 // CRM-4539
1203 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1204 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1205 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1206 }
1207 else {
1208 $tokenText = NULL;
1209 }
1210
1211 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1212 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1213 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1214 }
1215 else {
1216 $tokenHtml = NULL;
1217 }
1218
1219 if ($caseId) {
1220 $tokenSubject = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenSubject, $subjectToken, $escapeSmarty);
1221 $tokenText = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenText, $messageToken, $escapeSmarty);
1222 $tokenHtml = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenHtml, $messageToken, $escapeSmarty);
1223 }
1224
1225 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1226 // also add the contact tokens to the template
1227 $smarty->assign_by_ref('contact', $values);
1228
1229 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1230 $tokenText = $smarty->fetch("string:$tokenText");
1231 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1232 }
1233
1234 $sent = FALSE;
1235 if (self::sendMessage(
1236 $from,
1237 $userID,
1238 $contactId,
1239 $tokenSubject,
1240 $tokenText,
1241 $tokenHtml,
1242 $emailAddress,
1243 $activityID,
1244 // get the set of attachments from where they are stored
1245 CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activityID),
1246 $cc,
1247 $bcc
1248 )
1249 ) {
1250 $sent = TRUE;
1251 }
1252 }
1253
1254 return [$sent, $activityID];
1255 }
1256
1257 /**
1258 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1259 *
1260 * @param array $contactDetails
1261 * @param array $activityParams
1262 * @param array $smsProviderParams
1263 * @param array $contactIds
1264 * @param int $sourceContactId This is the source contact Id
1265 *
1266 * @return array(bool $sent, int $activityId, int $success)
1267 * @throws CRM_Core_Exception
1268 */
1269 public static function sendSMS(
1270 &$contactDetails = NULL,
1271 &$activityParams,
1272 &$smsProviderParams = [],
1273 &$contactIds = NULL,
1274 $sourceContactId = NULL
1275 ) {
1276 if (!CRM_Core_Permission::check('send SMS')) {
1277 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1278 }
1279
1280 if (!isset($contactDetails) && !isset($contactIds)) {
1281 throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1282 }
1283 // Populate $contactDetails and $contactIds if only one is set
1284 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1285 foreach ($contactIds as $id) {
1286 try {
1287 $contactDetails[] = civicrm_api3('Contact', 'getsingle', ['contact_id' => $id]);
1288 }
1289 catch (Exception $e) {
1290 // Contact Id doesn't exist
1291 }
1292 }
1293 }
1294 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1295 foreach ($contactDetails as $contact) {
1296 $contactIds[] = $contact['contact_id'];
1297 }
1298 }
1299
1300 // Get logged in User Id
1301 if (empty($sourceContactId)) {
1302 $sourceContactId = CRM_Core_Session::getLoggedInContactID();
1303 }
1304
1305 $text = &$activityParams['sms_text_message'];
1306
1307 // Create the meta level record first ( sms activity )
1308 $activityParams = [
1309 'source_contact_id' => $sourceContactId,
1310 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
1311 'activity_date_time' => date('YmdHis'),
1312 'subject' => $activityParams['activity_subject'],
1313 'details' => $text,
1314 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1315 ];
1316 $activity = self::create($activityParams);
1317 $activityID = $activity->id;
1318
1319 // Process Tokens
1320 // token replacement of addressee/email/postal greetings
1321 // get the tokens added in subject and message
1322 $messageToken = CRM_Utils_Token::getTokens($text);
1323 $returnProperties = [];
1324 if (isset($messageToken['contact'])) {
1325 foreach ($messageToken['contact'] as $key => $value) {
1326 $returnProperties[$value] = 1;
1327 }
1328 }
1329 // Call tokens hook
1330 $tokens = [];
1331 CRM_Utils_Hook::tokens($tokens);
1332 $categories = array_keys($tokens);
1333 // get token details for contacts, call only if tokens are used
1334 $tokenDetails = [];
1335 if (!empty($returnProperties) || !empty($tokens)) {
1336 list($tokenDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
1337 $returnProperties,
1338 NULL, NULL, FALSE,
1339 $messageToken,
1340 'CRM_Activity_BAO_Activity'
1341 );
1342 }
1343
1344 $success = 0;
1345 $errMsgs = [];
1346 foreach ($contactDetails as $contact) {
1347 $contactId = $contact['contact_id'];
1348
1349 // Replace tokens
1350 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
1351 // unset phone from details since it always returns primary number
1352 unset($tokenDetails["{$contactId}"]['phone']);
1353 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1354 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
1355 }
1356 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1357 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1358
1359 // Only send if the phone is of type mobile
1360 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1361 $smsProviderParams['To'] = $contact['phone'];
1362 }
1363 else {
1364 $smsProviderParams['To'] = '';
1365 }
1366
1367 $doNotSms = $contact['do_not_sms'] ?? 0;
1368
1369 if ($doNotSms) {
1370 $errMsgs[] = PEAR::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN);
1371 }
1372 else {
1373 try {
1374 $sendResult = self::sendSMSMessage(
1375 $contactId,
1376 $tokenText,
1377 $smsProviderParams,
1378 $activityID,
1379 $sourceContactId
1380 );
1381 $success++;
1382 }
1383 catch (CRM_Core_Exception $e) {
1384 $errMsgs[] = $e->getMessage();
1385 }
1386 }
1387 }
1388
1389 // If at least one message was sent and no errors
1390 // were generated then return a boolean value of TRUE.
1391 // Otherwise, return FALSE (no messages sent) or
1392 // and array of 1 or more PEAR_Error objects.
1393 $sent = FALSE;
1394 if ($success > 0 && count($errMsgs) == 0) {
1395 $sent = TRUE;
1396 }
1397 elseif (count($errMsgs) > 0) {
1398 $sent = $errMsgs;
1399 }
1400
1401 return [$sent, $activity->id, $success];
1402 }
1403
1404 /**
1405 * Send the sms message to a specific contact.
1406 *
1407 * @param int $toID
1408 * The contact id of the recipient.
1409 * @param $tokenText
1410 * @param array $smsProviderParams
1411 * The params used for sending sms.
1412 * @param int $activityID
1413 * The activity ID that tracks the message.
1414 * @param int $sourceContactID
1415 *
1416 * @return bool true on success
1417 * @throws CRM_Core_Exception
1418 */
1419 public static function sendSMSMessage(
1420 $toID,
1421 &$tokenText,
1422 $smsProviderParams = [],
1423 $activityID,
1424 $sourceContactID = NULL
1425 ) {
1426 $toPhoneNumber = NULL;
1427 if ($smsProviderParams['To']) {
1428 // If phone number is specified use it
1429 $toPhoneNumber = trim($smsProviderParams['To']);
1430 }
1431 elseif ($toID) {
1432 // No phone number specified, so find a suitable one for the contact
1433 $filters = ['is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0];
1434 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1435 // To get primary mobile phonenumber, if not get the first mobile phonenumber
1436 if (!empty($toPhoneNumbers)) {
1437 $toPhoneNumberDetails = reset($toPhoneNumbers);
1438 $toPhoneNumber = $toPhoneNumberDetails['phone'] ?? NULL;
1439 // Contact allows to send sms
1440 }
1441 }
1442
1443 // make sure both phone are valid
1444 // and that the recipient wants to receive sms
1445 if (empty($toPhoneNumber)) {
1446 throw new CRM_Core_Exception('Recipient phone number is invalid or recipient does not want to receive SMS');
1447 }
1448
1449 $recipient = $toPhoneNumber;
1450 $smsProviderParams['contact_id'] = $toID;
1451 $smsProviderParams['parent_activity_id'] = $activityID;
1452
1453 $providerObj = CRM_SMS_Provider::singleton(['provider_id' => $smsProviderParams['provider_id']]);
1454 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
1455 if (PEAR::isError($sendResult)) {
1456 throw new CRM_Core_Exception($sendResult->getMessage());
1457 }
1458
1459 // add activity target record for every sms that is sent
1460 $targetID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
1461 $activityTargetParams = [
1462 'activity_id' => $activityID,
1463 'contact_id' => $toID,
1464 'record_type_id' => $targetID,
1465 ];
1466 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1467
1468 return TRUE;
1469 }
1470
1471 /**
1472 * Send the message to a specific contact.
1473 *
1474 * @param string $from
1475 * The name and email of the sender.
1476 * @param int $fromID
1477 * @param int $toID
1478 * The contact id of the recipient.
1479 * @param string $subject
1480 * The subject of the message.
1481 * @param $text_message
1482 * @param $html_message
1483 * @param string $emailAddress
1484 * Use this 'to' email address instead of the default Primary address.
1485 * @param int $activityID
1486 * The activity ID that tracks the message.
1487 * @param null $attachments
1488 * @param null $cc
1489 * @param null $bcc
1490 *
1491 * @return bool
1492 * TRUE if successful else FALSE.
1493 */
1494 public static function sendMessage(
1495 $from,
1496 $fromID,
1497 $toID,
1498 &$subject,
1499 &$text_message,
1500 &$html_message,
1501 $emailAddress,
1502 $activityID,
1503 $attachments = NULL,
1504 $cc = NULL,
1505 $bcc = NULL
1506 ) {
1507 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1508 if ($emailAddress) {
1509 $toEmail = trim($emailAddress);
1510 }
1511
1512 // make sure both email addresses are valid
1513 // and that the recipient wants to receive email
1514 if (empty($toEmail) or $toDoNotEmail) {
1515 return FALSE;
1516 }
1517 if (!trim($toDisplayName)) {
1518 $toDisplayName = $toEmail;
1519 }
1520
1521 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1522 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1523
1524 // create the params array
1525 $mailParams = [
1526 'groupName' => 'Activity Email Sender',
1527 'from' => $from,
1528 'toName' => $toDisplayName,
1529 'toEmail' => $toEmail,
1530 'subject' => $subject,
1531 'cc' => $cc,
1532 'bcc' => $bcc,
1533 'text' => $text_message,
1534 'html' => $html_message,
1535 'attachments' => $attachments,
1536 ];
1537
1538 if (!CRM_Utils_Mail::send($mailParams)) {
1539 return FALSE;
1540 }
1541
1542 // add activity target record for every mail that is send
1543 $activityTargetParams = [
1544 'activity_id' => $activityID,
1545 'contact_id' => $toID,
1546 'record_type_id' => $targetID,
1547 ];
1548 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1549 return TRUE;
1550 }
1551
1552 /**
1553 * Combine all the importable fields from the lower levels object.
1554 *
1555 * The ordering is important, since currently we do not have a weight
1556 * scheme. Adding weight is super important and should be done in the
1557 * next week or so, before this can be called complete.
1558 *
1559 * @param bool $status
1560 *
1561 * @return array
1562 * array of importable Fields
1563 */
1564 public static function &importableFields($status = FALSE) {
1565 if (!self::$_importableFields) {
1566 if (!self::$_importableFields) {
1567 self::$_importableFields = [];
1568 }
1569 if (!$status) {
1570 $fields = ['' => ['title' => ts('- do not import -')]];
1571 }
1572 else {
1573 $fields = ['' => ['title' => ts('- Activity Fields -')]];
1574 }
1575
1576 $tmpFields = CRM_Activity_DAO_Activity::import();
1577 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1578
1579 // Using new Dedupe rule.
1580 $ruleParams = [
1581 'contact_type' => 'Individual',
1582 'used' => 'Unsupervised',
1583 ];
1584 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1585
1586 $tmpConatctField = [];
1587 if (is_array($fieldsArray)) {
1588 foreach ($fieldsArray as $value) {
1589 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1590 $value,
1591 'id',
1592 'column_name'
1593 );
1594 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1595 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1596 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1597 }
1598 }
1599 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1600 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1601 $fields = array_merge($fields, $tmpConatctField);
1602 $fields = array_merge($fields, $tmpFields);
1603 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1604 self::$_importableFields = $fields;
1605 }
1606 return self::$_importableFields;
1607 }
1608
1609 /**
1610 * @deprecated - use the api instead.
1611 *
1612 * Get the Activities of a target contact.
1613 *
1614 * @param int $contactId
1615 * Id of the contact whose activities need to find.
1616 *
1617 * @return array
1618 * array of activity fields
1619 */
1620 public static function getContactActivity($contactId) {
1621 // @todo remove this function entirely.
1622 $activities = [];
1623 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1624 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1625 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1626 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1627
1628 // First look for activities where contactId is one of the targets
1629 $query = "
1630 SELECT activity_id, record_type_id
1631 FROM civicrm_activity_contact
1632 WHERE contact_id = $contactId
1633 ";
1634 $dao = CRM_Core_DAO::executeQuery($query);
1635 while ($dao->fetch()) {
1636 if ($dao->record_type_id == $targetID) {
1637 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1638 }
1639 elseif ($dao->record_type_id == $assigneeID) {
1640 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1641 }
1642 else {
1643 // do source stuff here
1644 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
1645 }
1646 }
1647
1648 $activityIds = array_keys($activities);
1649 if (count($activityIds) < 1) {
1650 return [];
1651 }
1652
1653 $activityIds = implode(',', $activityIds);
1654 $query = "
1655 SELECT activity.id as activity_id,
1656 activity_type_id,
1657 subject, location, activity_date_time, details, status_id
1658 FROM civicrm_activity activity
1659 WHERE activity.id IN ($activityIds)";
1660
1661 $dao = CRM_Core_DAO::executeQuery($query);
1662
1663 while ($dao->fetch()) {
1664 $activities[$dao->activity_id]['id'] = $dao->activity_id;
1665 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1666 $activities[$dao->activity_id]['subject'] = $dao->subject;
1667 $activities[$dao->activity_id]['location'] = $dao->location;
1668 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1669 $activities[$dao->activity_id]['details'] = $dao->details;
1670 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1671 $activities[$dao->activity_id]['activity_name'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id);
1672 $activities[$dao->activity_id]['status'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id);
1673
1674 // set to null if not set
1675 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
1676 $activities[$dao->activity_id]['source_contact_id'] = NULL;
1677 }
1678 }
1679 return $activities;
1680 }
1681
1682 /**
1683 * Add activity for Membership/Event/Contribution.
1684 *
1685 * @param object $activity
1686 * particular component object.
1687 * @param string $activityType
1688 * For Membership Signup or Renewal.
1689 * @param int $targetContactID
1690 * @param array $params
1691 * Activity params to override.
1692 *
1693 * @return bool|NULL
1694 */
1695 public static function addActivity(
1696 $activity,
1697 $activityType = 'Membership Signup',
1698 $targetContactID = NULL,
1699 $params = []
1700 ) {
1701 $date = date('YmdHis');
1702 if ($activity->__table == 'civicrm_membership') {
1703 $component = 'Membership';
1704 }
1705 elseif ($activity->__table == 'civicrm_participant') {
1706 if ($activityType != 'Email') {
1707 $activityType = 'Event Registration';
1708 }
1709 $component = 'Event';
1710 }
1711 elseif ($activity->__table == 'civicrm_contribution') {
1712 // create activity record only for Completed Contributions
1713 $contributionCompletedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1714 if ($activity->contribution_status_id != $contributionCompletedStatusId) {
1715 //For onbehalf payments, create a scheduled activity.
1716 if (empty($params['on_behalf'])) {
1717 return NULL;
1718 }
1719 $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
1720 }
1721 $activityType = $component = 'Contribution';
1722
1723 // retrieve existing activity based on source_record_id and activity_type
1724 if (empty($params['id'])) {
1725 $params['id'] = CRM_Utils_Array::value('id', civicrm_api3('Activity', 'Get', [
1726 'source_record_id' => $activity->id,
1727 'activity_type_id' => $activityType,
1728 ]));
1729 }
1730 if (!empty($params['id'])) {
1731 // CRM-13237 : if activity record found, update it with campaign id of contribution
1732 $params['campaign_id'] = $activity->campaign_id;
1733 }
1734
1735 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1736 }
1737
1738 $activityParams = [
1739 'source_contact_id' => $activity->contact_id,
1740 'source_record_id' => $activity->id,
1741 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1742 'activity_date_time' => $date,
1743 'is_test' => $activity->is_test,
1744 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1745 'skipRecentView' => TRUE,
1746 'campaign_id' => $activity->campaign_id,
1747 ];
1748 $activityParams = array_merge($activityParams, $params);
1749
1750 if (empty($activityParams['subject'])) {
1751 $activityParams['subject'] = self::getActivitySubject($activity);
1752 }
1753
1754 if (!empty($activity->activity_id)) {
1755 $activityParams['id'] = $activity->activity_id;
1756 }
1757 // create activity with target contacts
1758 $id = CRM_Core_Session::getLoggedInContactID();
1759 if ($id) {
1760 $activityParams['source_contact_id'] = $id;
1761 $activityParams['target_contact_id'][] = $activity->contact_id;
1762 }
1763
1764 // CRM-14945
1765 if (property_exists($activity, 'details')) {
1766 $activityParams['details'] = $activity->details;
1767 }
1768 //CRM-4027
1769 if ($targetContactID) {
1770 $activityParams['target_contact_id'][] = $targetContactID;
1771 }
1772 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
1773 // deal with any exceptions.
1774 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1775 throw new CRM_Core_Exception("Failed creating Activity for $component of id {$activity->id}");
1776 }
1777 }
1778
1779 /**
1780 * Get activity subject on basis of component object.
1781 *
1782 * @param object $entityObj
1783 * particular component object.
1784 *
1785 * @return string
1786 * @throws \CRM_Core_Exception
1787 */
1788 public static function getActivitySubject($entityObj) {
1789 // @todo determine the subject on the appropriate entity rather than from the activity.
1790 switch ($entityObj->__table) {
1791 case 'civicrm_membership':
1792 $membershipType = CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $entityObj->membership_type_id);
1793 $subject = $membershipType ?: ts('Membership');
1794
1795 if (!CRM_Utils_System::isNull($entityObj->source)) {
1796 $subject .= " - {$entityObj->source}";
1797 }
1798
1799 if ($entityObj->owner_membership_id) {
1800 list($displayName) = CRM_Contact_BAO_Contact::getDisplayAndImage(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id, 'contact_id'));
1801 $subject .= sprintf(' (by %s)', $displayName);
1802 }
1803
1804 $subject .= ' - Status: ' . CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'status_id', $entityObj->status_id);
1805 return $subject;
1806
1807 case 'civicrm_participant':
1808 $event = CRM_Event_BAO_Event::getEvents(1, $entityObj->event_id, TRUE, FALSE);
1809 $roles = CRM_Event_PseudoConstant::participantRole();
1810 $status = CRM_Event_PseudoConstant::participantStatus();
1811 $subject = $event[$entityObj->event_id];
1812
1813 if (!empty($roles[$entityObj->role_id])) {
1814 $subject .= ' - ' . $roles[$entityObj->role_id];
1815 }
1816 if (!empty($status[$entityObj->status_id])) {
1817 $subject .= ' - ' . $status[$entityObj->status_id];
1818 }
1819
1820 return $subject;
1821
1822 case 'civicrm_contribution':
1823 $subject = CRM_Utils_Money::format($entityObj->total_amount, $entityObj->currency);
1824 if (!CRM_Utils_System::isNull($entityObj->source)) {
1825 $subject .= " - {$entityObj->source}";
1826 }
1827
1828 // Amount and source could exceed max length of subject column.
1829 return CRM_Utils_String::ellipsify($subject, 255);
1830 }
1831 }
1832
1833 /**
1834 * Get Parent activity for currently viewed activity.
1835 *
1836 * @param int $activityId
1837 * Current activity id.
1838 *
1839 * @return int
1840 * Id of parent activity otherwise false.
1841 * @throws \CRM_Core_Exception
1842 */
1843 public static function getParentActivity($activityId) {
1844 static $parentActivities = [];
1845
1846 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1847
1848 if (!array_key_exists($activityId, $parentActivities)) {
1849 $parentActivities[$activityId] = [];
1850
1851 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1852 $activityId,
1853 'parent_id'
1854 );
1855
1856 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1857 }
1858
1859 return $parentActivities[$activityId];
1860 }
1861
1862 /**
1863 * Get total count of prior revision of currently viewed activity.
1864 *
1865 * @param $activityID
1866 * Current activity id.
1867 * @deprecated
1868 * @return int
1869 * $params count of prior activities otherwise false.
1870 * @throws \CRM_Core_Exception
1871 */
1872 public static function getPriorCount($activityID) {
1873 CRM_Core_Error::deprecatedFunctionWarning('unused function to be removed');
1874 static $priorCounts = [];
1875
1876 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1877
1878 if (!array_key_exists($activityID, $priorCounts)) {
1879 $priorCounts[$activityID] = [];
1880 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1881 $activityID,
1882 'original_id'
1883 );
1884 $count = 0;
1885 if ($originalID) {
1886 $query = "
1887 SELECT count( id ) AS cnt
1888 FROM civicrm_activity
1889 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1890 AND is_current_revision = 0
1891 AND id < {$activityID}
1892 ";
1893 $params = [1 => [$originalID, 'Integer']];
1894 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1895 }
1896 $priorCounts[$activityID] = $count ? $count : 0;
1897 }
1898
1899 return $priorCounts[$activityID];
1900 }
1901
1902 /**
1903 * Get all prior activities of currently viewed activity.
1904 *
1905 * @param $activityID
1906 * Current activity id.
1907 * @param bool $onlyPriorRevisions
1908 *
1909 * @return array
1910 * prior activities info.
1911 * @throws \CRM_Core_Exception
1912 */
1913 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1914 static $priorActivities = [];
1915
1916 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1917 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1918
1919 if (!array_key_exists($index, $priorActivities)) {
1920 $priorActivities[$index] = [];
1921
1922 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1923 $activityID,
1924 'original_id'
1925 );
1926 if (!$originalID) {
1927 $originalID = $activityID;
1928 }
1929 if ($originalID) {
1930 $query = "
1931 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1932 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1933 WHERE (ca.id = %1 OR ca.original_id = %1)
1934 AND cl.entity_table = 'civicrm_activity'
1935 AND cl.entity_id = ca.id
1936 AND cl.modified_id = c.id
1937 ";
1938 if ($onlyPriorRevisions) {
1939 $query .= " AND ca.id < {$activityID}";
1940 }
1941 $query .= " ORDER BY ca.id DESC";
1942
1943 $params = [1 => [$originalID, 'Integer']];
1944 $dao = CRM_Core_DAO::executeQuery($query, $params);
1945
1946 while ($dao->fetch()) {
1947 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
1948 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
1949 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
1950 }
1951 }
1952 }
1953 return $priorActivities[$index];
1954 }
1955
1956 /**
1957 * Find the latest revision of a given activity.
1958 *
1959 * @param int $activityID
1960 * Prior activity id.
1961 *
1962 * @return int
1963 * current activity id.
1964 *
1965 * @throws \CRM_Core_Exception
1966 */
1967 public static function getLatestActivityId($activityID) {
1968 static $latestActivityIds = [];
1969
1970 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1971
1972 if (!array_key_exists($activityID, $latestActivityIds)) {
1973 $latestActivityIds[$activityID] = [];
1974
1975 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1976 $activityID,
1977 'original_id'
1978 );
1979 if ($originalID) {
1980 $activityID = $originalID;
1981 }
1982 $params = [1 => [$activityID, 'Integer']];
1983 $query = 'SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1';
1984
1985 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
1986 }
1987
1988 return $latestActivityIds[$activityID];
1989 }
1990
1991 /**
1992 * Create a follow up a given activity.
1993 *
1994 * @param int $activityId
1995 * activity id of parent activity.
1996 * @param array $params
1997 *
1998 * @return CRM_Activity_BAO_Activity|null|object
1999 *
2000 * @throws \CRM_Core_Exception
2001 */
2002 public static function createFollowupActivity($activityId, $params) {
2003 if (!$activityId) {
2004 return NULL;
2005 }
2006
2007 $followupParams = [];
2008 $followupParams['parent_id'] = $activityId;
2009 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
2010 $followupParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2011
2012 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2013 // Get Subject of Follow-up Activiity, CRM-4491
2014 $followupParams['subject'] = $params['followup_activity_subject'] ?? NULL;
2015 $followupParams['assignee_contact_id'] = $params['followup_assignee_contact_id'] ?? NULL;
2016
2017 // Create target contact for followup.
2018 if (!empty($params['target_contact_id'])) {
2019 $followupParams['target_contact_id'] = $params['target_contact_id'];
2020 }
2021
2022 $followupParams['activity_date_time'] = $params['followup_date'];
2023 $followupActivity = self::create($followupParams);
2024
2025 return $followupActivity;
2026 }
2027
2028 /**
2029 * Get Activity specific File according activity type Id.
2030 *
2031 * @param int $activityTypeId
2032 * Activity id.
2033 * @param string $crmDir
2034 *
2035 * @return string|bool
2036 * if file exists returns $activityTypeFile activity filename otherwise false.
2037 */
2038 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2039 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2040
2041 if ($activityTypes[$activityTypeId]['name']) {
2042 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2043 }
2044 else {
2045 return FALSE;
2046 }
2047
2048 global $civicrm_root;
2049 $config = CRM_Core_Config::singleton();
2050 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2051 if (empty($config->customPHPPathDir)) {
2052 return FALSE;
2053 }
2054 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2055 return FALSE;
2056 }
2057 }
2058
2059 return $activityTypeFile;
2060 }
2061
2062 /**
2063 * Restore the activity.
2064 *
2065 * @param array $params
2066 *
2067 * @return CRM_Activity_DAO_Activity
2068 */
2069 public static function restoreActivity(&$params) {
2070 $activity = new CRM_Activity_DAO_Activity();
2071 $activity->copyValues($params);
2072
2073 $activity->is_deleted = 0;
2074 $result = $activity->save();
2075
2076 return $result;
2077 }
2078
2079 /**
2080 * Return list of activity statuses of a given type.
2081 *
2082 * Note: activity status options use the "grouping" field to distinguish status types.
2083 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2084 *
2085 * @param int $type
2086 *
2087 * @return array
2088 * @throws \CiviCRM_API3_Exception
2089 */
2090 public static function getStatusesByType($type) {
2091 if (!isset(Civi::$statics[__CLASS__][__FUNCTION__])) {
2092 $statuses = civicrm_api3('OptionValue', 'get', [
2093 'option_group_id' => 'activity_status',
2094 'return' => ['value', 'name', 'filter'],
2095 'options' => ['limit' => 0],
2096 ]);
2097 Civi::$statics[__CLASS__][__FUNCTION__] = $statuses['values'];
2098 }
2099 $ret = [];
2100 foreach (Civi::$statics[__CLASS__][__FUNCTION__] as $status) {
2101 if ($status['filter'] == $type) {
2102 $ret[$status['value']] = $status['name'];
2103 }
2104 }
2105 return $ret;
2106 }
2107
2108 /**
2109 * Check if activity is overdue.
2110 *
2111 * @param array $activity
2112 *
2113 * @return bool
2114 * @throws \CiviCRM_API3_Exception
2115 */
2116 public static function isOverdue($activity) {
2117 return array_key_exists($activity['status_id'], self::getStatusesByType(self::INCOMPLETE)) && CRM_Utils_Date::overdue($activity['activity_date_time']);
2118 }
2119
2120 /**
2121 * Get the exportable fields for Activities.
2122 *
2123 * @param string $name
2124 * If it is called by case $name = Case else $name = Activity.
2125 *
2126 * @return array
2127 * array of exportable Fields
2128 */
2129 public static function exportableFields($name = 'Activity') {
2130 self::$_exportableFields[$name] = [];
2131
2132 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2133 $exportableFields = CRM_Activity_DAO_Activity::export();
2134 $exportableFields['source_contact_id'] = [
2135 'title' => ts('Source Contact ID'),
2136 'type' => CRM_Utils_Type::T_INT,
2137 ];
2138 $exportableFields['source_contact'] = [
2139 'title' => ts('Source Contact'),
2140 'type' => CRM_Utils_Type::T_STRING,
2141 ];
2142
2143 // @todo - remove these - they are added by CRM_Core_DAO::appendPseudoConstantsToFields
2144 // below. That search label stuff is referenced in search builder but is likely just
2145 // a hack that duplicates, maybe differently, other functionality.
2146 $activityFields = [
2147 'activity_type' => [
2148 'title' => ts('Activity Type'),
2149 'name' => 'activity_type',
2150 'type' => CRM_Utils_Type::T_STRING,
2151 'searchByLabel' => TRUE,
2152 ],
2153 'activity_status' => [
2154 'title' => ts('Activity Status'),
2155 'name' => 'activity_status',
2156 'type' => CRM_Utils_Type::T_STRING,
2157 'searchByLabel' => TRUE,
2158 ],
2159 'activity_priority' => [
2160 'title' => ts('Activity Priority'),
2161 'name' => 'activity_priority',
2162 'type' => CRM_Utils_Type::T_STRING,
2163 'searchByLabel' => TRUE,
2164 ],
2165 ];
2166 $fields = array_merge($activityFields, $exportableFields);
2167 $fields['activity_type_id']['title'] = ts('Activity Type ID');
2168 $fields['activity_priority_id'] = $fields['priority_id'];
2169
2170 if ($name === 'Case') {
2171 // Now add "case_activity" fields
2172 // Set title to activity fields.
2173 $caseActivityFields = [
2174 'case_source_contact_id' => [
2175 'title' => ts('Activity Reporter'),
2176 'type' => CRM_Utils_Type::T_STRING,
2177 ],
2178 'case_activity_date_time' => [
2179 'title' => ts('Activity Date'),
2180 'type' => CRM_Utils_Type::T_DATE,
2181 ],
2182 'case_activity_type' => [
2183 'title' => ts('Activity Type'),
2184 'type' => CRM_Utils_Type::T_STRING,
2185 ],
2186 'case_activity_medium_id' => [
2187 'title' => ts('Activity Medium'),
2188 'type' => CRM_Utils_Type::T_INT,
2189 ],
2190 'case_activity_is_auto' => [
2191 'title' => ts('Activity Auto-generated?'),
2192 'type' => CRM_Utils_Type::T_BOOLEAN,
2193 ],
2194 ];
2195 $caseStandardFields = ['activity_subject', 'activity_status', 'activity_duration', 'activity_details'];
2196 foreach ($caseStandardFields as $key) {
2197 $caseActivityFields['case_' . $key] = $fields[$key];
2198 }
2199 $fields = $caseActivityFields;
2200 }
2201 // Add custom data
2202 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2203 CRM_Core_DAO::appendPseudoConstantsToFields($fields);
2204 self::$_exportableFields[$name] = $fields;
2205 return self::$_exportableFields[$name];
2206 }
2207
2208 /**
2209 * Get the allowed profile fields for Activities.
2210 *
2211 * @return array
2212 * array of activity profile Fields
2213 */
2214 public static function getProfileFields() {
2215 $exportableFields = self::exportableFields('Activity');
2216 $skipFields = [
2217 'activity_id',
2218 'activity_type',
2219 'source_contact_id',
2220 'source_contact',
2221 'activity_campaign',
2222 'activity_is_test',
2223 'is_current_revision',
2224 'activity_is_deleted',
2225 ];
2226 $config = CRM_Core_Config::singleton();
2227 if (!in_array('CiviCampaign', $config->enableComponents)) {
2228 $skipFields[] = 'activity_engagement_level';
2229 }
2230
2231 foreach ($skipFields as $field) {
2232 if (isset($exportableFields[$field])) {
2233 unset($exportableFields[$field]);
2234 }
2235 }
2236
2237 // hack to use 'activity_type_id' instead of 'activity_type'
2238 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2239 unset($exportableFields['activity_status']);
2240
2241 return $exportableFields;
2242 }
2243
2244 /**
2245 * This function deletes the activity record related to contact record.
2246 *
2247 * This is conditional on there being no target and assignee record
2248 * with other contacts.
2249 *
2250 * @param int $contactId
2251 * ContactId.
2252 *
2253 * @return true/null
2254 */
2255 public static function cleanupActivity($contactId) {
2256 $result = NULL;
2257 if (!$contactId) {
2258 return $result;
2259 }
2260 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2261 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2262
2263 $transaction = new CRM_Core_Transaction();
2264
2265 // delete activity if there is no record in civicrm_activity_contact
2266 // pointing to any other contact record
2267 $activityContact = new CRM_Activity_DAO_ActivityContact();
2268 $activityContact->contact_id = $contactId;
2269 $activityContact->record_type_id = $sourceID;
2270 $activityContact->find();
2271
2272 while ($activityContact->fetch()) {
2273 // delete activity_contact record for the deleted contact
2274 $activityContact->delete();
2275
2276 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2277 $activityContactOther->activity_id = $activityContact->activity_id;
2278
2279 // delete activity only if no other contacts connected
2280 if (!$activityContactOther->find(TRUE)) {
2281 $activityParams = ['id' => $activityContact->activity_id];
2282 $result = self::deleteActivity($activityParams);
2283 }
2284
2285 }
2286
2287 $transaction->commit();
2288
2289 return $result;
2290 }
2291
2292 /**
2293 * Does user has sufficient permission for view/edit activity record.
2294 *
2295 * @param int $activityId
2296 * Activity record id.
2297 * @param int $action
2298 * Edit/view.
2299 *
2300 * @return bool
2301 */
2302 public static function checkPermission($activityId, $action) {
2303
2304 if (!$activityId ||
2305 !in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW])
2306 ) {
2307 return FALSE;
2308 }
2309
2310 $activity = new CRM_Activity_DAO_Activity();
2311 $activity->id = $activityId;
2312 if (!$activity->find(TRUE)) {
2313 return FALSE;
2314 }
2315
2316 if (!self::hasPermissionForActivityType($activity->activity_type_id)) {
2317 // this check is redundant for api access / anything that calls the selectWhereClause
2318 // to determine ACLs.
2319 return FALSE;
2320 }
2321 // Return early when it is case activity.
2322 // Check for CiviCase related permission.
2323 if (CRM_Case_BAO_Case::isCaseActivity($activityId)) {
2324 return self::isContactPermittedAccessToCaseActivity($activityId, $action, $activity->activity_type_id);
2325 }
2326
2327 // Check for this permission related to contact.
2328 $permission = CRM_Core_Permission::VIEW;
2329 if ($action == CRM_Core_Action::UPDATE) {
2330 $permission = CRM_Core_Permission::EDIT;
2331 }
2332
2333 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2334 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2335 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2336 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2337
2338 // Check for source contact.
2339 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2340 // Account for possibility of activity not having a source contact (as it may have been deleted).
2341 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
2342 if (!$allow) {
2343 return FALSE;
2344 }
2345
2346 // Check for target and assignee contacts.
2347 // First check for supper permission.
2348 $supPermission = 'view all contacts';
2349 if ($action == CRM_Core_Action::UPDATE) {
2350 $supPermission = 'edit all contacts';
2351 }
2352 $allow = CRM_Core_Permission::check($supPermission);
2353
2354 // User might have sufficient permission, through acls.
2355 if (!$allow) {
2356 $allow = TRUE;
2357 // Get the target contacts.
2358 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2359 foreach ($targetContacts as $cnt => $contactId) {
2360 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2361 $allow = FALSE;
2362 break;
2363 }
2364 }
2365
2366 // Get the assignee contacts.
2367 if ($allow) {
2368 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2369 foreach ($assigneeContacts as $cnt => $contactId) {
2370 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2371 $allow = FALSE;
2372 break;
2373 }
2374 }
2375 }
2376 }
2377
2378 return $allow;
2379 }
2380
2381 /**
2382 * Check if the logged in user has permission for the given case activity.
2383 *
2384 * @param int $activityId
2385 * @param int $action
2386 * @param int $activityTypeID
2387 *
2388 * @return bool
2389 */
2390 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
2391 $oper = 'view';
2392 if ($action == CRM_Core_Action::UPDATE) {
2393 $oper = 'edit';
2394 }
2395 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2396 $oper,
2397 $activityTypeID
2398 );
2399
2400 return $allow;
2401 }
2402
2403 /**
2404 * Check if the logged in user has permission to access the given activity type.
2405 *
2406 * @param int $activityTypeID
2407 *
2408 * @return bool
2409 */
2410 protected static function hasPermissionForActivityType($activityTypeID) {
2411 $permittedActivityTypes = self::getPermittedActivityTypes();
2412 return isset($permittedActivityTypes[$activityTypeID]);
2413 }
2414
2415 /**
2416 * Get the activity types the user is permitted to access.
2417 *
2418 * The types are filtered by the components they have access to. ie. a user
2419 * with access CiviContribute but not CiviMember will see contribution related
2420 * activities and activities with no component (e.g meetings) but not member related ones.
2421 *
2422 * @return array
2423 */
2424 protected static function getPermittedActivityTypes() {
2425 $userID = (int) CRM_Core_Session::getLoggedInContactID();
2426 if (!isset(Civi::$statics[__CLASS__]['permitted_activity_types'][$userID])) {
2427 $permittedActivityTypes = [];
2428 $components = self::activityComponents(FALSE);
2429 $componentClause = empty($components) ? '' : (' OR component_id IN (' . implode(', ', array_keys($components)) . ')');
2430
2431 $types = CRM_Core_DAO::executeQuery(
2432 "
2433 SELECT option_value.value activity_type_id
2434 FROM civicrm_option_value option_value
2435 INNER JOIN civicrm_option_group grp ON (grp.id = option_group_id AND grp.name = 'activity_type')
2436 WHERE component_id IS NULL $componentClause")->fetchAll();
2437 foreach ($types as $type) {
2438 $permittedActivityTypes[$type['activity_type_id']] = (int) $type['activity_type_id'];
2439 }
2440 asort($permittedActivityTypes);
2441 Civi::$statics[__CLASS__]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2442 }
2443 return Civi::$statics[__CLASS__]['permitted_activity_types'][$userID];
2444 }
2445
2446 /**
2447 * @param $params
2448 * @return array
2449 */
2450 protected static function getActivityParamsForDashboardFunctions($params) {
2451 $activityParams = [
2452 'is_deleted' => 0,
2453 'is_current_revision' => 1,
2454 'is_test' => 0,
2455 'contact_id' => $params['contact_id'] ?? NULL,
2456 'activity_date_time' => $params['activity_date_time'] ?? NULL,
2457 'check_permissions' => 1,
2458 'options' => [
2459 'offset' => $params['offset'] ?? 0,
2460 ],
2461 ];
2462
2463 if (!empty($params['activity_status_id'])) {
2464 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2465 }
2466
2467 $activityParams['activity_type_id'] = self::filterActivityTypes($params);
2468 $enabledComponents = self::activityComponents();
2469 // @todo - this appears to be duplicating the activity api.
2470 if (!in_array('CiviCase', $enabledComponents)) {
2471 $activityParams['case_id'] = ['IS NULL' => 1];
2472 }
2473 return $activityParams;
2474 }
2475
2476 /**
2477 * Checks if user has permissions to edit inbound e-mails, either basic info
2478 * or both basic information and content.
2479 *
2480 * @return bool
2481 */
2482 public static function checkEditInboundEmailsPermissions() {
2483 if (CRM_Core_Permission::check('edit inbound email basic information')
2484 || CRM_Core_Permission::check('edit inbound email basic information and content')
2485 ) {
2486 return TRUE;
2487 }
2488
2489 return FALSE;
2490 }
2491
2492 /**
2493 * Get the list of view only activities
2494 *
2495 * @return array
2496 */
2497 public static function getViewOnlyActivityTypeIDs() {
2498 $viewOnlyActivities = [
2499 'Email' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
2500 ];
2501 if (self::checkEditInboundEmailsPermissions()) {
2502 $viewOnlyActivities['Inbound Email'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
2503 }
2504 return $viewOnlyActivities;
2505 }
2506
2507 /**
2508 * Wrapper for ajax activity selector.
2509 *
2510 * @param array $params
2511 * Associated array for params record id.
2512 *
2513 * @return array
2514 * Associated array of contact activities
2515 */
2516 public static function getContactActivitySelector(&$params) {
2517 // Format the params.
2518 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2519 $params['rowCount'] = $params['rp'];
2520 $params['sort'] = $params['sortBy'] ?? NULL;
2521 $params['caseId'] = NULL;
2522 $context = $params['context'] ?? NULL;
2523 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
2524 $activityTypeInfo = civicrm_api3('OptionValue', 'get', [
2525 'option_group_id' => "activity_type",
2526 'options' => ['limit' => 0],
2527 ]);
2528 $activityIcons = [];
2529 foreach ($activityTypeInfo['values'] as $type) {
2530 if (!empty($type['icon'])) {
2531 $activityIcons[$type['value']] = $type['icon'];
2532 }
2533 }
2534 CRM_Utils_Date::convertFormDateToApiFormat($params, 'activity_date_time');
2535
2536 // Get contact activities.
2537 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2538
2539 // Add total.
2540 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2541
2542 // Format params and add links.
2543 $contactActivities = [];
2544
2545 // View-only activity types
2546 $viewOnlyCaseActivityTypeIDs = array_flip(CRM_Activity_BAO_Activity::getViewOnlyActivityTypeIDs());
2547
2548 if (!empty($activities)) {
2549 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2550
2551 // Check logged in user for permission.
2552 $page = new CRM_Core_Page();
2553 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2554 $permissions = [$page->_permission];
2555 if (CRM_Core_Permission::check('delete activities')) {
2556 $permissions[] = CRM_Core_Permission::DELETE;
2557 }
2558
2559 $mask = CRM_Core_Action::mask($permissions);
2560 $userID = CRM_Core_Session::getLoggedInContactID();
2561
2562 foreach ($activities as $activityId => $values) {
2563 $activity = ['source_contact_name' => '', 'target_contact_name' => ''];
2564 $activity['DT_RowId'] = $activityId;
2565 // Add class to this row if overdue.
2566 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2567 if (self::isOverdue($values)) {
2568 $activity['DT_RowClass'] .= ' status-overdue';
2569 }
2570 else {
2571 $activity['DT_RowClass'] .= ' status-ontime';
2572 }
2573
2574 $activity['DT_RowAttr'] = [];
2575 $activity['DT_RowAttr']['data-entity'] = 'activity';
2576 $activity['DT_RowAttr']['data-id'] = $activityId;
2577
2578 $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'];
2579 $activity['subject'] = $values['subject'];
2580
2581 if ($params['contact_id'] == $values['source_contact_id']) {
2582 $activity['source_contact_name'] = $values['source_contact_name'];
2583 }
2584 elseif ($values['source_contact_id']) {
2585 $srcTypeImage = "";
2586 if ($showContactOverlay) {
2587 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2588 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2589 FALSE,
2590 $values['source_contact_id']);
2591 }
2592 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
2593 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2594 }
2595 else {
2596 $activity['source_contact_name'] = '<em>n/a</em>';
2597 }
2598
2599 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2600 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
2601 'civicrm/mailing/report/event',
2602 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2603 }
2604 elseif (!empty($values['recipients'])) {
2605 $activity['target_contact_name'] = $values['recipients'];
2606 }
2607 elseif (isset($values['target_contact_count']) && $values['target_contact_count']) {
2608 $activity['target_contact_name'] = '';
2609 $firstTargetName = reset($values['target_contact_name']);
2610 $firstTargetContactID = key($values['target_contact_name']);
2611
2612 // The first target may not be accessable to the logged in user dev/core#1052
2613 if ($firstTargetName) {
2614 $targetLink = CRM_Utils_System::href($firstTargetName, 'civicrm/contact/view', "reset=1&cid={$firstTargetContactID}");
2615 if ($showContactOverlay) {
2616 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2617 CRM_Contact_BAO_Contact::getContactType($firstTargetContactID),
2618 FALSE,
2619 $firstTargetContactID);
2620 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2621 }
2622 else {
2623 $activity['target_contact_name'] .= $targetLink;
2624 }
2625
2626 if ($extraCount = $values['target_contact_count'] - 1) {
2627 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', [1 => $extraCount]) . ")";
2628 }
2629 if ($showContactOverlay) {
2630 $activity['target_contact_name'] .= "</div> ";
2631 }
2632 }
2633 }
2634 elseif (!$values['target_contact_name']) {
2635 $activity['target_contact_name'] = '<em>n/a</em>';
2636 }
2637
2638 $activity['assignee_contact_name'] = '';
2639 if (empty($values['assignee_contact_name'])) {
2640 $activity['assignee_contact_name'] = '<em>n/a</em>';
2641 }
2642 elseif (!empty($values['assignee_contact_name'])) {
2643 $count = 0;
2644 $activity['assignee_contact_name'] = '';
2645 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2646 if ($acID && $count < 5) {
2647 $assigneeTypeImage = "";
2648 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2649 if ($showContactOverlay) {
2650 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2651 CRM_Contact_BAO_Contact::getContactType($acID),
2652 FALSE,
2653 $acID);
2654 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2655 }
2656 else {
2657 $activity['assignee_contact_name'] .= $assigneeLink;
2658 }
2659
2660 $count++;
2661 if ($count) {
2662 $activity['assignee_contact_name'] .= ";&nbsp;";
2663 }
2664 if ($showContactOverlay) {
2665 $activity['assignee_contact_name'] .= "</div> ";
2666 }
2667
2668 if ($count == 4) {
2669 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2670 break;
2671 }
2672 }
2673 }
2674 }
2675
2676 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2677 $activity['status_id'] = $activityStatus[$values['status_id']];
2678
2679 // build links
2680 $activity['links'] = '';
2681 $accessMailingReport = FALSE;
2682 if (!empty($values['mailingId'])) {
2683 $accessMailingReport = TRUE;
2684 }
2685
2686 // Get action links.
2687
2688 // If this is a case activity, then we hand off to Case's actionLinks instead.
2689 if (!empty($values['case_id']) && Civi::settings()->get('civicaseShowCaseActivities')) {
2690 // This activity belongs to a case.
2691 $caseId = current($values['case_id']);
2692
2693 $activity['subject'] = $values['subject'];
2694
2695 // Get the view and edit (update) links:
2696 $caseActionLinks =
2697 $actionLinks = array_intersect_key(
2698 CRM_Case_Selector_Search::actionLinks(),
2699 array_fill_keys([CRM_Core_Action::VIEW, CRM_Core_Action::UPDATE], NULL));
2700
2701 // Create a Manage Case link (using ADVANCED as can't use two VIEW ones)
2702 $actionLinks[CRM_Core_Action::ADVANCED] = [
2703 "name" => 'Manage Case',
2704 "url" => 'civicrm/contact/view/case',
2705 'qs' => 'reset=1&id=%%caseid%%&cid=%%cid%%&action=view&context=&selectedChild=case',
2706 "title" => ts('Manage Case %1', [1 => $caseId]),
2707 'class' => 'no-popup',
2708 ];
2709
2710 $caseLinkValues = [
2711 'aid' => $activityId,
2712 'caseid' => $caseId,
2713 'cid' => current(CRM_Case_BAO_Case::getCaseClients($caseId) ?? []),
2714 // Unlike other 'context' params, this 'ctx' param is appended raw to the URL.
2715 'cxt' => '',
2716 ];
2717
2718 $caseActivityPermissions = CRM_Core_Action::VIEW | CRM_Core_Action::ADVANCED;
2719 // Allow Edit link if:
2720 // 1. Activity type is NOT view-only type. CRM-5871
2721 // 2. User has edit permission.
2722 if (!isset($viewOnlyCaseActivityTypeIDs[$values['activity_type_id']])
2723 && CRM_Case_BAO_Case::checkPermission($activityId, 'edit', $values['activity_type_id'], $userID)) {
2724 // We're allowed to edit.
2725 $caseActivityPermissions |= CRM_Core_Action::UPDATE;
2726 }
2727
2728 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2729 $caseActivityPermissions,
2730 $caseLinkValues,
2731 ts('more'),
2732 FALSE,
2733 'activity.tab.row',
2734 'Activity',
2735 $values['activity_id']
2736 );
2737 }
2738 else {
2739 // Non-case activity
2740 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2741 CRM_Utils_Array::value('activity_type_id', $values),
2742 CRM_Utils_Array::value('source_record_id', $values),
2743 $accessMailingReport,
2744 CRM_Utils_Array::value('activity_id', $values)
2745 );
2746 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2747
2748 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2749 $actionMask,
2750 [
2751 'id' => $values['activity_id'],
2752 'cid' => $params['contact_id'],
2753 'cxt' => $context,
2754 'caseid' => NULL,
2755 ],
2756 ts('more'),
2757 FALSE,
2758 'activity.tab.row',
2759 'Activity',
2760 $values['activity_id']
2761 );
2762 }
2763
2764 if ($values['is_recurring_activity']) {
2765 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2766 }
2767
2768 array_push($contactActivities, $activity);
2769 }
2770 }
2771
2772 $activitiesDT = [];
2773 $activitiesDT['data'] = $contactActivities;
2774 $activitiesDT['recordsTotal'] = $params['total'];
2775 $activitiesDT['recordsFiltered'] = $params['total'];
2776
2777 return $activitiesDT;
2778 }
2779
2780 /**
2781 * Copy custom fields and attachments from an existing activity to another.
2782 *
2783 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2784 *
2785 * @param array $params
2786 */
2787 public static function copyExtendedActivityData($params) {
2788 // attach custom data to the new activity
2789 $customParams = $htmlType = [];
2790 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2791
2792 if (!empty($customValues)) {
2793 $fieldIds = implode(', ', array_keys($customValues));
2794 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2795 $result = CRM_Core_DAO::executeQuery($sql);
2796
2797 while ($result->fetch()) {
2798 $htmlType[] = $result->id;
2799 }
2800
2801 foreach ($customValues as $key => $value) {
2802 if ($value !== NULL) {
2803 // CRM-10542
2804 if (in_array($key, $htmlType)) {
2805 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2806 $customParams["custom_{$key}_-1"] = [
2807 'name' => $fileValues[0],
2808 'type' => $fileValues[1],
2809 ];
2810 }
2811 else {
2812 $customParams["custom_{$key}_-1"] = $value;
2813 }
2814 }
2815 }
2816 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
2817 $params['mainActivityId'], 'Activity'
2818 );
2819 }
2820
2821 // copy activity attachments ( if any )
2822 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2823 }
2824
2825 /**
2826 * Get activity contact.
2827 *
2828 * @param int $activityId
2829 * @param int $recordTypeID
2830 * @param string $column
2831 *
2832 * @return null
2833 */
2834 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2835 $activityContact = new CRM_Activity_BAO_ActivityContact();
2836 $activityContact->activity_id = $activityId;
2837 if ($recordTypeID) {
2838 $activityContact->record_type_id = $recordTypeID;
2839 }
2840 if ($activityContact->find(TRUE)) {
2841 return $activityContact->$column;
2842 }
2843 return NULL;
2844 }
2845
2846 /**
2847 * Get source contact id.
2848 *
2849 * @param int $activityId
2850 *
2851 * @return null
2852 */
2853 public static function getSourceContactID($activityId) {
2854 static $sourceID = NULL;
2855 if (!$sourceID) {
2856 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2857 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2858 }
2859
2860 return self::getActivityContact($activityId, $sourceID);
2861 }
2862
2863 /**
2864 * Set api filter.
2865 *
2866 * @todo Document what this is for.
2867 *
2868 * @param array $params
2869 */
2870 public function setApiFilter(&$params) {
2871 if (!empty($params['target_contact_id'])) {
2872 $this->selectAdd();
2873 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2874 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2875 $obj = new CRM_Activity_BAO_ActivityContact();
2876 $params['return.target_contact_id'] = 1;
2877 $this->joinAdd($obj, 'LEFT');
2878 $this->selectAdd('civicrm_activity.*');
2879 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
2880 }
2881 }
2882
2883 /**
2884 * Send activity as attachment.
2885 *
2886 * @param object $activity
2887 * @param array $mailToContacts
2888 * @param array $params
2889 *
2890 * @return bool
2891 */
2892 public static function sendToAssignee($activity, $mailToContacts, $params = []) {
2893 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
2894 $clientID = $params['client_id'] ?? NULL;
2895 $caseID = $params['case_id'] ?? NULL;
2896
2897 $ics = new CRM_Activity_BAO_ICalendar($activity);
2898 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
2899 $ics->addAttachment($attachments, $mailToContacts);
2900
2901 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
2902 $ics->cleanup();
2903 return $result;
2904 }
2905 return FALSE;
2906 }
2907
2908 /**
2909 * @return array
2910 */
2911 public static function getEntityRefFilters() {
2912 return [
2913 ['key' => 'activity_type_id', 'value' => ts('Activity Type')],
2914 ['key' => 'status_id', 'value' => ts('Activity Status')],
2915 ];
2916 }
2917
2918 }