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