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