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