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