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