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