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