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