Wrong parameter passed to executeQuery function
[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'] = civicrm_api3('Case', 'getvalue', [
808 'return' => 'subject',
809 'id' => reset($activity['case_id']),
810 ]);
811 }
812 }
813 else {
814 // @todo this generic assign could just be handled in array declaration earlier.
815 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
816 if ($apiKey == 'campaign_id') {
817 $activities[$id]['campaign'] = CRM_Utils_Array::value($activities[$id][$expectedName], $allCampaigns);
818 }
819 }
820 }
821 // if deleted, wrap in <del>
822 if (!empty($activity['source_contact_id']) &&
823 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
824 ) {
825 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
826 }
827 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getParentFor($id, 'civicrm_activity');
828 }
829
830 return $activities;
831 }
832
833 /**
834 * Filter the activity types to only return the ones we actually asked for
835 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
836 *
837 * @param $params
838 * @return array|null (Use in Activity.get API activity_type_id)
839 */
840 public static function filterActivityTypes($params) {
841 $activityTypes = [];
842
843 // If no activity types are specified, get all the active ones
844 if (empty($params['activity_type_id'])) {
845 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'get');
846 }
847
848 // If no activity types are specified or excluded, return the list of all active ones
849 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
850 if (!empty($activityTypes)) {
851 return ['IN' => array_keys($activityTypes)];
852 }
853 return NULL;
854 }
855
856 // If we have specified activity types, build a list to return, excluding the ones we don't want.
857 if (!empty($params['activity_type_id'])) {
858 if (!is_array($params['activity_type_id'])) {
859 // Turn it into array if only one specified, so we don't duplicate processing below
860 $params['activity_type_id'] = [$params['activity_type_id'] => $params['activity_type_id']];
861 }
862 foreach ($params['activity_type_id'] as $value) {
863 // Add each activity type that was specified to list
864 $value = CRM_Utils_Type::escape($value, 'Positive');
865 $activityTypes[$value] = $value;
866 }
867 }
868
869 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
870 if (!empty($params['activity_type_exclude_id'])) {
871 if (!is_array($params['activity_type_exclude_id'])) {
872 // Turn it into array if only one specified, so we don't duplicate processing below
873 $params['activity_type_exclude_id'] = [$params['activity_type_exclude_id'] => $params['activity_type_exclude_id']];
874 }
875 foreach ($params['activity_type_exclude_id'] as $value) {
876 // Remove each activity type from list if it should be excluded
877 $value = CRM_Utils_Type::escape($value, 'Positive');
878 if (array_key_exists($value, $activityTypes)) {
879 unset($activityTypes[$value]);
880 }
881 }
882 }
883
884 return ['IN' => array_keys($activityTypes)];
885 }
886
887 /**
888 * @inheritDoc
889 */
890 public function addSelectWhereClause() {
891 $clauses = [];
892 // @todo - check if $permissedActivityTYpes === all activity types and do not add critieria if so.
893 $permittedActivityTypeIDs = self::getPermittedActivityTypes();
894 if (empty($permittedActivityTypeIDs)) {
895 // This just prevents a mysql fail if they have no access - should be extremely edge case.
896 $permittedActivityTypeIDs = [0];
897 }
898 $clauses['activity_type_id'] = ('IN (' . implode(', ', $permittedActivityTypeIDs) . ')');
899
900 $contactClause = CRM_Utils_SQL::mergeSubquery('Contact');
901 if ($contactClause) {
902 $contactClause = implode(' AND contact_id ', $contactClause);
903 $clauses['id'][] = "IN (SELECT activity_id FROM civicrm_activity_contact WHERE contact_id $contactClause)";
904 }
905 CRM_Utils_Hook::selectWhereClause($this, $clauses);
906 return $clauses;
907 }
908
909 /**
910 * Get an array of components that are accessible by the currenct user.
911 *
912 * This means checking if they are enabled and if the user has appropriate permission.
913 *
914 * For most components the permission is access component (e.g 'access CiviContribute').
915 * Exceptions as CiviCampaign (administer CiviCampaign) and CiviCase
916 * (accesses a case function which enforces edit all cases or edit my cases. Case
917 * permissions are also handled on a per activity basis).
918 *
919 * Checks whether logged in user has permission to the component.
920 *
921 * @param bool $excludeComponentHandledActivities
922 * Should we exclude components whose display is handled in the components.
923 * In practice this means should we include CiviCase in the results. Presumbaly
924 * at the time it was decided case activities should be shown in the case framework and
925 * that this concept might be extended later. In practice most places that
926 * call this then re-add CiviCase in some way so it's all a bit... odd.
927 *
928 * @return array
929 * Array of component id and name.
930 */
931 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
932 $components = [];
933 $compInfo = CRM_Core_Component::getEnabledComponents();
934 foreach ($compInfo as $compObj) {
935 $includeComponent = !$excludeComponentHandledActivities || !empty($compObj->info['showActivitiesInCore']);
936 if ($includeComponent) {
937 if ($compObj->info['name'] == 'CiviCampaign') {
938 $componentPermission = "administer {$compObj->name}";
939 }
940 else {
941 $componentPermission = "access {$compObj->name}";
942 }
943 if ($compObj->info['name'] == 'CiviCase') {
944 if (CRM_Case_BAO_Case::accessCiviCase()) {
945 $components[$compObj->componentID] = $compObj->info['name'];
946 }
947 }
948 elseif (CRM_Core_Permission::check($componentPermission)) {
949 $components[$compObj->componentID] = $compObj->info['name'];
950 }
951 }
952 }
953
954 return $components;
955 }
956
957 /**
958 * Get the activity Count.
959 *
960 * @param array $input
961 * Array of parameters.
962 * Keys include
963 * - contact_id int contact_id whose activities we want to retrieve
964 * - admin boolean if contact is admin
965 * - caseId int case ID
966 * - context string page on which selector is build
967 * - activity_type_id int|string the activity types we want to restrict by
968 *
969 * @return int
970 * count of activities
971 */
972 public static function getActivitiesCount($input) {
973 $activityParams = self::getActivityParamsForDashboardFunctions($input);
974 return civicrm_api3('Activity', 'getcount', $activityParams);
975 }
976
977 /**
978 * @param int $userID
979 * @param string $subject
980 * @param string $html
981 * @param string $text
982 * @param string $additionalDetails
983 * @param int $campaignID
984 * @param array $attachments
985 * @param int $caseID
986 *
987 * @return int
988 * The created activity ID
989 * @throws \CRM_Core_Exception
990 */
991 public static function createEmailActivity($userID, $subject, $html, $text, $additionalDetails, $campaignID, $attachments, $caseID) {
992 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
993
994 // CRM-6265: save both text and HTML parts in details (if present)
995 if ($html and $text) {
996 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
997 }
998 else {
999 $details = $html ? $html : $text;
1000 $details .= $additionalDetails;
1001 }
1002
1003 $activityParams = [
1004 'source_contact_id' => $userID,
1005 'activity_type_id' => $activityTypeID,
1006 'activity_date_time' => date('YmdHis'),
1007 'subject' => $subject,
1008 'details' => $details,
1009 // FIXME: check for name Completed and get ID from that lookup
1010 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1011 'campaign_id' => $campaignID,
1012 ];
1013 if (!empty($caseID)) {
1014 $activityParams['case_id'] = $caseID;
1015 }
1016
1017 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1018 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1019
1020 // add the attachments to activity params here
1021 if ($attachments) {
1022 // first process them
1023 $activityParams = array_merge($activityParams, $attachments);
1024 }
1025
1026 $activity = civicrm_api3('Activity', 'create', $activityParams);
1027 return $activity['id'];
1028 }
1029
1030 /**
1031 * Send the message to all the contacts.
1032 *
1033 * Also insert a contact activity in each contacts record.
1034 *
1035 * @param array $contactDetails
1036 * The array of contact details to send the email.
1037 * @param string $subject
1038 * The subject of the message.
1039 * @param $text
1040 * @param $html
1041 * @param string $emailAddress
1042 * Use this 'to' email address instead of the default Primary address.
1043 * @param int $userID
1044 * Use this userID if set.
1045 * @param string $from
1046 * @param array $attachments
1047 * The array of attachments if any.
1048 * @param string $cc
1049 * Cc recipient.
1050 * @param string $bcc
1051 * Bcc recipient.
1052 * @param array $contactIds
1053 * Contact ids.
1054 * @param string $additionalDetails
1055 * The additional information of CC and BCC appended to the activity Details.
1056 * @param array $contributionIds
1057 * @param int $campaignId
1058 * @param int $caseId
1059 *
1060 * @return array
1061 * ( sent, activityId) if any email is sent and activityId
1062 * @throws \CRM_Core_Exception
1063 * @throws \CiviCRM_API3_Exception
1064 */
1065 public static function sendEmail(
1066 &$contactDetails,
1067 &$subject,
1068 &$text,
1069 &$html,
1070 $emailAddress,
1071 $userID = NULL,
1072 $from = NULL,
1073 $attachments = NULL,
1074 $cc = NULL,
1075 $bcc = NULL,
1076 $contactIds = NULL,
1077 $additionalDetails = NULL,
1078 $contributionIds = NULL,
1079 $campaignId = NULL,
1080 $caseId = NULL
1081 ) {
1082 // get the contact details of logged in contact, which we set as from email
1083 if ($userID == NULL) {
1084 $userID = CRM_Core_Session::getLoggedInContactID();
1085 }
1086
1087 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1088 if (!$fromEmail) {
1089 return [count($contactDetails), 0, count($contactDetails)];
1090 }
1091 if (!trim($fromDisplayName)) {
1092 $fromDisplayName = $fromEmail;
1093 }
1094
1095 // CRM-4575
1096 // token replacement of addressee/email/postal greetings
1097 // get the tokens added in subject and message
1098 $subjectToken = CRM_Utils_Token::getTokens($subject);
1099 $messageToken = CRM_Utils_Token::getTokens($text);
1100 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1101 $allTokens = array_merge($messageToken, $subjectToken);
1102
1103 if (!$from) {
1104 $from = "$fromDisplayName <$fromEmail>";
1105 }
1106
1107 //create the meta level record first ( email activity )
1108 $activityID = self::createEmailActivity($userID, $subject, $html, $text, $additionalDetails, $campaignId, $attachments, $caseId);
1109
1110 $returnProperties = [];
1111 if (isset($messageToken['contact'])) {
1112 foreach ($messageToken['contact'] as $key => $value) {
1113 $returnProperties[$value] = 1;
1114 }
1115 }
1116
1117 if (isset($subjectToken['contact'])) {
1118 foreach ($subjectToken['contact'] as $key => $value) {
1119 if (!isset($returnProperties[$value])) {
1120 $returnProperties[$value] = 1;
1121 }
1122 }
1123 }
1124
1125 // get token details for contacts, call only if tokens are used
1126 $details = [];
1127 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
1128 list($details) = CRM_Utils_Token::getTokenDetails(
1129 $contactIds,
1130 $returnProperties,
1131 NULL, NULL, FALSE,
1132 $allTokens,
1133 'CRM_Activity_BAO_Activity'
1134 );
1135 }
1136
1137 // call token hook
1138 $tokens = [];
1139 CRM_Utils_Hook::tokens($tokens);
1140 $categories = array_keys($tokens);
1141
1142 $escapeSmarty = FALSE;
1143 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1144 $smarty = CRM_Core_Smarty::singleton();
1145 $escapeSmarty = TRUE;
1146 }
1147
1148 $contributionDetails = [];
1149 if (!empty($contributionIds)) {
1150 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1151 $contributionIds,
1152 $subject,
1153 $subjectToken,
1154 $text,
1155 $html,
1156 $messageToken,
1157 $escapeSmarty
1158 );
1159 }
1160
1161 $sent = $notSent = [];
1162 foreach ($contactDetails as $values) {
1163 $contactId = $values['contact_id'];
1164 $emailAddress = $values['email'];
1165
1166 if (!empty($contributionDetails)) {
1167 $subject = $contributionDetails[$contactId]['subject'];
1168 $text = $contributionDetails[$contactId]['text'];
1169 $html = $contributionDetails[$contactId]['html'];
1170 }
1171
1172 if (!empty($details) && is_array($details["{$contactId}"])) {
1173 // unset email from details since it always returns primary email address
1174 unset($details["{$contactId}"]['email']);
1175 unset($details["{$contactId}"]['email_id']);
1176 $values = array_merge($values, $details["{$contactId}"]);
1177 }
1178
1179 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1180 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1181
1182 // CRM-4539
1183 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1184 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1185 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1186 }
1187 else {
1188 $tokenText = NULL;
1189 }
1190
1191 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1192 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1193 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1194 }
1195 else {
1196 $tokenHtml = NULL;
1197 }
1198
1199 if ($caseId) {
1200 $tokenSubject = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenSubject, $subjectToken, $escapeSmarty);
1201 $tokenText = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenText, $messageToken, $escapeSmarty);
1202 $tokenHtml = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenHtml, $messageToken, $escapeSmarty);
1203 }
1204
1205 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1206 // also add the contact tokens to the template
1207 $smarty->assign_by_ref('contact', $values);
1208
1209 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1210 $tokenText = $smarty->fetch("string:$tokenText");
1211 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1212 }
1213
1214 $sent = FALSE;
1215 if (self::sendMessage(
1216 $from,
1217 $userID,
1218 $contactId,
1219 $tokenSubject,
1220 $tokenText,
1221 $tokenHtml,
1222 $emailAddress,
1223 $activityID,
1224 // get the set of attachments from where they are stored
1225 CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activityID),
1226 $cc,
1227 $bcc
1228 )
1229 ) {
1230 $sent = TRUE;
1231 }
1232 }
1233
1234 return [$sent, $activityID];
1235 }
1236
1237 /**
1238 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1239 *
1240 * @param array $contactDetails
1241 * @param array $activityParams
1242 * @param array $smsProviderParams
1243 * @param array $contactIds
1244 * @param int $sourceContactId This is the source contact Id
1245 *
1246 * @return array(bool $sent, int $activityId, int $success)
1247 * @throws CRM_Core_Exception
1248 */
1249 public static function sendSMS(
1250 &$contactDetails = NULL,
1251 &$activityParams,
1252 &$smsProviderParams = [],
1253 &$contactIds = NULL,
1254 $sourceContactId = NULL
1255 ) {
1256 if (!CRM_Core_Permission::check('send SMS')) {
1257 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1258 }
1259
1260 if (!isset($contactDetails) && !isset($contactIds)) {
1261 throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1262 }
1263 // Populate $contactDetails and $contactIds if only one is set
1264 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1265 foreach ($contactIds as $id) {
1266 try {
1267 $contactDetails[] = civicrm_api3('Contact', 'getsingle', ['contact_id' => $id]);
1268 }
1269 catch (Exception $e) {
1270 // Contact Id doesn't exist
1271 }
1272 }
1273 }
1274 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1275 foreach ($contactDetails as $contact) {
1276 $contactIds[] = $contact['contact_id'];
1277 }
1278 }
1279
1280 // Get logged in User Id
1281 if (empty($sourceContactId)) {
1282 $sourceContactId = CRM_Core_Session::getLoggedInContactID();
1283 }
1284
1285 $text = &$activityParams['sms_text_message'];
1286
1287 // Create the meta level record first ( sms activity )
1288 $activityParams = [
1289 'source_contact_id' => $sourceContactId,
1290 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
1291 'activity_date_time' => date('YmdHis'),
1292 'subject' => $activityParams['activity_subject'],
1293 'details' => $text,
1294 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1295 ];
1296 $activity = self::create($activityParams);
1297 $activityID = $activity->id;
1298
1299 // Process Tokens
1300 // token replacement of addressee/email/postal greetings
1301 // get the tokens added in subject and message
1302 $messageToken = CRM_Utils_Token::getTokens($text);
1303 $returnProperties = [];
1304 if (isset($messageToken['contact'])) {
1305 foreach ($messageToken['contact'] as $key => $value) {
1306 $returnProperties[$value] = 1;
1307 }
1308 }
1309 // Call tokens hook
1310 $tokens = [];
1311 CRM_Utils_Hook::tokens($tokens);
1312 $categories = array_keys($tokens);
1313 // get token details for contacts, call only if tokens are used
1314 $tokenDetails = [];
1315 if (!empty($returnProperties) || !empty($tokens)) {
1316 list($tokenDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
1317 $returnProperties,
1318 NULL, NULL, FALSE,
1319 $messageToken,
1320 'CRM_Activity_BAO_Activity'
1321 );
1322 }
1323
1324 $success = 0;
1325 $errMsgs = [];
1326 foreach ($contactDetails as $contact) {
1327 $contactId = $contact['contact_id'];
1328
1329 // Replace tokens
1330 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
1331 // unset phone from details since it always returns primary number
1332 unset($tokenDetails["{$contactId}"]['phone']);
1333 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1334 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
1335 }
1336 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1337 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1338
1339 // Only send if the phone is of type mobile
1340 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1341 $smsProviderParams['To'] = $contact['phone'];
1342 }
1343 else {
1344 $smsProviderParams['To'] = '';
1345 }
1346
1347 $doNotSms = CRM_Utils_Array::value('do_not_sms', $contact, 0);
1348
1349 if ($doNotSms) {
1350 $errMsgs[] = PEAR::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN);
1351 }
1352 else {
1353 try {
1354 $sendResult = self::sendSMSMessage(
1355 $contactId,
1356 $tokenText,
1357 $smsProviderParams,
1358 $activityID,
1359 $sourceContactId
1360 );
1361 $success++;
1362 }
1363 catch (CRM_Core_Exception $e) {
1364 $errMsgs[] = $e->getMessage();
1365 }
1366 }
1367 }
1368
1369 // If at least one message was sent and no errors
1370 // were generated then return a boolean value of TRUE.
1371 // Otherwise, return FALSE (no messages sent) or
1372 // and array of 1 or more PEAR_Error objects.
1373 $sent = FALSE;
1374 if ($success > 0 && count($errMsgs) == 0) {
1375 $sent = TRUE;
1376 }
1377 elseif (count($errMsgs) > 0) {
1378 $sent = $errMsgs;
1379 }
1380
1381 return [$sent, $activity->id, $success];
1382 }
1383
1384 /**
1385 * Send the sms message to a specific contact.
1386 *
1387 * @param int $toID
1388 * The contact id of the recipient.
1389 * @param $tokenText
1390 * @param array $smsProviderParams
1391 * The params used for sending sms.
1392 * @param int $activityID
1393 * The activity ID that tracks the message.
1394 * @param int $sourceContactID
1395 *
1396 * @return bool true on success
1397 * @throws CRM_Core_Exception
1398 */
1399 public static function sendSMSMessage(
1400 $toID,
1401 &$tokenText,
1402 $smsProviderParams = [],
1403 $activityID,
1404 $sourceContactID = NULL
1405 ) {
1406 $toPhoneNumber = NULL;
1407 if ($smsProviderParams['To']) {
1408 // If phone number is specified use it
1409 $toPhoneNumber = trim($smsProviderParams['To']);
1410 }
1411 elseif ($toID) {
1412 // No phone number specified, so find a suitable one for the contact
1413 $filters = ['is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0];
1414 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
1415 // To get primary mobile phonenumber, if not get the first mobile phonenumber
1416 if (!empty($toPhoneNumbers)) {
1417 $toPhoneNumberDetails = reset($toPhoneNumbers);
1418 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
1419 // Contact allows to send sms
1420 }
1421 }
1422
1423 // make sure both phone are valid
1424 // and that the recipient wants to receive sms
1425 if (empty($toPhoneNumber)) {
1426 throw new CRM_Core_Exception('Recipient phone number is invalid or recipient does not want to receive SMS');
1427 }
1428
1429 $recipient = $toPhoneNumber;
1430 $smsProviderParams['contact_id'] = $toID;
1431 $smsProviderParams['parent_activity_id'] = $activityID;
1432
1433 $providerObj = CRM_SMS_Provider::singleton(['provider_id' => $smsProviderParams['provider_id']]);
1434 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
1435 if (PEAR::isError($sendResult)) {
1436 throw new CRM_Core_Exception($sendResult->getMessage());
1437 }
1438
1439 // add activity target record for every sms that is sent
1440 $targetID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
1441 $activityTargetParams = [
1442 'activity_id' => $activityID,
1443 'contact_id' => $toID,
1444 'record_type_id' => $targetID,
1445 ];
1446 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1447
1448 return TRUE;
1449 }
1450
1451 /**
1452 * Send the message to a specific contact.
1453 *
1454 * @param string $from
1455 * The name and email of the sender.
1456 * @param int $fromID
1457 * @param int $toID
1458 * The contact id of the recipient.
1459 * @param string $subject
1460 * The subject of the message.
1461 * @param $text_message
1462 * @param $html_message
1463 * @param string $emailAddress
1464 * Use this 'to' email address instead of the default Primary address.
1465 * @param int $activityID
1466 * The activity ID that tracks the message.
1467 * @param null $attachments
1468 * @param null $cc
1469 * @param null $bcc
1470 *
1471 * @return bool
1472 * TRUE if successful else FALSE.
1473 */
1474 public static function sendMessage(
1475 $from,
1476 $fromID,
1477 $toID,
1478 &$subject,
1479 &$text_message,
1480 &$html_message,
1481 $emailAddress,
1482 $activityID,
1483 $attachments = NULL,
1484 $cc = NULL,
1485 $bcc = NULL
1486 ) {
1487 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1488 if ($emailAddress) {
1489 $toEmail = trim($emailAddress);
1490 }
1491
1492 // make sure both email addresses are valid
1493 // and that the recipient wants to receive email
1494 if (empty($toEmail) or $toDoNotEmail) {
1495 return FALSE;
1496 }
1497 if (!trim($toDisplayName)) {
1498 $toDisplayName = $toEmail;
1499 }
1500
1501 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1502 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1503
1504 // create the params array
1505 $mailParams = [
1506 'groupName' => 'Activity Email Sender',
1507 'from' => $from,
1508 'toName' => $toDisplayName,
1509 'toEmail' => $toEmail,
1510 'subject' => $subject,
1511 'cc' => $cc,
1512 'bcc' => $bcc,
1513 'text' => $text_message,
1514 'html' => $html_message,
1515 'attachments' => $attachments,
1516 ];
1517
1518 if (!CRM_Utils_Mail::send($mailParams)) {
1519 return FALSE;
1520 }
1521
1522 // add activity target record for every mail that is send
1523 $activityTargetParams = [
1524 'activity_id' => $activityID,
1525 'contact_id' => $toID,
1526 'record_type_id' => $targetID,
1527 ];
1528 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
1529 return TRUE;
1530 }
1531
1532 /**
1533 * Combine all the importable fields from the lower levels object.
1534 *
1535 * The ordering is important, since currently we do not have a weight
1536 * scheme. Adding weight is super important and should be done in the
1537 * next week or so, before this can be called complete.
1538 *
1539 * @param bool $status
1540 *
1541 * @return array
1542 * array of importable Fields
1543 */
1544 public static function &importableFields($status = FALSE) {
1545 if (!self::$_importableFields) {
1546 if (!self::$_importableFields) {
1547 self::$_importableFields = [];
1548 }
1549 if (!$status) {
1550 $fields = ['' => ['title' => ts('- do not import -')]];
1551 }
1552 else {
1553 $fields = ['' => ['title' => ts('- Activity Fields -')]];
1554 }
1555
1556 $tmpFields = CRM_Activity_DAO_Activity::import();
1557 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1558
1559 // Using new Dedupe rule.
1560 $ruleParams = [
1561 'contact_type' => 'Individual',
1562 'used' => 'Unsupervised',
1563 ];
1564 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1565
1566 $tmpConatctField = [];
1567 if (is_array($fieldsArray)) {
1568 foreach ($fieldsArray as $value) {
1569 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1570 $value,
1571 'id',
1572 'column_name'
1573 );
1574 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1575 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1576 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1577 }
1578 }
1579 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1580 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1581 $fields = array_merge($fields, $tmpConatctField);
1582 $fields = array_merge($fields, $tmpFields);
1583 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
1584 self::$_importableFields = $fields;
1585 }
1586 return self::$_importableFields;
1587 }
1588
1589 /**
1590 * @deprecated - use the api instead.
1591 *
1592 * Get the Activities of a target contact.
1593 *
1594 * @param int $contactId
1595 * Id of the contact whose activities need to find.
1596 *
1597 * @return array
1598 * array of activity fields
1599 */
1600 public static function getContactActivity($contactId) {
1601 // @todo remove this function entirely.
1602 $activities = [];
1603 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1604 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1605 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1606 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1607
1608 // First look for activities where contactId is one of the targets
1609 $query = "
1610 SELECT activity_id, record_type_id
1611 FROM civicrm_activity_contact
1612 WHERE contact_id = $contactId
1613 ";
1614 $dao = CRM_Core_DAO::executeQuery($query);
1615 while ($dao->fetch()) {
1616 if ($dao->record_type_id == $targetID) {
1617 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
1618 }
1619 elseif ($dao->record_type_id == $assigneeID) {
1620 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
1621 }
1622 else {
1623 // do source stuff here
1624 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
1625 }
1626 }
1627
1628 $activityIds = array_keys($activities);
1629 if (count($activityIds) < 1) {
1630 return [];
1631 }
1632
1633 $activityIds = implode(',', $activityIds);
1634 $query = "
1635 SELECT activity.id as activity_id,
1636 activity_type_id,
1637 subject, location, activity_date_time, details, status_id
1638 FROM civicrm_activity activity
1639 WHERE activity.id IN ($activityIds)";
1640
1641 $dao = CRM_Core_DAO::executeQuery($query);
1642
1643 while ($dao->fetch()) {
1644 $activities[$dao->activity_id]['id'] = $dao->activity_id;
1645 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
1646 $activities[$dao->activity_id]['subject'] = $dao->subject;
1647 $activities[$dao->activity_id]['location'] = $dao->location;
1648 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
1649 $activities[$dao->activity_id]['details'] = $dao->details;
1650 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
1651 $activities[$dao->activity_id]['activity_name'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id);
1652 $activities[$dao->activity_id]['status'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id);
1653
1654 // set to null if not set
1655 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
1656 $activities[$dao->activity_id]['source_contact_id'] = NULL;
1657 }
1658 }
1659 return $activities;
1660 }
1661
1662 /**
1663 * Add activity for Membership/Event/Contribution.
1664 *
1665 * @param object $activity
1666 * (reference) particular component object.
1667 * @param string $activityType
1668 * For Membership Signup or Renewal.
1669 * @param int $targetContactID
1670 * @param array $params
1671 * Activity params to override.
1672 *
1673 * @return bool|NULL
1674 */
1675 public static function addActivity(
1676 &$activity,
1677 $activityType = 'Membership Signup',
1678 $targetContactID = NULL,
1679 $params = []
1680 ) {
1681 $date = date('YmdHis');
1682 if ($activity->__table == 'civicrm_membership') {
1683 $component = 'Membership';
1684 }
1685 elseif ($activity->__table == 'civicrm_participant') {
1686 if ($activityType != 'Email') {
1687 $activityType = 'Event Registration';
1688 }
1689 $component = 'Event';
1690 }
1691 elseif ($activity->__table == 'civicrm_contribution') {
1692 // create activity record only for Completed Contributions
1693 $contributionCompletedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1694 if ($activity->contribution_status_id != $contributionCompletedStatusId) {
1695 return NULL;
1696 }
1697 $activityType = $component = 'Contribution';
1698
1699 // retrieve existing activity based on source_record_id and activity_type
1700 if (empty($params['id'])) {
1701 $params['id'] = CRM_Utils_Array::value('id', civicrm_api3('Activity', 'Get', [
1702 'source_record_id' => $activity->id,
1703 'activity_type_id' => $activityType,
1704 ]));
1705 }
1706 if (!empty($params['id'])) {
1707 // CRM-13237 : if activity record found, update it with campaign id of contribution
1708 $params['campaign_id'] = $activity->campaign_id;
1709 }
1710
1711 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
1712 }
1713
1714 $activityParams = [
1715 'source_contact_id' => $activity->contact_id,
1716 'source_record_id' => $activity->id,
1717 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
1718 'activity_date_time' => $date,
1719 'is_test' => $activity->is_test,
1720 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1721 'skipRecentView' => TRUE,
1722 'campaign_id' => $activity->campaign_id,
1723 ];
1724 $activityParams = array_merge($activityParams, $params);
1725
1726 if (empty($activityParams['subject'])) {
1727 $activityParams['subject'] = self::getActivitySubject($activity);
1728 }
1729
1730 if (!empty($activity->activity_id)) {
1731 $activityParams['id'] = $activity->activity_id;
1732 }
1733 // create activity with target contacts
1734 $id = CRM_Core_Session::getLoggedInContactID();
1735 if ($id) {
1736 $activityParams['source_contact_id'] = $id;
1737 $activityParams['target_contact_id'][] = $activity->contact_id;
1738 }
1739
1740 // CRM-14945
1741 if (property_exists($activity, 'details')) {
1742 $activityParams['details'] = $activity->details;
1743 }
1744 //CRM-4027
1745 if ($targetContactID) {
1746 $activityParams['target_contact_id'][] = $targetContactID;
1747 }
1748 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
1749 // deal with any exceptions.
1750 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
1751 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
1752 return FALSE;
1753 }
1754 }
1755
1756 /**
1757 * Get activity subject on basis of component object.
1758 *
1759 * @param object $entityObj
1760 * particular component object.
1761 *
1762 * @return string
1763 */
1764 public static function getActivitySubject($entityObj) {
1765 switch ($entityObj->__table) {
1766 case 'civicrm_membership':
1767 $membershipType = CRM_Member_PseudoConstant::membershipType($entityObj->membership_type_id);
1768 $subject = $membershipType ? $membershipType : ts('Membership');
1769
1770 if (is_array($subject)) {
1771 $subject = implode(", ", $subject);
1772 }
1773
1774 if (!CRM_Utils_System::isNull($entityObj->source)) {
1775 $subject .= " - {$entityObj->source}";
1776 }
1777
1778 if ($entityObj->owner_membership_id) {
1779 list($displayName) = CRM_Contact_BAO_Contact::getDisplayAndImage(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id, 'contact_id'));
1780 $subject .= sprintf(' (by %s)', $displayName);
1781 }
1782
1783 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $entityObj->status_id, 'label');
1784 return $subject;
1785
1786 case 'civicrm_participant':
1787 $event = CRM_Event_BAO_Event::getEvents(1, $entityObj->event_id, TRUE, FALSE);
1788 $roles = CRM_Event_PseudoConstant::participantRole();
1789 $status = CRM_Event_PseudoConstant::participantStatus();
1790 $subject = $event[$entityObj->event_id];
1791
1792 if (!empty($roles[$entityObj->role_id])) {
1793 $subject .= ' - ' . $roles[$entityObj->role_id];
1794 }
1795 if (!empty($status[$entityObj->status_id])) {
1796 $subject .= ' - ' . $status[$entityObj->status_id];
1797 }
1798
1799 return $subject;
1800
1801 case 'civicrm_contribution':
1802 $subject = CRM_Utils_Money::format($entityObj->total_amount, $entityObj->currency);
1803 if (!CRM_Utils_System::isNull($entityObj->source)) {
1804 $subject .= " - {$entityObj->source}";
1805 }
1806
1807 // Amount and source could exceed max length of subject column.
1808 return CRM_Utils_String::ellipsify($subject, 255);
1809 }
1810 }
1811
1812 /**
1813 * Get Parent activity for currently viewed activity.
1814 *
1815 * @param int $activityId
1816 * Current activity id.
1817 *
1818 * @return int
1819 * Id of parent activity otherwise false.
1820 */
1821 public static function getParentActivity($activityId) {
1822 static $parentActivities = [];
1823
1824 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
1825
1826 if (!array_key_exists($activityId, $parentActivities)) {
1827 $parentActivities[$activityId] = [];
1828
1829 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1830 $activityId,
1831 'parent_id'
1832 );
1833
1834 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
1835 }
1836
1837 return $parentActivities[$activityId];
1838 }
1839
1840 /**
1841 * Get total count of prior revision of currently viewed activity.
1842 *
1843 * @param $activityID
1844 * Current activity id.
1845 *
1846 * @return int
1847 * $params count of prior activities otherwise false.
1848 */
1849 public static function getPriorCount($activityID) {
1850 static $priorCounts = [];
1851
1852 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1853
1854 if (!array_key_exists($activityID, $priorCounts)) {
1855 $priorCounts[$activityID] = [];
1856 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1857 $activityID,
1858 'original_id'
1859 );
1860 $count = 0;
1861 if ($originalID) {
1862 $query = "
1863 SELECT count( id ) AS cnt
1864 FROM civicrm_activity
1865 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1866 AND is_current_revision = 0
1867 AND id < {$activityID}
1868 ";
1869 $params = [1 => [$originalID, 'Integer']];
1870 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1871 }
1872 $priorCounts[$activityID] = $count ? $count : 0;
1873 }
1874
1875 return $priorCounts[$activityID];
1876 }
1877
1878 /**
1879 * Get all prior activities of currently viewed activity.
1880 *
1881 * @param $activityID
1882 * Current activity id.
1883 * @param bool $onlyPriorRevisions
1884 *
1885 * @return array
1886 * prior activities info.
1887 */
1888 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1889 static $priorActivities = [];
1890
1891 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1892 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1893
1894 if (!array_key_exists($index, $priorActivities)) {
1895 $priorActivities[$index] = [];
1896
1897 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1898 $activityID,
1899 'original_id'
1900 );
1901 if (!$originalID) {
1902 $originalID = $activityID;
1903 }
1904 if ($originalID) {
1905 $query = "
1906 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1907 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1908 WHERE (ca.id = %1 OR ca.original_id = %1)
1909 AND cl.entity_table = 'civicrm_activity'
1910 AND cl.entity_id = ca.id
1911 AND cl.modified_id = c.id
1912 ";
1913 if ($onlyPriorRevisions) {
1914 $query .= " AND ca.id < {$activityID}";
1915 }
1916 $query .= " ORDER BY ca.id DESC";
1917
1918 $params = [1 => [$originalID, 'Integer']];
1919 $dao = CRM_Core_DAO::executeQuery($query, $params);
1920
1921 while ($dao->fetch()) {
1922 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
1923 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
1924 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
1925 }
1926 }
1927 }
1928 return $priorActivities[$index];
1929 }
1930
1931 /**
1932 * Find the latest revision of a given activity.
1933 *
1934 * @param int $activityID
1935 * Prior activity id.
1936 *
1937 * @return int
1938 * current activity id.
1939 */
1940 public static function getLatestActivityId($activityID) {
1941 static $latestActivityIds = [];
1942
1943 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
1944
1945 if (!array_key_exists($activityID, $latestActivityIds)) {
1946 $latestActivityIds[$activityID] = [];
1947
1948 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
1949 $activityID,
1950 'original_id'
1951 );
1952 if ($originalID) {
1953 $activityID = $originalID;
1954 }
1955 $params = [1 => [$activityID, 'Integer']];
1956 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1957
1958 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
1959 }
1960
1961 return $latestActivityIds[$activityID];
1962 }
1963
1964 /**
1965 * Create a follow up a given activity.
1966 *
1967 * @param int $activityId
1968 * activity id of parent activity.
1969 * @param array $params
1970 *
1971 * @return CRM_Activity_BAO_Activity|null|object
1972 */
1973 public static function createFollowupActivity($activityId, $params) {
1974 if (!$activityId) {
1975 return NULL;
1976 }
1977
1978 $followupParams = [];
1979 $followupParams['parent_id'] = $activityId;
1980 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
1981 $followupParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
1982
1983 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1984 // Get Subject of Follow-up Activiity, CRM-4491
1985 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
1986 $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
1987
1988 // Create target contact for followup.
1989 if (!empty($params['target_contact_id'])) {
1990 $followupParams['target_contact_id'] = $params['target_contact_id'];
1991 }
1992
1993 $followupParams['activity_date_time'] = $params['followup_date'];
1994 $followupActivity = self::create($followupParams);
1995
1996 return $followupActivity;
1997 }
1998
1999 /**
2000 * Get Activity specific File according activity type Id.
2001 *
2002 * @param int $activityTypeId
2003 * Activity id.
2004 * @param string $crmDir
2005 *
2006 * @return string|bool
2007 * if file exists returns $activityTypeFile activity filename otherwise false.
2008 */
2009 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2010 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2011
2012 if ($activityTypes[$activityTypeId]['name']) {
2013 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2014 }
2015 else {
2016 return FALSE;
2017 }
2018
2019 global $civicrm_root;
2020 $config = CRM_Core_Config::singleton();
2021 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2022 if (empty($config->customPHPPathDir)) {
2023 return FALSE;
2024 }
2025 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2026 return FALSE;
2027 }
2028 }
2029
2030 return $activityTypeFile;
2031 }
2032
2033 /**
2034 * Restore the activity.
2035 *
2036 * @param array $params
2037 *
2038 * @return CRM_Activity_DAO_Activity
2039 */
2040 public static function restoreActivity(&$params) {
2041 $activity = new CRM_Activity_DAO_Activity();
2042 $activity->copyValues($params);
2043
2044 $activity->is_deleted = 0;
2045 $result = $activity->save();
2046
2047 return $result;
2048 }
2049
2050 /**
2051 * Return list of activity statuses of a given type.
2052 *
2053 * Note: activity status options use the "grouping" field to distinguish status types.
2054 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2055 *
2056 * @param int $type
2057 *
2058 * @return array
2059 */
2060 public static function getStatusesByType($type) {
2061 if (!isset(Civi::$statics[__CLASS__][__FUNCTION__])) {
2062 $statuses = civicrm_api3('OptionValue', 'get', [
2063 'option_group_id' => 'activity_status',
2064 'return' => ['value', 'name', 'filter'],
2065 'options' => ['limit' => 0],
2066 ]);
2067 Civi::$statics[__CLASS__][__FUNCTION__] = $statuses['values'];
2068 }
2069 $ret = [];
2070 foreach (Civi::$statics[__CLASS__][__FUNCTION__] as $status) {
2071 if ($status['filter'] == $type) {
2072 $ret[$status['value']] = $status['name'];
2073 }
2074 }
2075 return $ret;
2076 }
2077
2078 /**
2079 * Check if activity is overdue.
2080 *
2081 * @param array $activity
2082 *
2083 * @return bool
2084 */
2085 public static function isOverdue($activity) {
2086 return array_key_exists($activity['status_id'], self::getStatusesByType(self::INCOMPLETE)) && CRM_Utils_Date::overdue($activity['activity_date_time']);
2087 }
2088
2089 /**
2090 * Get the exportable fields for Activities.
2091 *
2092 * @param string $name
2093 * If it is called by case $name = Case else $name = Activity.
2094 *
2095 * @return array
2096 * array of exportable Fields
2097 */
2098 public static function exportableFields($name = 'Activity') {
2099 self::$_exportableFields[$name] = [];
2100
2101 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2102 // my case hence we have defined fields as case_*
2103 if ($name == 'Activity') {
2104 $exportableFields = CRM_Activity_DAO_Activity::export();
2105 $exportableFields['source_contact_id'] = [
2106 'title' => ts('Source Contact ID'),
2107 'type' => CRM_Utils_Type::T_INT,
2108 ];
2109 $exportableFields['source_contact'] = [
2110 'title' => ts('Source Contact'),
2111 'type' => CRM_Utils_Type::T_STRING,
2112 ];
2113
2114 // @todo - remove these - they are added by CRM_Core_DAO::appendPseudoConstantsToFields
2115 // below. That search label stuff is referenced in search builder but is likely just
2116 // a hack that duplicates, maybe differently, other functionality.
2117 $Activityfields = [
2118 'activity_type' => [
2119 'title' => ts('Activity Type'),
2120 'name' => 'activity_type',
2121 'type' => CRM_Utils_Type::T_STRING,
2122 'searchByLabel' => TRUE,
2123 ],
2124 'activity_status' => [
2125 'title' => ts('Activity Status'),
2126 'name' => 'activity_status',
2127 'type' => CRM_Utils_Type::T_STRING,
2128 'searchByLabel' => TRUE,
2129 ],
2130 'activity_priority' => [
2131 'title' => ts('Activity Priority'),
2132 'name' => 'activity_priority',
2133 'type' => CRM_Utils_Type::T_STRING,
2134 'searchByLabel' => TRUE,
2135 ],
2136 ];
2137 $fields = array_merge($Activityfields, $exportableFields);
2138 $fields['activity_type_id']['title'] = ts('Activity Type ID');
2139 }
2140 else {
2141 // Set title to activity fields.
2142 $fields = [
2143 'case_activity_subject' => [
2144 'title' => ts('Activity Subject'),
2145 'type' => CRM_Utils_Type::T_STRING,
2146 ],
2147 'case_source_contact_id' => [
2148 'title' => ts('Activity Reporter'),
2149 'type' => CRM_Utils_Type::T_STRING,
2150 ],
2151 'case_recent_activity_date' => [
2152 'title' => ts('Activity Actual Date'),
2153 'type' => CRM_Utils_Type::T_DATE,
2154 ],
2155 'case_scheduled_activity_date' => [
2156 'title' => ts('Activity Scheduled Date'),
2157 'type' => CRM_Utils_Type::T_DATE,
2158 ],
2159 'case_recent_activity_type' => [
2160 'title' => ts('Activity Type'),
2161 'type' => CRM_Utils_Type::T_STRING,
2162 ],
2163 'case_activity_status' => [
2164 'title' => ts('Activity Status'),
2165 'type' => CRM_Utils_Type::T_STRING,
2166 ],
2167 'case_activity_duration' => [
2168 'title' => ts('Activity Duration'),
2169 'type' => CRM_Utils_Type::T_INT,
2170 ],
2171 'case_activity_medium_id' => [
2172 'title' => ts('Activity Medium'),
2173 'type' => CRM_Utils_Type::T_INT,
2174 ],
2175 'case_activity_details' => [
2176 'title' => ts('Activity Details'),
2177 'type' => CRM_Utils_Type::T_TEXT,
2178 ],
2179 'case_activity_is_auto' => [
2180 'title' => ts('Activity Auto-generated?'),
2181 'type' => CRM_Utils_Type::T_BOOLEAN,
2182 ],
2183 ];
2184 }
2185
2186 // add custom data for case activities
2187 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2188 CRM_Core_DAO::appendPseudoConstantsToFields($fields);
2189 self::$_exportableFields[$name] = $fields;
2190 return self::$_exportableFields[$name];
2191 }
2192
2193 /**
2194 * Get the allowed profile fields for Activities.
2195 *
2196 * @return array
2197 * array of activity profile Fields
2198 */
2199 public static function getProfileFields() {
2200 $exportableFields = self::exportableFields('Activity');
2201 $skipFields = [
2202 'activity_id',
2203 'activity_type',
2204 'source_contact_id',
2205 'source_contact',
2206 'activity_campaign',
2207 'activity_is_test',
2208 'is_current_revision',
2209 'activity_is_deleted',
2210 ];
2211 $config = CRM_Core_Config::singleton();
2212 if (!in_array('CiviCampaign', $config->enableComponents)) {
2213 $skipFields[] = 'activity_engagement_level';
2214 }
2215
2216 foreach ($skipFields as $field) {
2217 if (isset($exportableFields[$field])) {
2218 unset($exportableFields[$field]);
2219 }
2220 }
2221
2222 // hack to use 'activity_type_id' instead of 'activity_type'
2223 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2224 unset($exportableFields['activity_status']);
2225
2226 return $exportableFields;
2227 }
2228
2229 /**
2230 * This function deletes the activity record related to contact record.
2231 *
2232 * This is conditional on there being no target and assignee record
2233 * with other contacts.
2234 *
2235 * @param int $contactId
2236 * ContactId.
2237 *
2238 * @return true/null
2239 */
2240 public static function cleanupActivity($contactId) {
2241 $result = NULL;
2242 if (!$contactId) {
2243 return $result;
2244 }
2245 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2246 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2247
2248 $transaction = new CRM_Core_Transaction();
2249
2250 // delete activity if there is no record in civicrm_activity_contact
2251 // pointing to any other contact record
2252 $activityContact = new CRM_Activity_DAO_ActivityContact();
2253 $activityContact->contact_id = $contactId;
2254 $activityContact->record_type_id = $sourceID;
2255 $activityContact->find();
2256
2257 while ($activityContact->fetch()) {
2258 // delete activity_contact record for the deleted contact
2259 $activityContact->delete();
2260
2261 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2262 $activityContactOther->activity_id = $activityContact->activity_id;
2263
2264 // delete activity only if no other contacts connected
2265 if (!$activityContactOther->find(TRUE)) {
2266 $activityParams = ['id' => $activityContact->activity_id];
2267 $result = self::deleteActivity($activityParams);
2268 }
2269
2270 }
2271
2272 $transaction->commit();
2273
2274 return $result;
2275 }
2276
2277 /**
2278 * Does user has sufficient permission for view/edit activity record.
2279 *
2280 * @param int $activityId
2281 * Activity record id.
2282 * @param int $action
2283 * Edit/view.
2284 *
2285 * @return bool
2286 */
2287 public static function checkPermission($activityId, $action) {
2288
2289 if (!$activityId ||
2290 !in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW])
2291 ) {
2292 return FALSE;
2293 }
2294
2295 $activity = new CRM_Activity_DAO_Activity();
2296 $activity->id = $activityId;
2297 if (!$activity->find(TRUE)) {
2298 return FALSE;
2299 }
2300
2301 if (!self::hasPermissionForActivityType($activity->activity_type_id)) {
2302 // this check is redundant for api access / anything that calls the selectWhereClause
2303 // to determine ACLs.
2304 return FALSE;
2305 }
2306 // Return early when it is case activity.
2307 // Check for CiviCase related permission.
2308 if (CRM_Case_BAO_Case::isCaseActivity($activityId)) {
2309 return self::isContactPermittedAccessToCaseActivity($activityId, $action, $activity->activity_type_id);
2310 }
2311
2312 // Check for this permission related to contact.
2313 $permission = CRM_Core_Permission::VIEW;
2314 if ($action == CRM_Core_Action::UPDATE) {
2315 $permission = CRM_Core_Permission::EDIT;
2316 }
2317
2318 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2319 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2320 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2321 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2322
2323 // Check for source contact.
2324 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2325 // Account for possibility of activity not having a source contact (as it may have been deleted).
2326 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
2327 if (!$allow) {
2328 return FALSE;
2329 }
2330
2331 // Check for target and assignee contacts.
2332 // First check for supper permission.
2333 $supPermission = 'view all contacts';
2334 if ($action == CRM_Core_Action::UPDATE) {
2335 $supPermission = 'edit all contacts';
2336 }
2337 $allow = CRM_Core_Permission::check($supPermission);
2338
2339 // User might have sufficient permission, through acls.
2340 if (!$allow) {
2341 $allow = TRUE;
2342 // Get the target contacts.
2343 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2344 foreach ($targetContacts as $cnt => $contactId) {
2345 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2346 $allow = FALSE;
2347 break;
2348 }
2349 }
2350
2351 // Get the assignee contacts.
2352 if ($allow) {
2353 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2354 foreach ($assigneeContacts as $cnt => $contactId) {
2355 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2356 $allow = FALSE;
2357 break;
2358 }
2359 }
2360 }
2361 }
2362
2363 return $allow;
2364 }
2365
2366 /**
2367 * Check if the logged in user has permission for the given case activity.
2368 *
2369 * @param int $activityId
2370 * @param int $action
2371 * @param int $activityTypeID
2372 *
2373 * @return bool
2374 */
2375 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
2376 $oper = 'view';
2377 if ($action == CRM_Core_Action::UPDATE) {
2378 $oper = 'edit';
2379 }
2380 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2381 $oper,
2382 $activityTypeID
2383 );
2384
2385 return $allow;
2386 }
2387
2388 /**
2389 * Check if the logged in user has permission to access the given activity type.
2390 *
2391 * @param int $activityTypeID
2392 *
2393 * @return bool
2394 */
2395 protected static function hasPermissionForActivityType($activityTypeID) {
2396 $permittedActivityTypes = self::getPermittedActivityTypes();
2397 return isset($permittedActivityTypes[$activityTypeID]);
2398 }
2399
2400 /**
2401 * Get the activity types the user is permitted to access.
2402 *
2403 * The types are filtered by the components they have access to. ie. a user
2404 * with access CiviContribute but not CiviMember will see contribution related
2405 * activities and activities with no component (e.g meetings) but not member related ones.
2406 *
2407 * @return array
2408 */
2409 protected static function getPermittedActivityTypes() {
2410 $userID = (int) CRM_Core_Session::getLoggedInContactID();
2411 if (!isset(Civi::$statics[__CLASS__]['permitted_activity_types'][$userID])) {
2412 $permittedActivityTypes = [];
2413 $components = self::activityComponents(FALSE);
2414 $componentClause = empty($components) ? '' : (' OR component_id IN (' . implode(', ', array_keys($components)) . ')');
2415
2416 $types = CRM_Core_DAO::executeQuery(
2417 "
2418 SELECT option_value.value activity_type_id
2419 FROM civicrm_option_value option_value
2420 INNER JOIN civicrm_option_group grp ON (grp.id = option_group_id AND grp.name = 'activity_type')
2421 WHERE component_id IS NULL $componentClause")->fetchAll();
2422 foreach ($types as $type) {
2423 $permittedActivityTypes[$type['activity_type_id']] = (int) $type['activity_type_id'];
2424 }
2425 Civi::$statics[__CLASS__]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2426 }
2427 return Civi::$statics[__CLASS__]['permitted_activity_types'][$userID];
2428 }
2429
2430 /**
2431 * @param $params
2432 * @return array
2433 */
2434 protected static function getActivityParamsForDashboardFunctions($params) {
2435 $activityParams = [
2436 'is_deleted' => 0,
2437 'is_current_revision' => 1,
2438 'is_test' => 0,
2439 'contact_id' => CRM_Utils_Array::value('contact_id', $params),
2440 'activity_date_time' => CRM_Utils_Array::value('activity_date_time', $params),
2441 'check_permissions' => 1,
2442 'options' => [
2443 'offset' => CRM_Utils_Array::value('offset', $params, 0),
2444 ],
2445 ];
2446
2447 if (!empty($params['activity_status_id'])) {
2448 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2449 }
2450
2451 $activityParams['activity_type_id'] = self::filterActivityTypes($params);
2452 $enabledComponents = self::activityComponents();
2453 // @todo - this appears to be duplicating the activity api.
2454 if (!in_array('CiviCase', $enabledComponents)) {
2455 $activityParams['case_id'] = ['IS NULL' => 1];
2456 }
2457 return $activityParams;
2458 }
2459
2460 /**
2461 * Checks if user has permissions to edit inbound e-mails, either basic info
2462 * or both basic information and content.
2463 *
2464 * @return bool
2465 */
2466 public static function checkEditInboundEmailsPermissions() {
2467 if (CRM_Core_Permission::check('edit inbound email basic information')
2468 || CRM_Core_Permission::check('edit inbound email basic information and content')
2469 ) {
2470 return TRUE;
2471 }
2472
2473 return FALSE;
2474 }
2475
2476 /**
2477 * Get the list of view only activities
2478 *
2479 * @return array
2480 */
2481 public static function getViewOnlyActivityTypeIDs() {
2482 $viewOnlyActivities = [
2483 'Email' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
2484 ];
2485 if (self::checkEditInboundEmailsPermissions()) {
2486 $viewOnlyActivities['Inbound Email'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
2487 }
2488 return $viewOnlyActivities;
2489 }
2490
2491 /**
2492 * Wrapper for ajax activity selector.
2493 *
2494 * @param array $params
2495 * Associated array for params record id.
2496 *
2497 * @return array
2498 * Associated array of contact activities
2499 */
2500 public static function getContactActivitySelector(&$params) {
2501 // Format the params.
2502 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2503 $params['rowCount'] = $params['rp'];
2504 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2505 $params['caseId'] = NULL;
2506 $context = CRM_Utils_Array::value('context', $params);
2507 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
2508 $activityTypeInfo = civicrm_api3('OptionValue', 'get', [
2509 'option_group_id' => "activity_type",
2510 'options' => ['limit' => 0],
2511 ]);
2512 $activityIcons = [];
2513 foreach ($activityTypeInfo['values'] as $type) {
2514 if (!empty($type['icon'])) {
2515 $activityIcons[$type['value']] = $type['icon'];
2516 }
2517 }
2518 CRM_Utils_Date::convertFormDateToApiFormat($params, 'activity_date_time');
2519
2520 // Get contact activities.
2521 $activities = CRM_Activity_BAO_Activity::getActivities($params);
2522
2523 // Add total.
2524 $params['total'] = CRM_Activity_BAO_Activity::getActivitiesCount($params);
2525
2526 // Format params and add links.
2527 $contactActivities = [];
2528
2529 if (!empty($activities)) {
2530 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2531
2532 // Check logged in user for permission.
2533 $page = new CRM_Core_Page();
2534 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2535 $permissions = [$page->_permission];
2536 if (CRM_Core_Permission::check('delete activities')) {
2537 $permissions[] = CRM_Core_Permission::DELETE;
2538 }
2539
2540 $mask = CRM_Core_Action::mask($permissions);
2541
2542 foreach ($activities as $activityId => $values) {
2543 $activity = ['source_contact_name' => '', 'target_contact_name' => ''];
2544 $activity['DT_RowId'] = $activityId;
2545 // Add class to this row if overdue.
2546 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2547 if (self::isOverdue($values)) {
2548 $activity['DT_RowClass'] .= ' status-overdue';
2549 }
2550 else {
2551 $activity['DT_RowClass'] .= ' status-ontime';
2552 }
2553
2554 $activity['DT_RowAttr'] = [];
2555 $activity['DT_RowAttr']['data-entity'] = 'activity';
2556 $activity['DT_RowAttr']['data-id'] = $activityId;
2557
2558 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ? '<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2559 $activity['subject'] = $values['subject'];
2560
2561 if ($params['contact_id'] == $values['source_contact_id']) {
2562 $activity['source_contact_name'] = $values['source_contact_name'];
2563 }
2564 elseif ($values['source_contact_id']) {
2565 $srcTypeImage = "";
2566 if ($showContactOverlay) {
2567 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2568 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2569 FALSE,
2570 $values['source_contact_id']);
2571 }
2572 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
2573 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2574 }
2575 else {
2576 $activity['source_contact_name'] = '<em>n/a</em>';
2577 }
2578
2579 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2580 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
2581 'civicrm/mailing/report/event',
2582 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2583 }
2584 elseif (!empty($values['recipients'])) {
2585 $activity['target_contact_name'] = $values['recipients'];
2586 }
2587 elseif (isset($values['target_contact_count']) && $values['target_contact_count']) {
2588 $activity['target_contact_name'] = '';
2589 $firstTargetName = reset($values['target_contact_name']);
2590 $firstTargetContactID = key($values['target_contact_name']);
2591
2592 // The first target may not be accessable to the logged in user dev/core#1052
2593 if ($firstTargetName) {
2594 $targetLink = CRM_Utils_System::href($firstTargetName, 'civicrm/contact/view', "reset=1&cid={$firstTargetContactID}");
2595 if ($showContactOverlay) {
2596 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2597 CRM_Contact_BAO_Contact::getContactType($firstTargetContactID),
2598 FALSE,
2599 $firstTargetContactID);
2600 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2601 }
2602 else {
2603 $activity['target_contact_name'] .= $targetLink;
2604 }
2605
2606 if ($extraCount = $values['target_contact_count'] - 1) {
2607 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', [1 => $extraCount]) . ")";
2608 }
2609 if ($showContactOverlay) {
2610 $activity['target_contact_name'] .= "</div> ";
2611 }
2612 }
2613 }
2614 elseif (!$values['target_contact_name']) {
2615 $activity['target_contact_name'] = '<em>n/a</em>';
2616 }
2617
2618 $activity['assignee_contact_name'] = '';
2619 if (empty($values['assignee_contact_name'])) {
2620 $activity['assignee_contact_name'] = '<em>n/a</em>';
2621 }
2622 elseif (!empty($values['assignee_contact_name'])) {
2623 $count = 0;
2624 $activity['assignee_contact_name'] = '';
2625 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2626 if ($acID && $count < 5) {
2627 $assigneeTypeImage = "";
2628 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2629 if ($showContactOverlay) {
2630 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2631 CRM_Contact_BAO_Contact::getContactType($acID),
2632 FALSE,
2633 $acID);
2634 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2635 }
2636 else {
2637 $activity['assignee_contact_name'] .= $assigneeLink;
2638 }
2639
2640 $count++;
2641 if ($count) {
2642 $activity['assignee_contact_name'] .= ";&nbsp;";
2643 }
2644 if ($showContactOverlay) {
2645 $activity['assignee_contact_name'] .= "</div> ";
2646 }
2647
2648 if ($count == 4) {
2649 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2650 break;
2651 }
2652 }
2653 }
2654 }
2655
2656 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
2657 $activity['status_id'] = $activityStatus[$values['status_id']];
2658
2659 // build links
2660 $activity['links'] = '';
2661 $accessMailingReport = FALSE;
2662 if (!empty($values['mailingId'])) {
2663 $accessMailingReport = TRUE;
2664 }
2665
2666 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
2667 CRM_Utils_Array::value('activity_type_id', $values),
2668 CRM_Utils_Array::value('source_record_id', $values),
2669 $accessMailingReport,
2670 CRM_Utils_Array::value('activity_id', $values)
2671 );
2672
2673 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2674
2675 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
2676 $actionMask,
2677 [
2678 'id' => $values['activity_id'],
2679 'cid' => $params['contact_id'],
2680 'cxt' => $context,
2681 'caseid' => CRM_Utils_Array::value('case_id', $values),
2682 ],
2683 ts('more'),
2684 FALSE,
2685 'activity.tab.row',
2686 'Activity',
2687 $values['activity_id']
2688 );
2689
2690 if ($values['is_recurring_activity']) {
2691 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2692 }
2693
2694 array_push($contactActivities, $activity);
2695 }
2696 }
2697
2698 $activitiesDT = [];
2699 $activitiesDT['data'] = $contactActivities;
2700 $activitiesDT['recordsTotal'] = $params['total'];
2701 $activitiesDT['recordsFiltered'] = $params['total'];
2702
2703 return $activitiesDT;
2704 }
2705
2706 /**
2707 * Copy custom fields and attachments from an existing activity to another.
2708 *
2709 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2710 *
2711 * @param array $params
2712 */
2713 public static function copyExtendedActivityData($params) {
2714 // attach custom data to the new activity
2715 $customParams = $htmlType = [];
2716 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
2717
2718 if (!empty($customValues)) {
2719 $fieldIds = implode(', ', array_keys($customValues));
2720 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2721 $result = CRM_Core_DAO::executeQuery($sql);
2722
2723 while ($result->fetch()) {
2724 $htmlType[] = $result->id;
2725 }
2726
2727 foreach ($customValues as $key => $value) {
2728 if ($value !== NULL) {
2729 // CRM-10542
2730 if (in_array($key, $htmlType)) {
2731 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
2732 $customParams["custom_{$key}_-1"] = [
2733 'name' => $fileValues[0],
2734 'type' => $fileValues[1],
2735 ];
2736 }
2737 else {
2738 $customParams["custom_{$key}_-1"] = $value;
2739 }
2740 }
2741 }
2742 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
2743 $params['mainActivityId'], 'Activity'
2744 );
2745 }
2746
2747 // copy activity attachments ( if any )
2748 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2749 }
2750
2751 /**
2752 * Get activity contact.
2753 *
2754 * @param int $activityId
2755 * @param int $recordTypeID
2756 * @param string $column
2757 *
2758 * @return null
2759 */
2760 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2761 $activityContact = new CRM_Activity_BAO_ActivityContact();
2762 $activityContact->activity_id = $activityId;
2763 if ($recordTypeID) {
2764 $activityContact->record_type_id = $recordTypeID;
2765 }
2766 if ($activityContact->find(TRUE)) {
2767 return $activityContact->$column;
2768 }
2769 return NULL;
2770 }
2771
2772 /**
2773 * Get source contact id.
2774 *
2775 * @param int $activityId
2776 *
2777 * @return null
2778 */
2779 public static function getSourceContactID($activityId) {
2780 static $sourceID = NULL;
2781 if (!$sourceID) {
2782 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2783 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2784 }
2785
2786 return self::getActivityContact($activityId, $sourceID);
2787 }
2788
2789 /**
2790 * Set api filter.
2791 *
2792 * @todo Document what this is for.
2793 *
2794 * @param array $params
2795 */
2796 public function setApiFilter(&$params) {
2797 if (!empty($params['target_contact_id'])) {
2798 $this->selectAdd();
2799 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2800 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2801 $obj = new CRM_Activity_BAO_ActivityContact();
2802 $params['return.target_contact_id'] = 1;
2803 $this->joinAdd($obj, 'LEFT');
2804 $this->selectAdd('civicrm_activity.*');
2805 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
2806 }
2807 }
2808
2809 /**
2810 * Send activity as attachment.
2811 *
2812 * @param object $activity
2813 * @param array $mailToContacts
2814 * @param array $params
2815 *
2816 * @return bool
2817 */
2818 public static function sendToAssignee($activity, $mailToContacts, $params = []) {
2819 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
2820 $clientID = CRM_Utils_Array::value('client_id', $params);
2821 $caseID = CRM_Utils_Array::value('case_id', $params);
2822
2823 $ics = new CRM_Activity_BAO_ICalendar($activity);
2824 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
2825 $ics->addAttachment($attachments, $mailToContacts);
2826
2827 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
2828 $ics->cleanup();
2829 return $result;
2830 }
2831 return FALSE;
2832 }
2833
2834 /**
2835 * @return array
2836 */
2837 public static function getEntityRefFilters() {
2838 return [
2839 ['key' => 'activity_type_id', 'value' => ts('Activity Type')],
2840 ['key' => 'status_id', 'value' => ts('Activity Status')],
2841 ];
2842 }
2843
2844 }