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