Merge pull request #13416 from seamuslee001/647_selector_test
[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',
709 'target_contact_name',
710 'assignee_contact_name',
711 'status_id',
712 'subject',
713 'activity_type_id',
714 'activity_type',
715 'case_id',
716 'campaign_id',
717 ];
718 foreach (['case_id' => 'CiviCase', 'campaign_id' => 'CiviCampaign'] as $attr => $component) {
719 if (in_array($component, self::activityComponents())) {
720 $activityParams['return'][] = $attr;
721 }
722 }
466e3a53 723 $result = civicrm_api3('Activity', 'Get', $activityParams);
6a488035 724
5b22d1b8 725 $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
466e3a53 726 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
6a488035 727
7808aae6 728 // CRM-3553, need to check user has access to target groups.
6a488035 729 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
466e3a53 730 $accessCiviMail = ((CRM_Core_Permission::check('access CiviMail')) ||
731 (CRM_Mailing_Info::workflowEnabled() && CRM_Core_Permission::check('create mailings'))
6a488035
TO
732 );
733
466e3a53 734 $mappingParams = array(
735 'id' => 'activity_id',
736 'source_record_id' => 'source_record_id',
737 'activity_type_id' => 'activity_type_id',
738 'activity_date_time' => 'activity_date_time',
739 'status_id' => 'status_id',
740 'subject' => 'subject',
741 'campaign_id' => 'campaign_id',
742 'assignee_contact_name' => 'assignee_contact_name',
743 'target_contact_name' => 'target_contact_name',
744 'source_contact_id' => 'source_contact_id',
745 'source_contact_name' => 'source_contact_name',
746 'case_id' => 'case_id',
466e3a53 747 );
6a488035 748
466e3a53 749 foreach ($result['values'] as $id => $activity) {
6a488035 750
466e3a53 751 $activities[$id] = array();
6a488035 752
a84a8555 753 $isBulkActivity = (!$bulkActivityTypeID || ($bulkActivityTypeID === $activity['activity_type_id']));
84be264e 754
466e3a53 755 foreach ($mappingParams as $apiKey => $expectedName) {
756 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
757 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity, array());
758 if ($apiKey == 'target_contact_name' && count($activity['target_contact_name'])) {
759 $activities[$id]['target_contact_counter'] = count($activity['target_contact_name']);
760 }
91da6cd5 761
466e3a53 762 if ($isBulkActivity) {
763 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
764 $activities[$id]['mailingId'] = FALSE;
765 if ($accessCiviMail &&
766 ($mailingIDs === TRUE || in_array($activity['source_record_id'], $mailingIDs))
767 ) {
768 $activities[$id]['mailingId'] = TRUE;
769 }
770 }
6a488035 771 }
6a488035 772 // case related fields
5161bb0c 773 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
466e3a53 774 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
5161bb0c 775
776 // fetch case subject for case ID found
777 if (!empty($activity['case_id'])) {
778 $activities[$id]['case_subject'] = CRM_Core_DAO::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
779 }
466e3a53 780 }
781 else {
782 $activities[$id][$expectedName] = CRM_Utils_Array::value($apiKey, $activity);
783 if ($apiKey == 'activity_type_id') {
5b22d1b8 784 $activities[$id]['activity_type'] = CRM_Core_PseudoConstant::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $activities[$id][$expectedName]);
466e3a53 785 }
786 elseif ($apiKey == 'campaign_id') {
787 $activities[$id]['campaign'] = CRM_Utils_Array::value($activities[$id][$expectedName], $allCampaigns);
788 }
6a488035
TO
789 }
790 }
5161bb0c 791 // if deleted, wrap in <del>
792 if (!empty($activity['source_contact_id']) &&
793 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
794 ) {
795 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
796 }
797 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getParentFor($id, 'civicrm_activity');
6a488035
TO
798 }
799
84be264e 800 return $activities;
6a488035
TO
801 }
802
5b22d1b8
MW
803 /**
804 * Filter the activity types to only return the ones we actually asked for
805 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
806 *
807 * @param $params
808 * @return array|null (Use in Activity.get API activity_type_id)
809 */
810 public static function filterActivityTypes($params) {
811 $activityTypes = array();
812
813 // If no activity types are specified, get all the active ones
814 if (empty($params['activity_type_id'])) {
815 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'get');
816 }
817
818 // If no activity types are specified or excluded, return the list of all active ones
819 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
820 if (!empty($activityTypes)) {
821 return array('IN' => array_keys($activityTypes));
822 }
823 return NULL;
824 }
825
826 // If we have specified activity types, build a list to return, excluding the ones we don't want.
827 if (!empty($params['activity_type_id'])) {
828 if (!is_array($params['activity_type_id'])) {
829 // Turn it into array if only one specified, so we don't duplicate processing below
830 $params['activity_type_id'] = array($params['activity_type_id'] => $params['activity_type_id']);
831 }
832 foreach ($params['activity_type_id'] as $value) {
833 // Add each activity type that was specified to list
834 $value = CRM_Utils_Type::escape($value, 'Positive');
835 $activityTypes[$value] = $value;
836 }
837 }
838
839 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
840 if (!empty($params['activity_type_exclude_id'])) {
841 if (!is_array($params['activity_type_exclude_id'])) {
842 // Turn it into array if only one specified, so we don't duplicate processing below
843 $params['activity_type_exclude_id'] = array($params['activity_type_exclude_id'] => $params['activity_type_exclude_id']);
844 }
845 foreach ($params['activity_type_exclude_id'] as $value) {
846 // Remove each activity type from list if it should be excluded
847 $value = CRM_Utils_Type::escape($value, 'Positive');
848 if (array_key_exists($value, $activityTypes)) {
849 unset($activityTypes[$value]);
850 }
851 }
852 }
853
854 return array('IN' => array_keys($activityTypes));
855 }
856
6ab43e1b 857 /**
858 * Get the list Activities.
859 *
860 * @deprecated
861 *
862 * @todo - use the api for this - this is working but have temporarily backed out
863 * due to performance issue to be resolved - CRM-20481.
864 *
865 * @param array $input
866 * Array of parameters.
867 * Keys include
868 * - contact_id int contact_id whose activities we want to retrieve
869 * - offset int which row to start from ?
870 * - rowCount int how many rows to fetch
871 * - sort object|array object or array describing sort order for sql query.
872 * - admin boolean if contact is admin
873 * - caseId int case ID
874 * - context string page on which selector is build
875 * - activity_type_id int|string the activitiy types we want to restrict by
876 *
877 * @return array
878 * Relevant data object values of open activities
879 */
880 public static function deprecatedGetActivities($input) {
881 // Step 1: Get the basic activity data.
882 $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity',
883 'activity_type_id',
884 'Bulk Email'
885 );
886
44f817d4 887 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
6ab43e1b 888 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
889 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
890 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
891
892 $config = CRM_Core_Config::singleton();
893
33fa8c9d 894 $activityTempTable = CRM_Utils_SQL_TempTable::build()->setCategory('actdetail')->getName();
6ab43e1b 895
896 $tableFields = array(
897 'activity_id' => 'int unsigned',
898 'activity_date_time' => 'datetime',
899 'source_record_id' => 'int unsigned',
900 'status_id' => 'int unsigned',
901 'subject' => 'varchar(255)',
902 'source_contact_name' => 'varchar(255)',
903 'activity_type_id' => 'int unsigned',
904 'activity_type' => 'varchar(128)',
905 'case_id' => 'int unsigned',
906 'case_subject' => 'varchar(255)',
907 'campaign_id' => 'int unsigned',
908 );
909
910 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
7d3b1a9d 911 $insertValueSQL = $selectColumns = array();
6ab43e1b 912 // The activityTempTable contains the sorted rows
913 // so in order to maintain the sort order as-is we add an auto_increment
914 // field; we can sort by this later to ensure the sort order stays correct.
915 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
916 foreach ($tableFields as $name => $desc) {
917 $sql .= "$name $desc,\n";
918 $insertValueSQL[] = $name;
7d3b1a9d
SL
919 if ($name == 'source_contact_name' && CRM_Utils_SQL::supportsFullGroupBy()) {
920 $selectColumns[] = "ANY_VALUE(tbl.$name)";
921 }
922 else {
923 $selectColumns[] = "tbl.$name";
924 }
6ab43e1b 925 }
926
927 // add unique key on activity_id just to be sure
928 // this cannot be primary key because we need that for the auto_increment
929 // fixed_sort_order field
930 $sql .= "
931 UNIQUE KEY ( activity_id )
932 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
933 ";
934
935 CRM_Core_DAO::executeQuery($sql);
936
7d3b1a9d 937 $insertSQL = "INSERT IGNORE INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
6ab43e1b 938
939 $order = $limit = $groupBy = '';
940 $groupBy = " GROUP BY tbl.activity_id, tbl.activity_type, tbl.case_id, tbl.case_subject ";
941
942 if (!empty($input['sort'])) {
943 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
944 $orderBy = $input['sort']->orderBy();
945 if (!empty($orderBy)) {
946 $order = " ORDER BY $orderBy";
947 }
948 }
949 elseif (trim($input['sort'])) {
950 $sort = CRM_Utils_Type::escape($input['sort'], 'String');
951 $order = " ORDER BY $sort ";
952 }
953 }
954
955 if (empty($order)) {
956 // context = 'activity' in Activities tab.
885d25ac 957 $order = " ORDER BY tbl.activity_date_time desc ";
6ab43e1b 958 }
959
960 if (!empty($input['rowCount']) &&
961 $input['rowCount'] > 0
962 ) {
963 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
964 }
965
966 $input['count'] = FALSE;
967 list($sqlClause, $params) = self::deprecatedGetActivitySQLClause($input);
968
7d3b1a9d 969 $query = sprintf("{$insertSQL} \n SELECT DISTINCT %s from ( %s ) \n as tbl ", implode(', ', $selectColumns), $sqlClause);
6ab43e1b 970
971 // Filter case activities - CRM-5761.
972 $components = self::activityComponents();
973 if (!in_array('CiviCase', $components)) {
974 $query .= "
975LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
976 WHERE civicrm_case_activity.id IS NULL";
977 }
978
979 $query = $query . $groupBy . $order . $limit;
980
981 $dao = CRM_Core_DAO::executeQuery($query, $params);
982
983 // step 2: Get target and assignee contacts for above activities
984 // create temp table for target contacts
33fa8c9d 985 $activityContactTempTable = CRM_Utils_SQL_TempTable::build()->setCategory('actcontact')->getName();
6ab43e1b 986 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
987 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
988 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
989 ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
990
991 CRM_Core_DAO::executeQuery($query);
992
993 // note that we ignore bulk email for targets, since we don't show it in selector
994 $query = "
995INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
996SELECT ac.activity_id,
997 ac.contact_id,
998 ac.record_type_id,
999 c.sort_name,
1000 c.is_deleted
1001FROM {$activityTempTable}
1002INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1003INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1004INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1005WHERE ac.record_type_id != %1
1006";
1007 $params = array(1 => array($targetID, 'Integer'));
1008 CRM_Core_DAO::executeQuery($query, $params);
1009
1010 $activityFields = array("ac.activity_id", "ac.contact_id", "ac.record_type_id", "c.sort_name", "c.is_deleted");
1011 $select = CRM_Contact_BAO_Query::appendAnyValueToSelect($activityFields, "ac.activity_id");
1012
1013 // for each activity insert one target contact
1014 // if we load all target contacts the performance will suffer a lot for mass-activities.
1015 $query = "
1016INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
1017{$select}, count(ac.contact_id)
1018FROM {$activityTempTable}
1019INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1020INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1021INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1022WHERE ac.record_type_id = %1
1023GROUP BY ac.activity_id
1024";
1025
1026 CRM_Core_DAO::executeQuery($query, $params);
1027
1028 // step 3: Combine all temp tables to get final query for activity selector
1029 // sort by the original sort order, stored in fixed_sort_order
1030 $query = "
1031SELECT {$activityTempTable}.*,
1032 {$activityContactTempTable}.contact_id,
1033 {$activityContactTempTable}.record_type_id,
1034 {$activityContactTempTable}.contact_name,
1035 {$activityContactTempTable}.is_deleted,
1036 {$activityContactTempTable}.counter,
1037 re.parent_id as is_recurring_activity
1038FROM {$activityTempTable}
1039INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
1040LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
1041ORDER BY fixed_sort_order
1042 ";
1043
1044 $dao = CRM_Core_DAO::executeQuery($query);
1045
1046 // CRM-3553, need to check user has access to target groups.
1047 $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
1048 $accessCiviMail = (
1049 (CRM_Core_Permission::check('access CiviMail')) ||
1050 (CRM_Mailing_Info::workflowEnabled() &&
1051 CRM_Core_Permission::check('create mailings'))
1052 );
1053
1054 // Get all campaigns.
1055 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
1056 $values = array();
1057 while ($dao->fetch()) {
1058 $activityID = $dao->activity_id;
1059 $values[$activityID]['activity_id'] = $dao->activity_id;
1060 $values[$activityID]['source_record_id'] = $dao->source_record_id;
1061 $values[$activityID]['activity_type_id'] = $dao->activity_type_id;
1062 $values[$activityID]['activity_type'] = $dao->activity_type;
1063 $values[$activityID]['activity_date_time'] = $dao->activity_date_time;
1064 $values[$activityID]['status_id'] = $dao->status_id;
1065 $values[$activityID]['subject'] = $dao->subject;
1066 $values[$activityID]['campaign_id'] = $dao->campaign_id;
1067 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity;
1068
1069 if ($dao->campaign_id) {
1070 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id];
1071 }
1072
1073 if (empty($values[$activityID]['assignee_contact_name'])) {
1074 $values[$activityID]['assignee_contact_name'] = array();
1075 }
1076
1077 if (empty($values[$activityID]['target_contact_name'])) {
1078 $values[$activityID]['target_contact_name'] = array();
1079 $values[$activityID]['target_contact_counter'] = $dao->counter;
1080 }
1081
1082 // if deleted, wrap in <del>
1083 if ($dao->is_deleted) {
1084 $dao->contact_name = "<del>{$dao->contact_name}</del>";
1085 }
1086
1087 if ($dao->record_type_id == $sourceID && $dao->contact_id) {
1088 $values[$activityID]['source_contact_id'] = $dao->contact_id;
1089 $values[$activityID]['source_contact_name'] = $dao->contact_name;
1090 }
1091
1092 if (!$bulkActivityTypeID || ($bulkActivityTypeID != $dao->activity_type_id)) {
1093 // build array of target / assignee names
1094 if ($dao->record_type_id == $targetID && $dao->contact_id) {
1095 $values[$activityID]['target_contact_name'][$dao->contact_id] = $dao->contact_name;
1096 }
1097 if ($dao->record_type_id == $assigneeID && $dao->contact_id) {
1098 $values[$activityID]['assignee_contact_name'][$dao->contact_id] = $dao->contact_name;
1099 }
1100
1101 // case related fields
1102 $values[$activityID]['case_id'] = $dao->case_id;
1103 $values[$activityID]['case_subject'] = $dao->case_subject;
1104 }
1105 else {
1106 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter));
1107 $values[$activityID]['mailingId'] = FALSE;
1108 if (
1109 $accessCiviMail &&
1110 ($mailingIDs === TRUE || in_array($dao->source_record_id, $mailingIDs))
1111 ) {
1112 $values[$activityID]['mailingId'] = TRUE;
1113 }
1114 }
1115 }
1116
1117 return $values;
1118 }
1119
6a488035 1120 /**
c4937fe9 1121 * Get an array of components that are accessible by the currenct user.
0965e988 1122 *
c4937fe9 1123 * This means checking if they are enabled and if the user has appropriate permission.
6a488035 1124 *
c4937fe9 1125 * For most components the permission is access component (e.g 'access CiviContribute').
1126 * Exceptions as CiviCampaign (administer CiviCampaign) and CiviCase
1127 * (accesses a case function which enforces edit all cases or edit my cases. Case
1128 * permissions are also handled on a per activity basis).
1129 *
1130 * Checks whether logged in user has permission to the component.
1131 *
1132 * @param bool $excludeComponentHandledActivities
1133 * Should we exclude components whose display is handled in the components.
1134 * In practice this means should we include CiviCase in the results. Presumbaly
1135 * at the time it was decided case activities should be shown in the case framework and
1136 * that this concept might be extended later. In practice most places that
1137 * call this then re-add CiviCase in some way so it's all a bit... odd.
1138 *
1139 * @return array Array of component id and name.
16b10e64 1140 * Array of component id and name.
59f4c9ee 1141 */
c4937fe9 1142 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
6a488035
TO
1143 $components = array();
1144 $compInfo = CRM_Core_Component::getEnabledComponents();
1145 foreach ($compInfo as $compObj) {
c4937fe9 1146 $includeComponent = !$excludeComponentHandledActivities || !empty($compObj->info['showActivitiesInCore']);
1147 if ($includeComponent) {
6a488035
TO
1148 if ($compObj->info['name'] == 'CiviCampaign') {
1149 $componentPermission = "administer {$compObj->name}";
1150 }
1151 else {
1152 $componentPermission = "access {$compObj->name}";
1153 }
1154 if ($compObj->info['name'] == 'CiviCase') {
1155 if (CRM_Case_BAO_Case::accessCiviCase()) {
1156 $components[$compObj->componentID] = $compObj->info['name'];
1157 }
1158 }
1159 elseif (CRM_Core_Permission::check($componentPermission)) {
1160 $components[$compObj->componentID] = $compObj->info['name'];
1161 }
1162 }
1163 }
1164
1165 return $components;
1166 }
1167
6ab43e1b 1168 /**
1169 * Get the activity Count.
1170 *
1171 * @param array $input
1172 * Array of parameters.
1173 * Keys include
1174 * - contact_id int contact_id whose activities we want to retrieve
1175 * - admin boolean if contact is admin
1176 * - caseId int case ID
1177 * - context string page on which selector is build
1178 * - activity_type_id int|string the activity types we want to restrict by
1179 *
1180 * @return int
1181 * count of activities
1182 */
1183 public static function getActivitiesCount($input) {
84be264e 1184 $activityParams = self::getActivityParamsForDashboardFunctions($input);
1185 return civicrm_api3('Activity', 'getcount', $activityParams);
6ab43e1b 1186 }
1187
1188 /**
1189 * Get the activity Count.
1190 *
5b22d1b8
MW
1191 * @deprecated
1192 *
6ab43e1b 1193 * @param array $input
1194 * Array of parameters.
1195 * Keys include
1196 * - contact_id int contact_id whose activities we want to retrieve
1197 * - admin boolean if contact is admin
1198 * - caseId int case ID
1199 * - context string page on which selector is build
1200 * - activity_type_id int|string the activity types we want to restrict by
1201 *
1202 * @return int
1203 * count of activities
1204 */
1205 public static function deprecatedGetActivitiesCount($input) {
1206 $input['count'] = TRUE;
1207 list($sqlClause, $params) = self::deprecatedGetActivitySQLClause($input);
1208
1209 //filter case activities - CRM-5761
1210 $components = self::activityComponents();
1211 if (!in_array('CiviCase', $components)) {
1212 $query = "
1213 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
1214 FROM ( {$sqlClause} ) as tbl
1215LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
1216 WHERE civicrm_case_activity.id IS NULL";
1217 }
1218 else {
1219 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
1220 }
1221
1222 return CRM_Core_DAO::singleValueQuery($query, $params);
1223 }
1224
1225 /**
1226 * Get the activity sql clause to pick activities.
1227 *
5b22d1b8
MW
1228 * @deprecated
1229 *
6ab43e1b 1230 * @param array $input
1231 * Array of parameters.
1232 * Keys include
1233 * - contact_id int contact_id whose activities we want to retrieve
1234 * - admin boolean if contact is admin
1235 * - caseId int case ID
1236 * - context string page on which selector is build
1237 * - count boolean are we interested in the count clause only?
1238 * - activity_type_id int|string the activity types we want to restrict by
1239 *
1240 * @return int
1241 * count of activities
1242 */
1243 public static function deprecatedGetActivitySQLClause($input) {
1244 $params = array();
1245 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1246
1247 $config = CRM_Core_Config::singleton();
1248 if (!CRM_Utils_Array::value('admin', $input, FALSE)) {
1249 $sourceWhere = ' ac.contact_id = %1 ';
1250 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1251
1252 $params = array(1 => array($input['contact_id'], 'Integer'));
1253 }
1254
1255 $commonClauses = array(
1256 "civicrm_option_group.name = 'activity_type'",
1257 "civicrm_activity.is_deleted = 0",
1258 "civicrm_activity.is_current_revision = 1",
1259 "civicrm_activity.is_test= 0",
1260 );
1261
49d4d222 1262 if (isset($input['activity_date_relative']) ||
1263 (!empty($input['activity_date_low']) || !empty($input['activity_date_high']))
1264 ) {
1265 list($from, $to) = CRM_Utils_Date::getFromTo(
1266 CRM_Utils_Array::value('activity_date_relative', $input, 0),
1267 CRM_Utils_Array::value('activity_date_low', $input),
1268 CRM_Utils_Array::value('activity_date_high', $input)
1269 );
1270 $commonClauses[] = sprintf('civicrm_activity.activity_date_time BETWEEN "%s" AND "%s" ', $from, $to);
1271 }
1272
1273 if (!empty($input['activity_status_id'])) {
1274 $commonClauses[] = sprintf("civicrm_activity.status_id IN (%s)", $input['activity_status_id']);
1275 }
6ab43e1b 1276
1277 // Filter on component IDs.
1278 $components = self::activityComponents();
1279 if (!empty($components)) {
1280 $componentsIn = implode(',', array_keys($components));
1281 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1282 }
1283 else {
1284 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1285 }
1286
1287 // activity type ID clause
1288 if (!empty($input['activity_type_id'])) {
1289 if (is_array($input['activity_type_id'])) {
1290 foreach ($input['activity_type_id'] as $idx => $value) {
1291 $input['activity_type_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1292 }
1293 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1294 }
1295 else {
1296 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_id'], 'Positive');
1297 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1298 }
1299 }
1300
1301 // exclude by activity type clause
1302 if (!empty($input['activity_type_exclude_id'])) {
1303 if (is_array($input['activity_type_exclude_id'])) {
1304 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1305 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type::escape($value, 'Positive');
1306 }
1307 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1308 }
1309 else {
1310 $activityTypeID = CRM_Utils_Type::escape($input['activity_type_exclude_id'], 'Positive');
1311 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1312 }
1313 }
1314
1315 $commonClause = implode(' AND ', $commonClauses);
1316
1317 $includeCaseActivities = FALSE;
1318 if (in_array('CiviCase', $components)) {
1319 $includeCaseActivities = TRUE;
1320 }
1321
1322 // build main activity table select clause
1323 $sourceSelect = '';
1324
44f817d4 1325 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
6ab43e1b 1326 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1327 $sourceJoin = "
1328INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1329INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1330";
1331
1332 if (!$input['count']) {
1333 $sourceSelect = ',
1334 civicrm_activity.activity_date_time,
1335 civicrm_activity.source_record_id,
1336 civicrm_activity.status_id,
1337 civicrm_activity.subject,
1338 contact.sort_name as source_contact_name,
1339 civicrm_option_value.value as activity_type_id,
1340 civicrm_option_value.label as activity_type,
1341 null as case_id, null as case_subject,
1342 civicrm_activity.campaign_id as campaign_id
1343 ';
1344
1345 $sourceJoin .= "
1346LEFT JOIN civicrm_activity_contact src ON (src.activity_id = ac.activity_id AND src.record_type_id = {$sourceID} AND src.contact_id = contact.id)
1347";
1348 }
1349
1350 $sourceClause = "
1351 SELECT civicrm_activity.id as activity_id
1352 {$sourceSelect}
1353 from civicrm_activity
1354 left join civicrm_option_value on
1355 civicrm_activity.activity_type_id = civicrm_option_value.value
1356 left join civicrm_option_group on
1357 civicrm_option_group.id = civicrm_option_value.option_group_id
1358 {$sourceJoin}
1359 where
1360 {$sourceWhere}
1361 AND $commonClause
1362 ";
1363
1364 // Build case clause
1365 // or else exclude Inbound Emails that have been filed on a case.
1366 $caseClause = '';
1367
1368 if ($includeCaseActivities) {
1369 $caseSelect = '';
1370 if (!$input['count']) {
1371 $caseSelect = ',
1372 civicrm_activity.activity_date_time,
1373 civicrm_activity.source_record_id,
1374 civicrm_activity.status_id,
1375 civicrm_activity.subject,
1376 contact.sort_name as source_contact_name,
1377 civicrm_option_value.value as activity_type_id,
1378 civicrm_option_value.label as activity_type,
1379 null as case_id, null as case_subject,
1380 civicrm_activity.campaign_id as campaign_id';
1381 }
1382
1383 $caseClause = "
1384 union all
1385
1386 SELECT civicrm_activity.id as activity_id
1387 {$caseSelect}
1388 from civicrm_activity
1389 inner join civicrm_case_activity on
1390 civicrm_case_activity.activity_id = civicrm_activity.id
1391 inner join civicrm_case on
1392 civicrm_case_activity.case_id = civicrm_case.id
1393 inner join civicrm_case_contact on
1394 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1395 left join civicrm_option_value on
1396 civicrm_activity.activity_type_id = civicrm_option_value.value
1397 left join civicrm_option_group on
1398 civicrm_option_group.id = civicrm_option_value.option_group_id
1399 {$sourceJoin}
1400 where
1401 {$caseWhere}
1402 AND $commonClause
1403 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1404 ( civicrm_option_value.name <> 'Inbound Email' AND
1405 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1406 IS NOT NULL )
1407 )
1408 ";
1409 }
1410
1411 $returnClause = " {$sourceClause} {$caseClause} ";
1412
1413 return array($returnClause, $params);
1414 }
1415
6a488035 1416 /**
0965e988
EM
1417 * Send the message to all the contacts.
1418 *
1419 * Also insert a contact activity in each contacts record.
6a488035 1420 *
041ab3d1
TO
1421 * @param array $contactDetails
1422 * The array of contact details to send the email.
1423 * @param string $subject
1424 * The subject of the message.
fd31fa4c
EM
1425 * @param $text
1426 * @param $html
041ab3d1
TO
1427 * @param string $emailAddress
1428 * Use this 'to' email address instead of the default Primary address.
1429 * @param int $userID
1430 * Use this userID if set.
6a488035 1431 * @param string $from
041ab3d1
TO
1432 * @param array $attachments
1433 * The array of attachments if any.
1434 * @param string $cc
1435 * Cc recipient.
1436 * @param string $bcc
1437 * Bcc recipient.
1438 * @param array $contactIds
1439 * Contact ids.
1440 * @param string $additionalDetails
1441 * The additional information of CC and BCC appended to the activity Details.
cb5d08cd
JP
1442 * @param array $contributionIds
1443 * @param int $campaignId
6a488035 1444 *
a6c01b45
CW
1445 * @return array
1446 * ( sent, activityId) if any email is sent and activityId
6a488035 1447 */
59f4c9ee 1448 public static function sendEmail(
6a488035
TO
1449 &$contactDetails,
1450 &$subject,
1451 &$text,
1452 &$html,
1453 $emailAddress,
9d5494f7
TO
1454 $userID = NULL,
1455 $from = NULL,
6a488035 1456 $attachments = NULL,
9d5494f7
TO
1457 $cc = NULL,
1458 $bcc = NULL,
6c552737 1459 $contactIds = NULL,
7e2ec997 1460 $additionalDetails = NULL,
824989b9 1461 $contributionIds = NULL,
cb5d08cd 1462 $campaignId = NULL
6a488035
TO
1463 ) {
1464 // get the contact details of logged in contact, which we set as from email
1465 if ($userID == NULL) {
3bdcd4ec 1466 $userID = CRM_Core_Session::getLoggedInContactID();
6a488035
TO
1467 }
1468
1469 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
1470 if (!$fromEmail) {
1471 return array(count($contactDetails), 0, count($contactDetails));
1472 }
1473 if (!trim($fromDisplayName)) {
1474 $fromDisplayName = $fromEmail;
1475 }
1476
1477 // CRM-4575
1478 // token replacement of addressee/email/postal greetings
1479 // get the tokens added in subject and message
1480 $subjectToken = CRM_Utils_Token::getTokens($subject);
1481 $messageToken = CRM_Utils_Token::getTokens($text);
1482 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
c7436e9c 1483 $allTokens = array_merge($messageToken, $subjectToken);
6a488035
TO
1484
1485 if (!$from) {
1486 $from = "$fromDisplayName <$fromEmail>";
1487 }
1488
1489 //create the meta level record first ( email activity )
5b22d1b8 1490 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
6a488035
TO
1491
1492 // CRM-6265: save both text and HTML parts in details (if present)
1493 if ($html and $text) {
c1d26519 1494 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
6a488035
TO
1495 }
1496 else {
1497 $details = $html ? $html : $text;
c1d26519 1498 $details .= $additionalDetails;
6a488035
TO
1499 }
1500
1501 $activityParams = array(
1502 'source_contact_id' => $userID,
1503 'activity_type_id' => $activityTypeID,
1504 'activity_date_time' => date('YmdHis'),
1505 'subject' => $subject,
1506 'details' => $details,
1507 // FIXME: check for name Completed and get ID from that lookup
5b22d1b8 1508 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
cb5d08cd 1509 'campaign_id' => $campaignId,
6a488035
TO
1510 );
1511
1512 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1513 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1514
1515 // add the attachments to activity params here
1516 if ($attachments) {
1517 // first process them
1518 $activityParams = array_merge($activityParams,
1519 $attachments
1520 );
1521 }
1522
1523 $activity = self::create($activityParams);
1524
1525 // get the set of attachments from where they are stored
1526 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity',
1527 $activity->id
1528 );
1529 $returnProperties = array();
1530 if (isset($messageToken['contact'])) {
1531 foreach ($messageToken['contact'] as $key => $value) {
1532 $returnProperties[$value] = 1;
1533 }
1534 }
1535
1536 if (isset($subjectToken['contact'])) {
1537 foreach ($subjectToken['contact'] as $key => $value) {
1538 if (!isset($returnProperties[$value])) {
1539 $returnProperties[$value] = 1;
1540 }
1541 }
1542 }
1543
6a488035
TO
1544 // get token details for contacts, call only if tokens are used
1545 $details = array();
db969160 1546 if (!empty($returnProperties) || !empty($tokens) || !empty($allTokens)) {
6a488035
TO
1547 list($details) = CRM_Utils_Token::getTokenDetails(
1548 $contactIds,
1549 $returnProperties,
1550 NULL, NULL, FALSE,
c7436e9c 1551 $allTokens,
6a488035
TO
1552 'CRM_Activity_BAO_Activity'
1553 );
1554 }
1555
1556 // call token hook
1557 $tokens = array();
1558 CRM_Utils_Hook::tokens($tokens);
1559 $categories = array_keys($tokens);
1560
1561 $escapeSmarty = FALSE;
1562 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1563 $smarty = CRM_Core_Smarty::singleton();
1564 $escapeSmarty = TRUE;
1565 }
1566
7e2ec997
E
1567 $contributionDetails = array();
1568 if (!empty($contributionIds)) {
1569 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1570 $contributionIds,
1571 $subject,
1572 $subjectToken,
1573 $text,
1574 $html,
1575 $messageToken,
1576 $escapeSmarty
1577 );
1578 }
1579
6a488035
TO
1580 $sent = $notSent = array();
1581 foreach ($contactDetails as $values) {
1582 $contactId = $values['contact_id'];
1583 $emailAddress = $values['email'];
1584
7e2ec997
E
1585 if (!empty($contributionDetails)) {
1586 $subject = $contributionDetails[$contactId]['subject'];
1587 $text = $contributionDetails[$contactId]['text'];
1588 $html = $contributionDetails[$contactId]['html'];
1589 }
1590
6a488035
TO
1591 if (!empty($details) && is_array($details["{$contactId}"])) {
1592 // unset email from details since it always returns primary email address
1593 unset($details["{$contactId}"]['email']);
1594 unset($details["{$contactId}"]['email_id']);
1595 $values = array_merge($values, $details["{$contactId}"]);
1596 }
1597
1598 $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1599 $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1600
7808aae6 1601 // CRM-4539
6a488035
TO
1602 if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
1603 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1604 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1605 }
1606 else {
1607 $tokenText = NULL;
1608 }
1609
1610 if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
1611 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1612 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1613 }
1614 else {
1615 $tokenHtml = NULL;
1616 }
1617
1618 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
1619 // also add the contact tokens to the template
1620 $smarty->assign_by_ref('contact', $values);
1621
1622 $tokenSubject = $smarty->fetch("string:$tokenSubject");
9d5494f7
TO
1623 $tokenText = $smarty->fetch("string:$tokenText");
1624 $tokenHtml = $smarty->fetch("string:$tokenHtml");
6a488035
TO
1625 }
1626
1627 $sent = FALSE;
1628 if (self::sendMessage(
9d5494f7
TO
1629 $from,
1630 $userID,
1631 $contactId,
1632 $tokenSubject,
1633 $tokenText,
1634 $tokenHtml,
1635 $emailAddress,
1636 $activity->id,
1637 $attachments,
1638 $cc,
1639 $bcc
1640 )
1641 ) {
6a488035
TO
1642 $sent = TRUE;
1643 }
1644 }
1645
1646 return array($sent, $activity->id);
1647 }
1648
ffd93213 1649 /**
36f5faa3 1650 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
0965e988 1651 *
100fef9d
CW
1652 * @param array $contactDetails
1653 * @param array $activityParams
36f5faa3
MW
1654 * @param array $smsProviderParams
1655 * @param array $contactIds
1656 * @param int $sourceContactId This is the source contact Id
ffd93213 1657 *
36f5faa3 1658 * @return array(bool $sent, int $activityId, int $success)
ffd93213
EM
1659 * @throws CRM_Core_Exception
1660 */
59f4c9ee 1661 public static function sendSMS(
36f5faa3 1662 &$contactDetails = NULL,
6a488035 1663 &$activityParams,
36f5faa3
MW
1664 &$smsProviderParams = array(),
1665 &$contactIds = NULL,
1666 $sourceContactId = NULL
6a488035 1667 ) {
63483feb
MM
1668 if (!CRM_Core_Permission::check('send SMS')) {
1669 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1670 }
6a488035 1671
36f5faa3
MW
1672 if (!isset($contactDetails) && !isset($contactIds)) {
1673 Throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1674 }
1675 // Populate $contactDetails and $contactIds if only one is set
1676 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1677 foreach ($contactIds as $id) {
1678 try {
1679 $contactDetails[] = civicrm_api3('Contact', 'getsingle', array('contact_id' => $id));
1680 }
1681 catch (Exception $e) {
1682 // Contact Id doesn't exist
1683 }
1684 }
6a488035 1685 }
36f5faa3
MW
1686 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1687 foreach ($contactDetails as $contact) {
1688 $contactIds[] = $contact['contact_id'];
1689 }
1690 }
6a488035 1691
36f5faa3
MW
1692 // Get logged in User Id
1693 if (empty($sourceContactId)) {
1694 $sourceContactId = CRM_Core_Session::getLoggedInContactID();
1695 }
6a488035 1696
36f5faa3 1697 $text = &$activityParams['sms_text_message'];
6a488035 1698
36f5faa3 1699 // Create the meta level record first ( sms activity )
6a488035 1700 $activityParams = array(
36f5faa3
MW
1701 'source_contact_id' => $sourceContactId,
1702 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
6a488035 1703 'activity_date_time' => date('YmdHis'),
36f5faa3
MW
1704 'subject' => $activityParams['activity_subject'],
1705 'details' => $text,
fc0c4d20 1706 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
6a488035 1707 );
6a488035
TO
1708 $activity = self::create($activityParams);
1709 $activityID = $activity->id;
1710
36f5faa3
MW
1711 // Process Tokens
1712 // token replacement of addressee/email/postal greetings
1713 // get the tokens added in subject and message
1714 $messageToken = CRM_Utils_Token::getTokens($text);
6a488035 1715 $returnProperties = array();
6a488035
TO
1716 if (isset($messageToken['contact'])) {
1717 foreach ($messageToken['contact'] as $key => $value) {
1718 $returnProperties[$value] = 1;
1719 }
1720 }
36f5faa3 1721 // Call tokens hook
6a488035
TO
1722 $tokens = array();
1723 CRM_Utils_Hook::tokens($tokens);
1724 $categories = array_keys($tokens);
6a488035 1725 // get token details for contacts, call only if tokens are used
36f5faa3 1726 $tokenDetails = array();
6a488035 1727 if (!empty($returnProperties) || !empty($tokens)) {
36f5faa3 1728 list($tokenDetails) = CRM_Utils_Token::getTokenDetails($contactIds,
6a488035
TO
1729 $returnProperties,
1730 NULL, NULL, FALSE,
1731 $messageToken,
1732 'CRM_Activity_BAO_Activity'
1733 );
1734 }
1735
f53ea1ce 1736 $success = 0;
c5a6413b 1737 $errMsgs = array();
36f5faa3
MW
1738 foreach ($contactDetails as $contact) {
1739 $contactId = $contact['contact_id'];
6a488035 1740
36f5faa3
MW
1741 // Replace tokens
1742 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
c965c606 1743 // unset phone from details since it always returns primary number
36f5faa3
MW
1744 unset($tokenDetails["{$contactId}"]['phone']);
1745 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1746 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
6a488035 1747 }
36f5faa3
MW
1748 $tokenText = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1749 $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
6a488035 1750
d65e1a68 1751 // Only send if the phone is of type mobile
36f5faa3
MW
1752 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1753 $smsProviderParams['To'] = $contact['phone'];
01aca362
DL
1754 }
1755 else {
36f5faa3 1756 $smsProviderParams['To'] = '';
d65e1a68 1757 }
6a488035 1758
a9b7ee41 1759 $doNotSms = CRM_Utils_Array::value('do_not_sms', $contact, 0);
c5a6413b 1760
a9b7ee41
SL
1761 if ($doNotSms) {
1762 $errMsgs[] = PEAR::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN);
9d5494f7
TO
1763 }
1764 else {
a9b7ee41
SL
1765 $sendResult = self::sendSMSMessage(
1766 $contactId,
1767 $tokenText,
1768 $smsProviderParams,
1769 $activityID,
1770 $sourceContactId
1771 );
1772
1773 if (PEAR::isError($sendResult)) {
1774 // Collect all of the PEAR_Error objects
1775 $errMsgs[] = $sendResult;
1776 }
1777 else {
1778 $success++;
1779 }
6a488035
TO
1780 }
1781 }
1782
c5a6413b
DS
1783 // If at least one message was sent and no errors
1784 // were generated then return a boolean value of TRUE.
1785 // Otherwise, return FALSE (no messages sent) or
1786 // and array of 1 or more PEAR_Error objects.
1787 $sent = FALSE;
1788 if ($success > 0 && count($errMsgs) == 0) {
1789 $sent = TRUE;
9d5494f7
TO
1790 }
1791 elseif (count($errMsgs) > 0) {
c5a6413b
DS
1792 $sent = $errMsgs;
1793 }
1794
f53ea1ce 1795 return array($sent, $activity->id, $success);
6a488035
TO
1796 }
1797
1798 /**
5c9ff055 1799 * Send the sms message to a specific contact.
6a488035 1800 *
041ab3d1
TO
1801 * @param int $toID
1802 * The contact id of the recipient.
77b97be7 1803 * @param $tokenText
36f5faa3 1804 * @param array $smsProviderParams
041ab3d1
TO
1805 * The params used for sending sms.
1806 * @param int $activityID
1807 * The activity ID that tracks the message.
36f5faa3 1808 * @param int $sourceContactID
6a488035 1809 *
72b3a70c
CW
1810 * @return bool|PEAR_Error
1811 * true on success or PEAR_Error object
6a488035 1812 */
59f4c9ee 1813 public static function sendSMSMessage(
9d5494f7 1814 $toID,
6a488035 1815 &$tokenText,
36f5faa3 1816 $smsProviderParams = array(),
e8cb3963 1817 $activityID,
36f5faa3 1818 $sourceContactID = NULL
6a488035 1819 ) {
36f5faa3 1820 $toPhoneNumber = NULL;
36f5faa3
MW
1821 if ($smsProviderParams['To']) {
1822 // If phone number is specified use it
1823 $toPhoneNumber = trim($smsProviderParams['To']);
6a488035
TO
1824 }
1825 elseif ($toID) {
36f5faa3 1826 // No phone number specified, so find a suitable one for the contact
6a488035
TO
1827 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1828 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($toID, FALSE, 'Mobile', $filters);
36f5faa3 1829 // To get primary mobile phonenumber, if not get the first mobile phonenumber
6a488035 1830 if (!empty($toPhoneNumbers)) {
36f5faa3
MW
1831 $toPhoneNumberDetails = reset($toPhoneNumbers);
1832 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
7808aae6 1833 // Contact allows to send sms
6a488035
TO
1834 }
1835 }
1836
1837 // make sure both phone are valid
1838 // and that the recipient wants to receive sms
a9b7ee41 1839 if (empty($toPhoneNumber)) {
c5a6413b
DS
1840 return PEAR::raiseError(
1841 'Recipient phone number is invalid or recipient does not want to receive SMS',
9d5494f7 1842 NULL,
c5a6413b
DS
1843 PEAR_ERROR_RETURN
1844 );
6a488035
TO
1845 }
1846
a9b7ee41 1847 $recipient = $toPhoneNumber;
36f5faa3
MW
1848 $smsProviderParams['contact_id'] = $toID;
1849 $smsProviderParams['parent_activity_id'] = $activityID;
6a488035 1850
36f5faa3
MW
1851 $providerObj = CRM_SMS_Provider::singleton(array('provider_id' => $smsProviderParams['provider_id']));
1852 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
c5a6413b
DS
1853 if (PEAR::isError($sendResult)) {
1854 return $sendResult;
6a488035
TO
1855 }
1856
36f5faa3
MW
1857 // add activity target record for every sms that is sent
1858 $targetID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
6a488035
TO
1859 $activityTargetParams = array(
1860 'activity_id' => $activityID,
9d5494f7 1861 'contact_id' => $toID,
21dfd5f5 1862 'record_type_id' => $targetID,
6a488035 1863 );
1d85d241 1864 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
6a488035
TO
1865
1866 return TRUE;
1867 }
1868
1869 /**
5c9ff055 1870 * Send the message to a specific contact.
6a488035 1871 *
041ab3d1
TO
1872 * @param string $from
1873 * The name and email of the sender.
100fef9d 1874 * @param int $fromID
041ab3d1
TO
1875 * @param int $toID
1876 * The contact id of the recipient.
1877 * @param string $subject
1878 * The subject of the message.
77b97be7
EM
1879 * @param $text_message
1880 * @param $html_message
041ab3d1
TO
1881 * @param string $emailAddress
1882 * Use this 'to' email address instead of the default Primary address.
1883 * @param int $activityID
1884 * The activity ID that tracks the message.
77b97be7
EM
1885 * @param null $attachments
1886 * @param null $cc
1887 * @param null $bcc
6a488035 1888 *
59f4c9ee
TO
1889 * @return bool
1890 * TRUE if successful else FALSE.
6a488035 1891 */
59f4c9ee 1892 public static function sendMessage(
9d5494f7 1893 $from,
6a488035
TO
1894 $fromID,
1895 $toID,
1896 &$subject,
1897 &$text_message,
1898 &$html_message,
1899 $emailAddress,
1900 $activityID,
1901 $attachments = NULL,
9d5494f7
TO
1902 $cc = NULL,
1903 $bcc = NULL
6a488035
TO
1904 ) {
1905 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
1906 if ($emailAddress) {
1907 $toEmail = trim($emailAddress);
1908 }
1909
1910 // make sure both email addresses are valid
1911 // and that the recipient wants to receive email
1912 if (empty($toEmail) or $toDoNotEmail) {
1913 return FALSE;
1914 }
1915 if (!trim($toDisplayName)) {
1916 $toDisplayName = $toEmail;
1917 }
1918
44f817d4 1919 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
a24b3694 1920 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1921
6a488035
TO
1922 // create the params array
1923 $mailParams = array(
1924 'groupName' => 'Activity Email Sender',
1925 'from' => $from,
1926 'toName' => $toDisplayName,
1927 'toEmail' => $toEmail,
1928 'subject' => $subject,
1929 'cc' => $cc,
1930 'bcc' => $bcc,
1931 'text' => $text_message,
1932 'html' => $html_message,
1933 'attachments' => $attachments,
1934 );
1935
1936 if (!CRM_Utils_Mail::send($mailParams)) {
1937 return FALSE;
1938 }
1939
1940 // add activity target record for every mail that is send
1941 $activityTargetParams = array(
1942 'activity_id' => $activityID,
1d85d241 1943 'contact_id' => $toID,
21dfd5f5 1944 'record_type_id' => $targetID,
6a488035 1945 );
1d85d241 1946 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
6a488035
TO
1947 return TRUE;
1948 }
1949
1950 /**
db7de9c1 1951 * Combine all the importable fields from the lower levels object.
6a488035
TO
1952 *
1953 * The ordering is important, since currently we do not have a weight
1954 * scheme. Adding weight is super important and should be done in the
1955 * next week or so, before this can be called complete.
1956 *
dd244018
EM
1957 * @param bool $status
1958 *
a6c01b45
CW
1959 * @return array
1960 * array of importable Fields
6a488035 1961 */
00be9182 1962 public static function &importableFields($status = FALSE) {
6a488035
TO
1963 if (!self::$_importableFields) {
1964 if (!self::$_importableFields) {
1965 self::$_importableFields = array();
1966 }
1967 if (!$status) {
1968 $fields = array('' => array('title' => ts('- do not import -')));
1969 }
1970 else {
1971 $fields = array('' => array('title' => ts('- Activity Fields -')));
1972 }
1973
1974 $tmpFields = CRM_Activity_DAO_Activity::import();
1975 $contactFields = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
1976
1977 // Using new Dedupe rule.
1978 $ruleParams = array(
1979 'contact_type' => 'Individual',
9d5494f7 1980 'used' => 'Unsupervised',
6a488035
TO
1981 );
1982 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1983
1984 $tmpConatctField = array();
1985 if (is_array($fieldsArray)) {
1986 foreach ($fieldsArray as $value) {
1987 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1988 $value,
1989 'id',
1990 'column_name'
1991 );
1992 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1993 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1994 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1995 }
1996 }
1997 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1998 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1999 $fields = array_merge($fields, $tmpConatctField);
2000 $fields = array_merge($fields, $tmpFields);
2001 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
2002 self::$_importableFields = $fields;
2003 }
2004 return self::$_importableFields;
2005 }
2006
2007 /**
a59cecb1 2008 * @deprecated - use the api instead.
2009 *
57507ae6 2010 * Get the Activities of a target contact.
6a488035 2011 *
041ab3d1
TO
2012 * @param int $contactId
2013 * Id of the contact whose activities need to find.
6a488035 2014 *
a6c01b45
CW
2015 * @return array
2016 * array of activity fields
6a488035 2017 */
00be9182 2018 public static function getContactActivity($contactId) {
a59cecb1 2019 // @todo remove this function entirely.
6a488035 2020 $activities = array();
44f817d4 2021 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
a24b3694 2022 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2023 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2024 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
b319d00a 2025
6a488035 2026 // First look for activities where contactId is one of the targets
91da6cd5 2027 $query = "
a24b3694 2028SELECT activity_id, record_type_id
91da6cd5
DL
2029FROM civicrm_activity_contact
2030WHERE contact_id = $contactId
2031";
2032 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 2033 while ($dao->fetch()) {
9d5494f7 2034 if ($dao->record_type_id == $targetID) {
91da6cd5
DL
2035 $activities[$dao->activity_id]['targets'][$contactId] = $contactId;
2036 }
4c9b6178 2037 elseif ($dao->record_type_id == $assigneeID) {
91da6cd5
DL
2038 $activities[$dao->activity_id]['asignees'][$contactId] = $contactId;
2039 }
2040 else {
2041 // do source stuff here
42d30b83 2042 $activities[$dao->activity_id]['source_contact_id'] = $contactId;
91da6cd5 2043 }
6a488035
TO
2044 }
2045
91da6cd5 2046 $activityIds = array_keys($activities);
6a488035
TO
2047 if (count($activityIds) < 1) {
2048 return array();
2049 }
91da6cd5 2050
6a488035 2051 $activityIds = implode(',', $activityIds);
91da6cd5
DL
2052 $query = "
2053SELECT activity.id as activity_id,
2054 activity_type_id,
2055 subject, location, activity_date_time, details, status_id
2056FROM civicrm_activity activity
2057WHERE activity.id IN ($activityIds)";
6a488035 2058
91da6cd5 2059 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 2060
6a488035 2061 while ($dao->fetch()) {
6a488035 2062 $activities[$dao->activity_id]['id'] = $dao->activity_id;
6a488035
TO
2063 $activities[$dao->activity_id]['activity_type_id'] = $dao->activity_type_id;
2064 $activities[$dao->activity_id]['subject'] = $dao->subject;
2065 $activities[$dao->activity_id]['location'] = $dao->location;
2066 $activities[$dao->activity_id]['activity_date_time'] = $dao->activity_date_time;
2067 $activities[$dao->activity_id]['details'] = $dao->details;
2068 $activities[$dao->activity_id]['status_id'] = $dao->status_id;
f9aa1e86
MW
2069 $activities[$dao->activity_id]['activity_name'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id);
2070 $activities[$dao->activity_id]['status'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id);
42d30b83
DL
2071
2072 // set to null if not set
2073 if (!isset($activities[$dao->activity_id]['source_contact_id'])) {
2074 $activities[$dao->activity_id]['source_contact_id'] = NULL;
2075 }
6a488035
TO
2076 }
2077 return $activities;
2078 }
2079
2080 /**
57507ae6 2081 * Add activity for Membership/Event/Contribution.
6a488035 2082 *
041ab3d1
TO
2083 * @param object $activity
2084 * (reference) particular component object.
2085 * @param string $activityType
2086 * For Membership Signup or Renewal.
c490a46a 2087 * @param int $targetContactID
d2460a89 2088 * @param array $params
66a1e31f 2089 * Activity params to override.
6a488035 2090 *
59f4c9ee 2091 * @return bool|NULL
6a488035 2092 */
59f4c9ee 2093 public static function addActivity(
9d5494f7 2094 &$activity,
6a488035 2095 $activityType = 'Membership Signup',
d2460a89
MD
2096 $targetContactID = NULL,
2097 $params = array()
6a488035 2098 ) {
d2460a89 2099 $date = date('YmdHis');
6a488035 2100 if ($activity->__table == 'civicrm_membership') {
6a488035
TO
2101 $component = 'Membership';
2102 }
2103 elseif ($activity->__table == 'civicrm_participant') {
6a488035
TO
2104 if ($activityType != 'Email') {
2105 $activityType = 'Event Registration';
2106 }
2107 $component = 'Event';
2108 }
2109 elseif ($activity->__table == 'civicrm_contribution') {
7808aae6 2110 // create activity record only for Completed Contributions
5b22d1b8
MW
2111 $contributionCompletedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
2112 if ($activity->contribution_status_id != $contributionCompletedStatusId) {
59f4c9ee 2113 return NULL;
6a488035 2114 }
98f0683a 2115 $activityType = $component = 'Contribution';
6a488035 2116
b6d493f3
MD
2117 // retrieve existing activity based on source_record_id and activity_type
2118 if (empty($params['id'])) {
2119 $params['id'] = CRM_Utils_Array::value('id', civicrm_api3('Activity', 'Get', array(
2120 'source_record_id' => $activity->id,
2121 'activity_type_id' => $activityType,
2122 )));
2123 }
6150b2a0
MD
2124 if (!empty($params['id'])) {
2125 // CRM-13237 : if activity record found, update it with campaign id of contribution
2126 $params['campaign_id'] = $activity->campaign_id;
2127 }
b6d493f3 2128
6a488035 2129 $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
6a488035 2130 }
d2460a89 2131
6a488035
TO
2132 $activityParams = array(
2133 'source_contact_id' => $activity->contact_id,
2134 'source_record_id' => $activity->id,
d66c61b6 2135 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
6a488035
TO
2136 'activity_date_time' => $date,
2137 'is_test' => $activity->is_test,
d66c61b6 2138 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
6a488035
TO
2139 'skipRecentView' => TRUE,
2140 'campaign_id' => $activity->campaign_id,
2141 );
d2460a89
MD
2142 $activityParams = array_merge($activityParams, $params);
2143
2144 if (empty($activityParams['subject'])) {
2145 $activityParams['subject'] = self::getActivitySubject($activity);
2146 }
6a488035 2147
6e143f06
WA
2148 if (!empty($activity->activity_id)) {
2149 $activityParams['id'] = $activity->activity_id;
2150 }
6a488035 2151 // create activity with target contacts
6150b2a0
MD
2152 $id = CRM_Core_Session::getLoggedInContactID();
2153 if ($id) {
2154 $activityParams['source_contact_id'] = $id;
71acd4bf 2155 $activityParams['target_contact_id'][] = $activity->contact_id;
6a488035
TO
2156 }
2157
b870f878 2158 // CRM-14945
2159 if (property_exists($activity, 'details')) {
2160 $activityParams['details'] = $activity->details;
2161 }
6a488035
TO
2162 //CRM-4027
2163 if ($targetContactID) {
71acd4bf 2164 $activityParams['target_contact_id'][] = $targetContactID;
6a488035 2165 }
d66c61b6 2166 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
2167 // deal with any exceptions.
6a488035
TO
2168 if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
2169 CRM_Core_Error::fatal("Failed creating Activity for $component of id {$activity->id}");
2170 return FALSE;
2171 }
2172 }
2173
d2460a89 2174 /**
66a1e31f 2175 * Get activity subject on basis of component object.
d2460a89
MD
2176 *
2177 * @param object $entityObj
66a1e31f 2178 * particular component object.
d2460a89
MD
2179 *
2180 * @return string
2181 */
2182 public static function getActivitySubject($entityObj) {
2183 switch ($entityObj->__table) {
2184 case 'civicrm_membership':
2185 $membershipType = CRM_Member_PseudoConstant::membershipType($entityObj->membership_type_id);
2186 $subject = $membershipType ? $membershipType : ts('Membership');
2187
5ab57aa2
SL
2188 if (is_array($subject)) {
2189 $subject = implode(", ", $subject);
2190 }
2191
d2460a89
MD
2192 if (!CRM_Utils_System::isNull($entityObj->source)) {
2193 $subject .= " - {$entityObj->source}";
2194 }
2195
2196 if ($entityObj->owner_membership_id) {
2197 list($displayName) = CRM_Contact_BAO_Contact::getDisplayAndImage(CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id, 'contact_id'));
2198 $subject .= sprintf(' (by %s)', $displayName);
2199 }
2200
2201 $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $entityObj->status_id, 'label');
2202 return $subject;
2203
2204 case 'civicrm_participant':
2205 $event = CRM_Event_BAO_Event::getEvents(1, $entityObj->event_id, TRUE, FALSE);
2206 $roles = CRM_Event_PseudoConstant::participantRole();
2207 $status = CRM_Event_PseudoConstant::participantStatus();
2208 $subject = $event[$entityObj->event_id];
2209
2210 if (!empty($roles[$entityObj->role_id])) {
2211 $subject .= ' - ' . $roles[$entityObj->role_id];
2212 }
2213 if (!empty($status[$entityObj->status_id])) {
2214 $subject .= ' - ' . $status[$entityObj->status_id];
2215 }
2216
2217 return $subject;
2218
2219 case 'civicrm_contribution':
2220 $subject = CRM_Utils_Money::format($entityObj->total_amount, $entityObj->currency);
2221 if (!CRM_Utils_System::isNull($entityObj->source)) {
2222 $subject .= " - {$entityObj->source}";
2223 }
2224
1ea22892 2225 // Amount and source could exceed max length of subject column.
2226 return CRM_Utils_String::ellipsify($subject, 255);
d2460a89
MD
2227 }
2228 }
2229
6a488035 2230 /**
57507ae6 2231 * Get Parent activity for currently viewed activity.
6a488035 2232 *
041ab3d1
TO
2233 * @param int $activityId
2234 * Current activity id.
6a488035 2235 *
a6c01b45 2236 * @return int
57507ae6 2237 * Id of parent activity otherwise false.
6a488035 2238 */
00be9182 2239 public static function getParentActivity($activityId) {
6a488035
TO
2240 static $parentActivities = array();
2241
2242 $activityId = CRM_Utils_Type::escape($activityId, 'Integer');
2243
2244 if (!array_key_exists($activityId, $parentActivities)) {
2245 $parentActivities[$activityId] = array();
2246
2247 $parentId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2248 $activityId,
2249 'parent_id'
2250 );
2251
2252 $parentActivities[$activityId] = $parentId ? $parentId : FALSE;
2253 }
2254
2255 return $parentActivities[$activityId];
2256 }
2257
2258 /**
57507ae6 2259 * Get total count of prior revision of currently viewed activity.
77b97be7 2260 *
041ab3d1
TO
2261 * @param $activityID
2262 * Current activity id.
6a488035 2263 *
a6c01b45
CW
2264 * @return int
2265 * $params count of prior activities otherwise false.
6a488035 2266 */
00be9182 2267 public static function getPriorCount($activityID) {
6a488035
TO
2268 static $priorCounts = array();
2269
2270 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2271
2272 if (!array_key_exists($activityID, $priorCounts)) {
2273 $priorCounts[$activityID] = array();
2274 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2275 $activityID,
2276 'original_id'
2277 );
2278 $count = 0;
2279 if ($originalID) {
2280 $query = "
2281SELECT count( id ) AS cnt
2282FROM civicrm_activity
2283WHERE ( id = {$originalID} OR original_id = {$originalID} )
2284AND is_current_revision = 0
2285AND id < {$activityID}
2286";
2287 $params = array(1 => array($originalID, 'Integer'));
2288 $count = CRM_Core_DAO::singleValueQuery($query, $params);
2289 }
2290 $priorCounts[$activityID] = $count ? $count : 0;
2291 }
2292
2293 return $priorCounts[$activityID];
2294 }
2295
2296 /**
db7de9c1 2297 * Get all prior activities of currently viewed activity.
6a488035 2298 *
041ab3d1
TO
2299 * @param $activityID
2300 * Current activity id.
77b97be7
EM
2301 * @param bool $onlyPriorRevisions
2302 *
a6c01b45
CW
2303 * @return array
2304 * prior activities info.
6a488035 2305 */
00be9182 2306 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
6a488035
TO
2307 static $priorActivities = array();
2308
2309 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2310 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2311
2312 if (!array_key_exists($index, $priorActivities)) {
2313 $priorActivities[$index] = array();
2314
2315 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2316 $activityID,
2317 'original_id'
2318 );
6ea979d9
CW
2319 if (!$originalID) {
2320 $originalID = $activityID;
2321 }
6a488035
TO
2322 if ($originalID) {
2323 $query = "
2324SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2325FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2326WHERE (ca.id = %1 OR ca.original_id = %1)
2327AND cl.entity_table = 'civicrm_activity'
2328AND cl.entity_id = ca.id
2329AND cl.modified_id = c.id
2330";
2331 if ($onlyPriorRevisions) {
2332 $query .= " AND ca.id < {$activityID}";
2333 }
2334 $query .= " ORDER BY ca.id DESC";
2335
2336 $params = array(1 => array($originalID, 'Integer'));
2337 $dao = CRM_Core_DAO::executeQuery($query, $params);
2338
2339 while ($dao->fetch()) {
2340 $priorActivities[$index][$dao->activityID]['id'] = $dao->activityID;
2341 $priorActivities[$index][$dao->activityID]['name'] = $dao->name;
2342 $priorActivities[$index][$dao->activityID]['date'] = $dao->date;
6a488035
TO
2343 }
2344 $dao->free();
2345 }
2346 }
2347 return $priorActivities[$index];
2348 }
2349
2350 /**
db7de9c1 2351 * Find the latest revision of a given activity.
6a488035 2352 *
041ab3d1
TO
2353 * @param int $activityID
2354 * Prior activity id.
6a488035 2355 *
a6c01b45
CW
2356 * @return int
2357 * current activity id.
6a488035 2358 */
00be9182 2359 public static function getLatestActivityId($activityID) {
6a488035
TO
2360 static $latestActivityIds = array();
2361
2362 $activityID = CRM_Utils_Type::escape($activityID, 'Integer');
2363
2364 if (!array_key_exists($activityID, $latestActivityIds)) {
2365 $latestActivityIds[$activityID] = array();
2366
2367 $originalID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity',
2368 $activityID,
2369 'original_id'
2370 );
2371 if ($originalID) {
2372 $activityID = $originalID;
2373 }
2374 $params = array(1 => array($activityID, 'Integer'));
2375 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2376
2377 $latestActivityIds[$activityID] = CRM_Core_DAO::singleValueQuery($query, $params);
2378 }
2379
2380 return $latestActivityIds[$activityID];
2381 }
2382
2383 /**
db7de9c1 2384 * Create a follow up a given activity.
6a488035 2385 *
5a4f6742
CW
2386 * @param int $activityId
2387 * activity id of parent activity.
c490a46a 2388 * @param array $params
77b97be7 2389 *
59f4c9ee 2390 * @return CRM_Activity_BAO_Activity|null|object
6a488035 2391 */
00be9182 2392 public static function createFollowupActivity($activityId, $params) {
6a488035 2393 if (!$activityId) {
59f4c9ee 2394 return NULL;
6a488035
TO
2395 }
2396
6a488035
TO
2397 $followupParams = array();
2398 $followupParams['parent_id'] = $activityId;
3bdcd4ec 2399 $followupParams['source_contact_id'] = CRM_Core_Session::getLoggedInContactID();
5b22d1b8 2400 $followupParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
6a488035
TO
2401
2402 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2403 // Get Subject of Follow-up Activiity, CRM-4491
2404 $followupParams['subject'] = CRM_Utils_Array::value('followup_activity_subject', $params);
90b05581 2405 $followupParams['assignee_contact_id'] = CRM_Utils_Array::value('followup_assignee_contact_id', $params);
6a488035 2406
7808aae6 2407 // Create target contact for followup.
a7488080 2408 if (!empty($params['target_contact_id'])) {
6a488035
TO
2409 $followupParams['target_contact_id'] = $params['target_contact_id'];
2410 }
2411
d7c5e6c3 2412 $followupParams['activity_date_time'] = $params['followup_date'];
6a488035
TO
2413 $followupActivity = self::create($followupParams);
2414
2415 return $followupActivity;
2416 }
2417
2418 /**
100fef9d 2419 * Get Activity specific File according activity type Id.
6a488035 2420 *
041ab3d1
TO
2421 * @param int $activityTypeId
2422 * Activity id.
77b97be7 2423 * @param string $crmDir
6a488035 2424 *
72b3a70c
CW
2425 * @return string|bool
2426 * if file exists returns $activityTypeFile activity filename otherwise false.
6a488035 2427 */
00be9182 2428 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
6a488035
TO
2429 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
2430
2431 if ($activityTypes[$activityTypeId]['name']) {
2432 $activityTypeFile = CRM_Utils_String::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2433 }
2434 else {
2435 return FALSE;
2436 }
2437
2438 global $civicrm_root;
2439 $config = CRM_Core_Config::singleton();
2440 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2441 if (empty($config->customPHPPathDir)) {
2442 return FALSE;
2443 }
2444 elseif (!file_exists(rtrim($config->customPHPPathDir, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2445 return FALSE;
2446 }
2447 }
2448
2449 return $activityTypeFile;
2450 }
2451
2452 /**
ee0ce2ef 2453 * Restore the activity.
6a488035 2454 *
041ab3d1 2455 * @param array $params
6a488035 2456 *
ee0ce2ef 2457 * @return CRM_Activity_DAO_Activity
6a488035
TO
2458 */
2459 public static function restoreActivity(&$params) {
2460 $activity = new CRM_Activity_DAO_Activity();
2461 $activity->copyValues($params);
2462
2463 $activity->is_deleted = 0;
2464 $result = $activity->save();
2465
2466 return $result;
2467 }
2468
760ac501 2469 /**
ce9d78e1
CW
2470 * Return list of activity statuses of a given type.
2471 *
2472 * Note: activity status options use the "grouping" field to distinguish status types.
2473 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
760ac501 2474 *
ce9d78e1 2475 * @param int $type
760ac501
CW
2476 *
2477 * @return array
2478 */
ce9d78e1 2479 public static function getStatusesByType($type) {
760ac501
CW
2480 if (!isset(Civi::$statics[__CLASS__][__FUNCTION__])) {
2481 $statuses = civicrm_api3('OptionValue', 'get', array(
d544ffcd 2482 'option_group_id' => 'activity_status',
ce9d78e1 2483 'return' => array('value', 'name', 'filter'),
760ac501
CW
2484 'options' => array('limit' => 0),
2485 ));
ce9d78e1 2486 Civi::$statics[__CLASS__][__FUNCTION__] = $statuses['values'];
760ac501 2487 }
ce9d78e1
CW
2488 $ret = array();
2489 foreach (Civi::$statics[__CLASS__][__FUNCTION__] as $status) {
2490 if ($status['filter'] == $type) {
2491 $ret[$status['value']] = $status['name'];
2492 }
2493 }
2494 return $ret;
760ac501
CW
2495 }
2496
2497 /**
2498 * Check if activity is overdue.
2499 *
2500 * @param array $activity
2501 *
2502 * @return bool
2503 */
2504 public static function isOverdue($activity) {
ce9d78e1 2505 return array_key_exists($activity['status_id'], self::getStatusesByType(self::INCOMPLETE)) && CRM_Utils_Date::overdue($activity['activity_date_time']);
760ac501
CW
2506 }
2507
6a488035 2508 /**
db7de9c1 2509 * Get the exportable fields for Activities.
6a488035 2510 *
041ab3d1
TO
2511 * @param string $name
2512 * If it is called by case $name = Case else $name = Activity.
6a488035 2513 *
a6c01b45
CW
2514 * @return array
2515 * array of exportable Fields
6a488035 2516 */
dcc79888 2517 public static function exportableFields($name = 'Activity') {
2518 self::$_exportableFields[$name] = array();
2519
2520 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2521 // my case hence we have defined fields as case_*
2522 if ($name == 'Activity') {
2523 $exportableFields = CRM_Activity_DAO_Activity::export();
2524 $exportableFields['source_contact_id'] = [
2525 'title' => ts('Source Contact ID'),
2526 'type' => CRM_Utils_Type::T_INT,
2527 ];
2528 $exportableFields['source_contact'] = array(
2529 'title' => ts('Source Contact'),
2530 'type' => CRM_Utils_Type::T_STRING,
2531 );
6a488035 2532
dcc79888 2533 $Activityfields = array(
2534 'activity_type' => array(
2535 'title' => ts('Activity Type'),
2536 'name' => 'activity_type',
2537 'type' => CRM_Utils_Type::T_STRING,
2538 'searchByLabel' => TRUE,
2539 ),
2540 'activity_status' => array(
2541 'title' => ts('Activity Status'),
2542 'name' => 'activity_status',
2543 'type' => CRM_Utils_Type::T_STRING,
2544 'searchByLabel' => TRUE,
2545 ),
2546 'activity_priority' => array(
2547 'title' => ts('Activity Priority'),
2548 'name' => 'activity_priority',
2549 'type' => CRM_Utils_Type::T_STRING,
2550 'searchByLabel' => TRUE,
2551 ),
2552 );
2553 $fields = array_merge($Activityfields, $exportableFields);
2554 }
2555 else {
2556 // Set title to activity fields.
2557 $fields = array(
2558 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type::T_STRING),
2559 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type::T_STRING),
2560 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type::T_DATE),
2561 'case_scheduled_activity_date' => array(
2562 'title' => ts('Activity Scheduled Date'),
2563 'type' => CRM_Utils_Type::T_DATE,
2564 ),
2565 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type::T_STRING),
2566 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type::T_STRING),
2567 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type::T_INT),
2568 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type::T_INT),
2569 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type::T_TEXT),
2570 'case_activity_is_auto' => array(
2571 'title' => ts('Activity Auto-generated?'),
2572 'type' => CRM_Utils_Type::T_BOOLEAN,
2573 ),
2574 );
2575 }
6a488035 2576
dcc79888 2577 // add custom data for case activities
2578 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Activity'));
6a488035 2579
dcc79888 2580 self::$_exportableFields[$name] = $fields;
6a488035
TO
2581 return self::$_exportableFields[$name];
2582 }
2583
2584 /**
63e9c3fd 2585 * Get the allowed profile fields for Activities.
6a488035 2586 *
a6c01b45
CW
2587 * @return array
2588 * array of activity profile Fields
6a488035 2589 */
00be9182 2590 public static function getProfileFields() {
6a488035 2591 $exportableFields = self::exportableFields('Activity');
4f79a2f5 2592 $skipFields = array(
2593 'activity_id',
2594 'activity_type',
2595 'source_contact_id',
2596 'source_contact',
2597 'activity_campaign',
2598 'activity_is_test',
2599 'is_current_revision',
2600 'activity_is_deleted',
2601 );
6a488035
TO
2602 $config = CRM_Core_Config::singleton();
2603 if (!in_array('CiviCampaign', $config->enableComponents)) {
2604 $skipFields[] = 'activity_engagement_level';
2605 }
2606
2607 foreach ($skipFields as $field) {
2608 if (isset($exportableFields[$field])) {
2609 unset($exportableFields[$field]);
2610 }
2611 }
2612
2613 // hack to use 'activity_type_id' instead of 'activity_type'
2614 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2615 unset($exportableFields['activity_status']);
2616
2617 return $exportableFields;
2618 }
2619
2620 /**
63e9c3fd
EM
2621 * This function deletes the activity record related to contact record.
2622 *
2623 * This is conditional on there being no target and assignee record
2624 * with other contacts.
6a488035 2625 *
041ab3d1
TO
2626 * @param int $contactId
2627 * ContactId.
6a488035
TO
2628 *
2629 * @return true/null
6a488035
TO
2630 */
2631 public static function cleanupActivity($contactId) {
2632 $result = NULL;
2633 if (!$contactId) {
2634 return $result;
2635 }
44f817d4 2636 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2bf96211 2637 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
6a488035
TO
2638
2639 $transaction = new CRM_Core_Transaction();
2640
f1504541
DL
2641 // delete activity if there is no record in civicrm_activity_contact
2642 // pointing to any other contact record
2bf96211 2643 $activityContact = new CRM_Activity_DAO_ActivityContact();
2644 $activityContact->contact_id = $contactId;
2645 $activityContact->record_type_id = $sourceID;
2646 $activityContact->find();
6a488035 2647
2bf96211 2648 while ($activityContact->fetch()) {
f1504541 2649 // delete activity_contact record for the deleted contact
32ecf7bb
BS
2650 $activityContact->delete();
2651
2652 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2653 $activityContactOther->activity_id = $activityContact->activity_id;
32ecf7bb 2654
83e0a89c 2655 // delete activity only if no other contacts connected
9d5494f7 2656 if (!$activityContactOther->find(TRUE)) {
32ecf7bb
BS
2657 $activityParams = array('id' => $activityContact->activity_id);
2658 $result = self::deleteActivity($activityParams);
2659 }
2660
2661 $activityContactOther->free();
6a488035 2662 }
6a488035 2663
2bf96211 2664 $activityContact->free();
6a488035
TO
2665 $transaction->commit();
2666
2667 return $result;
2668 }
2669
2670 /**
567b2076 2671 * Does user has sufficient permission for view/edit activity record.
6a488035 2672 *
041ab3d1
TO
2673 * @param int $activityId
2674 * Activity record id.
2675 * @param int $action
2676 * Edit/view.
6a488035 2677 *
59f4c9ee 2678 * @return bool
6a488035
TO
2679 */
2680 public static function checkPermission($activityId, $action) {
3af8de9f 2681
6a488035
TO
2682 if (!$activityId ||
2683 !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
2684 ) {
3af8de9f 2685 return FALSE;
6a488035
TO
2686 }
2687
2688 $activity = new CRM_Activity_DAO_Activity();
2689 $activity->id = $activityId;
2690 if (!$activity->find(TRUE)) {
3af8de9f 2691 return FALSE;
6a488035 2692 }
ac4b9bc3 2693
11b18d9d 2694 if (!self::hasPermissionForActivityType($activity->activity_type_id)) {
2695 return FALSE;
2696 }
ac4b9bc3 2697 // Return early when it is case activity.
2698 // Check for CiviCase related permission.
2699 if (CRM_Case_BAO_Case::isCaseActivity($activityId)) {
2700 return self::isContactPermittedAccessToCaseActivity($activityId, $action, $activity->activity_type_id);
2701 }
2702
7808aae6 2703 // Check for this permission related to contact.
6a488035
TO
2704 $permission = CRM_Core_Permission::VIEW;
2705 if ($action == CRM_Core_Action::UPDATE) {
2706 $permission = CRM_Core_Permission::EDIT;
2707 }
2708
44f817d4 2709 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
034500d4 2710 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2711 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2712 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2713
7808aae6 2714 // Check for source contact.
f3b59360 2715 $sourceContactId = self::getActivityContact($activity->id, $sourceID);
2716 // Account for possibility of activity not having a source contact (as it may have been deleted).
2717 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission) : TRUE;
2718 if (!$allow) {
2719 return FALSE;
6a488035
TO
2720 }
2721
7808aae6 2722 // Check for target and assignee contacts.
f3b59360 2723 // First check for supper permission.
2724 $supPermission = 'view all contacts';
2725 if ($action == CRM_Core_Action::UPDATE) {
2726 $supPermission = 'edit all contacts';
2727 }
2728 $allow = CRM_Core_Permission::check($supPermission);
2729
2730 // User might have sufficient permission, through acls.
2731 if (!$allow) {
2732 $allow = TRUE;
2733 // Get the target contacts.
2734 $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
2735 foreach ($targetContacts as $cnt => $contactId) {
2736 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2737 $allow = FALSE;
2738 break;
2739 }
2740 }
2741
2742 // Get the assignee contacts.
2743 if ($allow) {
2744 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
2745 foreach ($assigneeContacts as $cnt => $contactId) {
6a488035
TO
2746 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
2747 $allow = FALSE;
2748 break;
2749 }
2750 }
6a488035
TO
2751 }
2752 }
2753
2754 return $allow;
2755 }
2756
ac4b9bc3 2757 /**
2758 * Check if the logged in user has permission for the given case activity.
2759 *
2760 * @param int $activityId
2761 * @param int $action
2762 * @param int $activityTypeID
2763 *
2764 * @return bool
2765 */
2766 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
11b18d9d 2767 $oper = 'view';
2768 if ($action == CRM_Core_Action::UPDATE) {
2769 $oper = 'edit';
ac4b9bc3 2770 }
11b18d9d 2771 $allow = CRM_Case_BAO_Case::checkPermission($activityId,
2772 $oper,
2773 $activityTypeID
2774 );
ac4b9bc3 2775
2776 return $allow;
2777 }
2778
15e11313 2779 /**
a2d210b2 2780 * Check if the logged in user has permission to access the given activity type.
2781 *
15e11313 2782 * @param int $activityTypeID
a2d210b2 2783 *
15e11313 2784 * @return bool
2785 */
2786 protected static function hasPermissionForActivityType($activityTypeID) {
a2d210b2 2787 $permittedActivityTypes = self::getPermittedActivityTypes();
2788 return isset($permittedActivityTypes[$activityTypeID]);
2789 }
15e11313 2790
a2d210b2 2791 /**
2792 * Get the activity types the user is permitted to access.
2793 *
2794 * The types are filtered by the components they have access to. ie. a user
2795 * with access CiviContribute but not CiviMember will see contribution related
2796 * activities and activities with no component (e.g meetings) but not member related ones.
2797 *
2798 * @return array
2799 */
2800 public static function getPermittedActivityTypes() {
2801 $userID = (int) CRM_Core_Session::getLoggedInContactID();
2802 if (!isset(Civi::$statics[__CLASS__]['permitted_activity_types'][$userID])) {
2803 $permittedActivityTypes = [];
2804 $components = self::activityComponents(FALSE);
2805 $componentClause = empty($components) ? '' : (' OR component_id IN (' . implode(', ', array_keys($components)) . ')');
2806
2807 $types = CRM_Core_DAO::executeQuery(
2808 "
2809 SELECT option_value.value activity_type_id
2810 FROM civicrm_option_value option_value
2811INNER JOIN civicrm_option_group grp ON (grp.id = option_group_id AND grp.name = 'activity_type')
2812 WHERE component_id IS NULL $componentClause")->fetchAll();
2813 foreach ($types as $type) {
2814 $permittedActivityTypes[$type['activity_type_id']] = $type['activity_type_id'];
2815 }
2816 Civi::$statics[__CLASS__]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2817 }
2818 return Civi::$statics[__CLASS__]['permitted_activity_types'][$userID];
15e11313 2819 }
2820
84be264e 2821 /**
2822 * @param $params
2823 * @return array
2824 */
2825 protected static function getActivityParamsForDashboardFunctions($params) {
2826 $activityParams = [
2827 'is_deleted' => 0,
2828 'is_current_revision' => 1,
2829 'is_test' => 0,
2830 'contact_id' => CRM_Utils_Array::value('contact_id', $params),
2831 'check_permissions' => 1,
2832 'options' => [
2833 'offset' => CRM_Utils_Array::value('offset', $params, 0),
2834 ],
2835 ];
2836
2837 if (!empty($params['activity_status_id'])) {
2838 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2839 }
2840
2841 $activityParams['activity_type_id'] = self::filterActivityTypes($params);
2842 $enabledComponents = self::activityComponents();
2843 // @todo - should we move this to activity get api.
2844 foreach ([
2845 'case_id' => 'CiviCase',
2846 'campaign_id' => 'CiviCampaign'
2847 ] as $attr => $component) {
2848 if (!in_array($component, $enabledComponents)) {
2849 $activityParams[$attr] = ['IS NULL' => 1];
2850 }
2851 }
2852 return $activityParams;
2853 }
2854
55806731
CR
2855 /**
2856 * Checks if user has permissions to edit inbound e-mails, either bsic info
2857 * or both basic information and content.
2858 *
2859 * @return bool
2860 */
2861 public function checkEditInboundEmailsPermissions() {
2862 if (CRM_Core_Permission::check('edit inbound email basic information')
2863 || CRM_Core_Permission::check('edit inbound email basic information and content')
2864 ) {
2865 return TRUE;
2866 }
2867
2868 return FALSE;
2869 }
2870
6a488035 2871 /**
db7de9c1 2872 * Wrapper for ajax activity selector.
6a488035 2873 *
041ab3d1
TO
2874 * @param array $params
2875 * Associated array for params record id.
6a488035 2876 *
a6c01b45 2877 * @return array
db7de9c1 2878 * Associated array of contact activities
6a488035
TO
2879 */
2880 public static function getContactActivitySelector(&$params) {
7808aae6 2881 // Format the params.
9d5494f7 2882 $params['offset'] = ($params['page'] - 1) * $params['rp'];
6a488035 2883 $params['rowCount'] = $params['rp'];
9d5494f7
TO
2884 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2885 $params['caseId'] = NULL;
2886 $context = CRM_Utils_Array::value('context', $params);
e5dcfebc 2887 $showContactOverlay = !CRM_Utils_String::startsWith($context, "dashlet");
8c99c0bb
CW
2888 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2889 'option_group_id' => "activity_type",
2890 'options' => array('limit' => 0),
2891 ));
2892 $activityIcons = array();
2893 foreach ($activityTypeInfo['values'] as $type) {
2894 if (!empty($type['icon'])) {
2895 $activityIcons[$type['value']] = $type['icon'];
2896 }
2897 }
6a488035 2898
7808aae6 2899 // Get contact activities.
550e5b1a 2900 $activities = CRM_Activity_BAO_Activity::deprecatedGetActivities($params);
6a488035 2901
7808aae6 2902 // Add total.
6ab43e1b 2903 $params['total'] = CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($params);
6a488035 2904
7808aae6 2905 // Format params and add links.
6a488035
TO
2906 $contactActivities = array();
2907
2908 if (!empty($activities)) {
2909 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
2910
7808aae6 2911 // Check logged in user for permission.
6a488035
TO
2912 $page = new CRM_Core_Page();
2913 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
2914 $permissions = array($page->_permission);
2915 if (CRM_Core_Permission::check('delete activities')) {
2916 $permissions[] = CRM_Core_Permission::DELETE;
2917 }
2918
2919 $mask = CRM_Core_Action::mask($permissions);
2920
2921 foreach ($activities as $activityId => $values) {
7d12de7f 2922 $activity = array();
febb6506 2923 $activity['DT_RowId'] = $activityId;
7808aae6 2924 // Add class to this row if overdue.
b62580ac 2925 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
760ac501 2926 if (self::isOverdue($values)) {
7d12de7f
JL
2927 $activity['DT_RowClass'] .= ' status-overdue';
2928 }
2929 else {
2930 $activity['DT_RowClass'] .= ' status-ontime';
2931 }
2932
febb6506
JL
2933 $activity['DT_RowAttr'] = array();
2934 $activity['DT_RowAttr']['data-entity'] = 'activity';
2935 $activity['DT_RowAttr']['data-id'] = $activityId;
7d12de7f 2936
8c99c0bb 2937 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ? '<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
7d12de7f 2938 $activity['subject'] = $values['subject'];
ad280fb6
JL
2939
2940 $activity['source_contact_name'] = '';
6a488035 2941 if ($params['contact_id'] == $values['source_contact_id']) {
7d12de7f 2942 $activity['source_contact_name'] = $values['source_contact_name'];
6a488035
TO
2943 }
2944 elseif ($values['source_contact_id']) {
e846bd8d 2945 $srcTypeImage = "";
2946 if ($showContactOverlay) {
2947 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2948 CRM_Contact_BAO_Contact::getContactType($values['source_contact_id']),
2949 FALSE,
2950 $values['source_contact_id']);
2951 }
160db45f 2952 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System::href($values['source_contact_name'],
5a99d240 2953 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
6a488035
TO
2954 }
2955 else {
7d12de7f 2956 $activity['source_contact_name'] = '<em>n/a</em>';
6a488035
TO
2957 }
2958
ad280fb6 2959 $activity['target_contact_name'] = '';
6a488035 2960 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
7d12de7f 2961 $activity['target_contact'] = CRM_Utils_System::href($values['recipients'],
5a99d240
KJ
2962 'civicrm/mailing/report/event',
2963 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
6a488035 2964 }
a7488080 2965 elseif (!empty($values['recipients'])) {
7d12de7f 2966 $activity['target_contact_name'] = $values['recipients'];
6a488035 2967 }
9254ec4e 2968 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
7d12de7f 2969 $activity['target_contact_name'] = '';
a84a8555 2970 $firstTargetName = reset($values['target_contact_name']);
2971 $firstTargetContactID = key($values['target_contact_name']);
2972
2973 $targetLink = CRM_Utils_System::href($firstTargetName, 'civicrm/contact/view', "reset=1&cid={$firstTargetContactID}");
2974 if ($showContactOverlay) {
2975 $targetTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
2976 CRM_Contact_BAO_Contact::getContactType($firstTargetContactID),
2977 FALSE,
2978 $firstTargetContactID);
2979 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2980 }
2981 else {
2982 $activity['target_contact_name'] .= $targetLink;
9254ec4e 2983 }
6a488035 2984
9254ec4e 2985 if ($extraCount = $values['target_contact_counter'] - 1) {
ceb21ebb 2986 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2987 }
2988 if ($showContactOverlay) {
2989 $activity['target_contact_name'] .= "</div> ";
6a488035
TO
2990 }
2991 }
9254ec4e 2992 elseif (!$values['target_contact_name']) {
7d12de7f 2993 $activity['target_contact_name'] = '<em>n/a</em>';
9254ec4e 2994 }
6a488035 2995
ad280fb6 2996 $activity['assignee_contact_name'] = '';
6a488035 2997 if (empty($values['assignee_contact_name'])) {
7d12de7f 2998 $activity['assignee_contact_name'] = '<em>n/a</em>';
6a488035
TO
2999 }
3000 elseif (!empty($values['assignee_contact_name'])) {
3001 $count = 0;
7d12de7f 3002 $activity['assignee_contact_name'] = '';
6a488035
TO
3003 foreach ($values['assignee_contact_name'] as $acID => $acName) {
3004 if ($acID && $count < 5) {
e846bd8d 3005 $assigneeTypeImage = "";
ceb21ebb 3006 $assigneeLink = CRM_Utils_System::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
e846bd8d 3007 if ($showContactOverlay) {
3008 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils::getImage(
3009 CRM_Contact_BAO_Contact::getContactType($acID),
3010 FALSE,
3011 $acID);
ceb21ebb 3012 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
e846bd8d 3013 }
ceb21ebb 3014 else {
3015 $activity['assignee_contact_name'] .= $assigneeLink;
3016 }
3017
6a488035
TO
3018 $count++;
3019 if ($count) {
ceb21ebb 3020 $activity['assignee_contact_name'] .= ";&nbsp;";
3021 }
3022 if ($showContactOverlay) {
3023 $activity['assignee_contact_name'] .= "</div> ";
6a488035
TO
3024 }
3025
3026 if ($count == 4) {
7d12de7f 3027 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
6a488035
TO
3028 break;
3029 }
3030 }
3031 }
3032 }
6a488035 3033
7d12de7f
JL
3034 $activity['activity_date_time'] = CRM_Utils_Date::customFormat($values['activity_date_time']);
3035 $activity['status_id'] = $activityStatus[$values['status_id']];
6a488035
TO
3036
3037 // build links
7d12de7f 3038 $activity['links'] = '';
6a488035 3039 $accessMailingReport = FALSE;
a7488080 3040 if (!empty($values['mailingId'])) {
6a488035
TO
3041 $accessMailingReport = TRUE;
3042 }
3043
3044 $actionLinks = CRM_Activity_Selector_Activity::actionLinks(
3045 CRM_Utils_Array::value('activity_type_id', $values),
3046 CRM_Utils_Array::value('source_record_id', $values),
3047 $accessMailingReport,
3048 CRM_Utils_Array::value('activity_id', $values)
3049 );
3050
3051 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
3052
7d12de7f 3053 $activity['links'] = CRM_Core_Action::formLink($actionLinks,
6a488035
TO
3054 $actionMask,
3055 array(
3056 'id' => $values['activity_id'],
3057 'cid' => $params['contact_id'],
3058 'cxt' => $context,
3059 'caseid' => CRM_Utils_Array::value('case_id', $values),
87dab4a4
AH
3060 ),
3061 ts('more'),
3062 FALSE,
3063 'activity.tab.row',
3064 'Activity',
3065 $values['activity_id']
6a488035 3066 );
97c7504f 3067
04374d9d 3068 if ($values['is_recurring_activity']) {
053eb755 3069 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity::getPositionAndCount($values['activity_id'], 'civicrm_activity');
04374d9d 3070 }
7d12de7f
JL
3071
3072 array_push($contactActivities, $activity);
6a488035
TO
3073 }
3074 }
3075
7d12de7f
JL
3076 $activitiesDT = array();
3077 $activitiesDT['data'] = $contactActivities;
3078 $activitiesDT['recordsTotal'] = $params['total'];
3079 $activitiesDT['recordsFiltered'] = $params['total'];
3080
3081 return $activitiesDT;
6a488035
TO
3082 }
3083
ffd93213 3084 /**
63e9c3fd
EM
3085 * Copy custom fields and attachments from an existing activity to another.
3086 *
d3e86119 3087 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
c490a46a
CW
3088 *
3089 * @param array $params
ffd93213 3090 */
00be9182 3091 public static function copyExtendedActivityData($params) {
6a488035
TO
3092 // attach custom data to the new activity
3093 $customParams = $htmlType = array();
3094 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
3095
3096 if (!empty($customValues)) {
3097 $fieldIds = implode(', ', array_keys($customValues));
9d5494f7
TO
3098 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
3099 $result = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
3100
3101 while ($result->fetch()) {
3102 $htmlType[] = $result->id;
3103 }
3104
3105 foreach ($customValues as $key => $value) {
59f4c9ee
TO
3106 if ($value !== NULL) {
3107 // CRM-10542
6a488035
TO
3108 if (in_array($key, $htmlType)) {
3109 $fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
3110 $customParams["custom_{$key}_-1"] = array(
3111 'name' => $fileValues[0],
3112 'path' => $fileValues[1],
3113 );
3114 }
3115 else {
3116 $customParams["custom_{$key}_-1"] = $value;
3117 }
3118 }
3119 }
5fc3ea24 3120 CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_activity',
6a488035
TO
3121 $params['mainActivityId'], 'Activity'
3122 );
3123 }
3124
3125 // copy activity attachments ( if any )
3126 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
3127 }
65ebc887 3128
ffd93213 3129 /**
63e9c3fd
EM
3130 * Get activity contact.
3131 *
100fef9d
CW
3132 * @param int $activityId
3133 * @param int $recordTypeID
ffd93213
EM
3134 * @param string $column
3135 *
3136 * @return null
3137 */
65ebc887 3138 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
3139 $activityContact = new CRM_Activity_BAO_ActivityContact();
3140 $activityContact->activity_id = $activityId;
3141 if ($recordTypeID) {
3142 $activityContact->record_type_id = $recordTypeID;
3143 }
3144 if ($activityContact->find(TRUE)) {
b319d00a 3145 return $activityContact->$column;
65ebc887 3146 }
42d30b83
DL
3147 return NULL;
3148 }
3149
ffd93213 3150 /**
567b2076
EM
3151 * Get source contact id.
3152 *
100fef9d 3153 * @param int $activityId
ffd93213
EM
3154 *
3155 * @return null
3156 */
42d30b83
DL
3157 public static function getSourceContactID($activityId) {
3158 static $sourceID = NULL;
3159 if (!$sourceID) {
44f817d4 3160 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
42d30b83
DL
3161 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
3162 }
3163
3164 return self::getActivityContact($activityId, $sourceID);
65ebc887 3165 }
42d30b83 3166
ffd93213 3167 /**
63e9c3fd
EM
3168 * Set api filter.
3169 *
3170 * @todo Document what this is for.
3171 *
c490a46a 3172 * @param array $params
ffd93213 3173 */
00be9182 3174 public function setApiFilter(&$params) {
b53cbfbc 3175 if (!empty($params['target_contact_id'])) {
6e1bb60c 3176 $this->selectAdd();
44f817d4 3177 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
6e1bb60c
N
3178 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3179 $obj = new CRM_Activity_BAO_ActivityContact();
3180 $params['return.target_contact_id'] = 1;
3181 $this->joinAdd($obj, 'LEFT');
3182 $this->selectAdd('civicrm_activity.*');
3183 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
3184 }
3185 }
3186
2bbb4a91 3187 /**
7808aae6 3188 * Send activity as attachment.
2bbb4a91 3189 *
3190 * @param object $activity
3191 * @param array $mailToContacts
fc110b68 3192 * @param array $params
2bbb4a91 3193 *
bc883279 3194 * @return bool
2bbb4a91 3195 */
fc110b68 3196 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
3197 if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
9f661777 3198 $clientID = CRM_Utils_Array::value('client_id', $params);
fc110b68 3199 $caseID = CRM_Utils_Array::value('case_id', $params);
3200
2bbb4a91 3201 $ics = new CRM_Activity_BAO_ICalendar($activity);
3202 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
3203 $ics->addAttachment($attachments, $mailToContacts);
3204
fc110b68 3205 $result = CRM_Case_BAO_Case::sendActivityCopy($clientID, $activity->id, $mailToContacts, $attachments, $caseID);
2bbb4a91 3206 $ics->cleanup();
fc110b68 3207 return $result;
2bbb4a91 3208 }
3209 return FALSE;
3210 }
bc883279 3211
6a488035 3212}