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