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