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