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