3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * This class is for activity functions.
37 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
40 * Activity status types
48 * Static field for all the activity information that we can potentially export.
52 static $_exportableFields = NULL;
55 * Static field for all the activity information that we can potentially import.
59 static $_importableFields = NULL;
62 * Check if there is absolute minimum of data to add the object.
64 * @param array $params
65 * (reference ) an assoc array of name/value pairs.
69 public static function dataExists(&$params) {
70 if (!empty($params['source_contact_id']) ||
!empty($params['id'])) {
79 * Fetch object based on array of properties.
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
83 * @param array $defaults
84 * (reference ) an assoc array to hold the flattened values.
86 * @return CRM_Activity_DAO_Activity
88 public static function retrieve(&$params, &$defaults) {
89 // this will bypass acls - use the api instead.
90 // @todo add deprecation logging to this function.
91 $activity = new CRM_Activity_DAO_Activity();
92 $activity->copyValues($params);
94 if ($activity->find(TRUE)) {
95 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
96 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
97 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
98 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
100 // TODO: at some stage we'll have to deal
101 // with multiple values for assignees and targets, but
102 // for now, let's just fetch first row.
103 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
104 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
105 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
106 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
107 if ($activity->activity_type_id
!= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email')) {
108 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
109 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
110 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
112 elseif (CRM_Core_Permission
::check('access CiviMail') ||
113 (CRM_Mailing_Info
::workflowEnabled() &&
114 CRM_Core_Permission
::check('create mailings')
117 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
118 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
122 $defaults['target_contact_value'] = ts('(recipients)');
125 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
126 $defaults['source_contact_id'] = $sourceContactId;
128 if ($sourceContactId &&
129 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
134 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
141 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
143 CRM_Core_DAO
::storeValues($activity, $defaults);
151 * Delete the activity.
153 * @param array $params
154 * @param bool $moveToTrash
158 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
160 if (!empty($params['id']) && !is_array($params['id'])) {
161 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
164 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
167 $transaction = new CRM_Core_Transaction();
168 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
169 $sourceRecordIds = implode(',', $params['source_record_id']);
172 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
177 if (!isset($params['id'])) {
178 if (is_array($params['activity_type_id'])) {
179 $activityTypes = implode(',', $params['activity_type_id']);
182 $activityTypes = $params['activity_type_id'];
185 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
186 $dao = CRM_Core_DAO
::executeQuery($query);
189 $activity = new CRM_Activity_DAO_Activity();
190 $activity->copyValues($params);
191 $result = $activity->delete();
194 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
196 // CRM-13994 delete activity entity_tag
197 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
198 $dao = CRM_Core_DAO
::executeQuery($query);
202 $activity = new CRM_Activity_DAO_Activity();
203 $activity->copyValues($params);
205 $activity->is_deleted
= 1;
206 $result = $activity->save();
208 // CRM-4525 log activity delete
209 $logMsg = 'Case Activity deleted for';
212 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
213 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
214 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
215 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
216 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
217 if ($sourceContactId) {
218 $msgs[] = " source={$sourceContactId}";
221 // get target contacts.
222 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
223 if (!empty($targetContactIds)) {
224 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
226 // get assignee contacts.
227 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
228 if (!empty($assigneeContactIds)) {
229 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
232 $logMsg .= implode(', ', $msgs);
234 self
::logActivityAction($activity, $logMsg);
237 // delete the recently created Activity
239 $activityRecent = array(
240 'id' => $activity->id
,
241 'type' => 'Activity',
243 CRM_Utils_Recent
::del($activityRecent);
246 $transaction->commit();
247 if (isset($activity)) {
249 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
250 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
257 * Delete activity assignment record.
259 * @param int $activityId
260 * @param int $recordTypeID
262 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
263 $activityContact = new CRM_Activity_BAO_ActivityContact();
264 $activityContact->activity_id
= $activityId;
266 $activityContact->record_type_id
= $recordTypeID;
269 // Let's check if activity contact record exits and then delete.
270 // Looks like delete leads to deadlock when multiple simultaneous
271 // requests are done. CRM-15470
272 if ($activityContact->find()) {
273 $activityContact->delete();
278 * Process the activities.
280 * @param array $params
281 * Associated array of the submitted values.
283 * @throws CRM_Core_Exception
285 * @return CRM_Activity_BAO_Activity|null|object
287 public static function create(&$params) {
288 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
289 unset($params['created_date']);
290 unset($params['modified_date']);
292 // check required params
293 if (!self
::dataExists($params)) {
294 throw new CRM_Core_Exception('Not enough data to create activity object');
297 $activity = new CRM_Activity_DAO_Activity();
299 if (isset($params['id']) && empty($params['id'])) {
300 unset($params['id']);
303 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
304 if (isset($params['activity_date_time']) &&
305 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
307 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed');
310 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
314 // Set priority to Normal for Auto-populated activities (for Cases)
315 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
316 // if not set and not 0
317 !CRM_Utils_Array
::value('id', $params)
319 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
320 $params['priority_id'] = array_search('Normal', $priority);
323 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
324 $params['target_contact_id'] = array_unique($params['target_contact_id']);
326 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
327 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
331 if (!empty($params['id'])) {
332 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
335 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
338 $activity->copyValues($params);
339 if (isset($params['case_id'])) {
340 // CRM-8708, preserve case ID even though it's not part of the SQL model
341 $activity->case_id
= $params['case_id'];
343 elseif (is_numeric($activity->id
)) {
344 // CRM-8708, preserve case ID even though it's not part of the SQL model
345 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
349 $transaction = new CRM_Core_Transaction();
351 $result = $activity->save();
353 if (is_a($result, 'CRM_Core_Error')) {
354 $transaction->rollback();
358 $activityId = $activity->id
;
359 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
360 $assigneeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Assignees');
361 $targetID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
363 if (isset($params['source_contact_id'])) {
365 'activity_id' => $activityId,
366 'contact_id' => $params['source_contact_id'],
367 'record_type_id' => $sourceID,
369 self
::deleteActivityContact($activityId, $sourceID);
370 CRM_Activity_BAO_ActivityContact
::create($acParams);
373 // check and attach and files as needed
374 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
376 // attempt to save activity assignment
377 $resultAssignment = NULL;
378 if (!empty($params['assignee_contact_id'])) {
380 $assignmentParams = array('activity_id' => $activityId);
382 if (is_array($params['assignee_contact_id'])) {
383 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
384 // first delete existing assignments if any
385 self
::deleteActivityContact($activityId, $assigneeID);
388 foreach ($params['assignee_contact_id'] as $acID) {
390 $assigneeParams = array(
391 'activity_id' => $activityId,
392 'contact_id' => $acID,
393 'record_type_id' => $assigneeID,
395 CRM_Activity_BAO_ActivityContact
::create($assigneeParams);
400 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
401 $assignmentParams['record_type_id'] = $assigneeID;
402 if (!empty($params['id'])) {
403 $assignment = new CRM_Activity_BAO_ActivityContact();
404 $assignment->activity_id
= $activityId;
405 $assignment->record_type_id
= $assigneeID;
406 $assignment->find(TRUE);
408 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
409 $assignmentParams['id'] = $assignment->id
;
410 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
414 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
419 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
420 self
::deleteActivityContact($activityId, $assigneeID);
424 if (is_a($resultAssignment, 'CRM_Core_Error')) {
425 $transaction->rollback();
426 return $resultAssignment;
429 // attempt to save activity targets
430 $resultTarget = NULL;
431 if (!empty($params['target_contact_id'])) {
433 $targetParams = array('activity_id' => $activityId);
434 $resultTarget = array();
435 if (is_array($params['target_contact_id'])) {
436 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
437 // first delete existing targets if any
438 self
::deleteActivityContact($activityId, $targetID);
441 foreach ($params['target_contact_id'] as $tid) {
443 $targetContactParams = array(
444 'activity_id' => $activityId,
445 'contact_id' => $tid,
446 'record_type_id' => $targetID,
448 CRM_Activity_BAO_ActivityContact
::create($targetContactParams);
453 $targetParams['contact_id'] = $params['target_contact_id'];
454 $targetParams['record_type_id'] = $targetID;
455 if (!empty($params['id'])) {
456 $target = new CRM_Activity_BAO_ActivityContact();
457 $target->activity_id
= $activityId;
458 $target->record_type_id
= $targetID;
461 if ($target->contact_id
!= $params['target_contact_id']) {
462 $targetParams['id'] = $target->id
;
463 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
467 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
472 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
473 self
::deleteActivityContact($activityId, $targetID);
477 // write to changelog before transaction is committed/rolled
478 // back (and prepare status to display)
479 if (!empty($params['id'])) {
480 $logMsg = "Activity (id: {$result->id} ) updated with ";
483 $logMsg = "Activity created for ";
487 if (isset($params['source_contact_id'])) {
488 $msgs[] = "source={$params['source_contact_id']}";
491 if (!empty($params['target_contact_id'])) {
492 if (is_array($params['target_contact_id']) && !CRM_Utils_Array
::crmIsEmptyArray($params['target_contact_id'])) {
493 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
494 // take only first target
495 // will be used for recently viewed display
496 $t = array_slice($params['target_contact_id'], 0, 1);
497 $recentContactId = $t[0];
499 // Is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
500 // as it may always be an array
501 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
502 $msgs[] = "target={$params['target_contact_id']}";
503 // will be used for recently viewed display
504 $recentContactId = $params['target_contact_id'];
508 // at worst, take source for recently viewed display
509 $recentContactId = CRM_Utils_Array
::value('source_contact_id', $params);
512 if (isset($params['assignee_contact_id'])) {
513 if (is_array($params['assignee_contact_id'])) {
514 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
517 $msgs[] = "assignee={$params['assignee_contact_id']}";
520 $logMsg .= implode(', ', $msgs);
522 self
::logActivityAction($result, $logMsg);
524 if (!empty($params['custom']) &&
525 is_array($params['custom'])
527 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
530 $transaction->commit();
531 if (empty($params['skipRecentView'])) {
532 $recentOther = array();
533 if (!empty($params['case_id'])) {
534 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
535 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
536 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
540 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home";
541 if ($activity->activity_type_id
!= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email')) {
542 $url = CRM_Utils_System
::url('civicrm/activity', $q);
543 if ($activity->activity_type_id
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Print PDF Letter')) {
544 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
545 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
549 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
550 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
554 if (CRM_Core_Permission
::check("delete activities")) {
555 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
556 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
561 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
562 if (CRM_Core_Permission
::check('delete activities')) {
563 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
564 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
570 if (!isset($activity->parent_id
)) {
571 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
572 // add the recently created Activity
573 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
574 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
577 if (isset($activitySubject)) {
578 $title = $activitySubject . ' - ';
581 $title = $title . $recentContactDisplay;
582 if (!empty($activityTypes[$activity->activity_type_id
])) {
583 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
586 CRM_Utils_Recent
::add($title,
591 $recentContactDisplay,
597 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
599 if (!empty($params['id'])) {
600 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
603 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
606 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
608 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
609 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
611 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
613 'activity_id' => $activity->id
,
614 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
616 if ($caseParams['case_id']) {
617 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
620 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
628 * Create an activity.
630 * @todo elaborate on what this does.
632 * @param CRM_Core_DAO_Activity $activity
633 * @param string $logMessage
637 public static function logActivityAction($activity, $logMessage = NULL) {
638 $id = CRM_Core_Session
::getLoggedInContactID();
640 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
641 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
642 $id = self
::getActivityContact($activity->id
, $sourceID);
645 'entity_table' => 'civicrm_activity',
646 'entity_id' => $activity->id
,
647 'modified_id' => $id,
648 'modified_date' => date('YmdHis'),
649 'data' => $logMessage,
651 CRM_Core_BAO_Log
::add($logParams);
656 * Get the list Activities.
658 * @param array $params
659 * Array of parameters.
661 * - contact_id int contact_id whose activities we want to retrieve
662 * - offset int which row to start from ?
663 * - rowCount int how many rows to fetch
664 * - sort object|array object or array describing sort order for sql query.
665 * - admin boolean if contact is admin
666 * - caseId int case ID
667 * - context string page on which selector is build
668 * - activity_type_id int|string the activitiy types we want to restrict by
669 * @param bool $getCount
670 * Get count of the activities
673 * Relevant data object values of open activities
675 public static function getActivities($params, $getCount = FALSE) {
676 $activities = array();
678 // fetch all active activity types
679 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
681 // Activity.Get API params
682 $activityParams = array(
684 'is_current_revision' => 1,
686 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
688 'activity_date_time',
691 'source_contact_name',
692 'assignee_contact_id',
694 'target_contact_name',
695 'assignee_contact_name',
703 'check_permissions' => 1,
705 'offset' => CRM_Utils_Array
::value('offset', $params, 0),
709 // activity type ID clause
710 if (!empty($params['activity_type_id'])) {
711 if (is_array($params['activity_type_id'])) {
712 foreach ($params['activity_type_id'] as $idx => $value) {
713 $params['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
715 $activityParams['activity_type_id'] = array('IN' => $params['activity_type_id']);
718 $activityParams['activity_type_id'] = CRM_Utils_Type
::escape($params['activity_type_id'], 'Positive');
721 elseif (!empty($activityTypes) && count($activityTypes)) {
722 $activityParams['activity_type_id'] = array('IN' => array_keys($activityTypes));
725 if (!empty($params['activity_status_id'])) {
726 $activityParams['activity_status_id'] = array('IN' => explode(',', $params['activity_status_id']));
729 $excludeActivityIDs = array();
730 if (!empty($params['activity_type_exclude_id'])) {
731 if (is_array($params['activity_type_exclude_id'])) {
732 foreach ($params['activity_type_exclude_id'] as $idx => $value) {
733 $excludeActivityIDs[$idx] = CRM_Utils_Type
::escape($value, 'Positive');
737 $excludeActivityIDs[] = CRM_Utils_Type
::escape($params['activity_type_exclude_id'], 'Positive');
741 if (!empty($params['rowCount']) &&
742 $params['rowCount'] > 0
744 $activityParams['options']['limit'] = $params['rowCount'];
746 // set limit = 0 if we need to fetch the activity count
748 $activityParams['options']['limit'] = 0;
751 if (!empty($params['sort'])) {
752 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
753 $order = $params['sort']->orderBy();
755 elseif (trim($params['sort'])) {
756 $order = CRM_Utils_Type
::escape($params['sort'], 'String');
760 $activityParams['options']['sort'] = empty($order) ?
"activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
763 // 1. we should use Activity.Getcount for fetching count only, but in order to check that
764 // current logged in user has permission to view Case activities we are performing filtering out those activities from list (see below).
765 // This logic need to be incorporated in Activity.get definition
766 $result = civicrm_api3('Activity', 'Get', $activityParams);
768 $enabledComponents = self
::activityComponents();
769 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
770 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey(__CLASS__
, 'activity_type_id', 'Bulk Email');
772 // CRM-3553, need to check user has access to target groups.
773 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
774 $accessCiviMail = ((CRM_Core_Permission
::check('access CiviMail')) ||
775 (CRM_Mailing_Info
::workflowEnabled() && CRM_Core_Permission
::check('create mailings'))
778 $mappingParams = array(
779 'id' => 'activity_id',
780 'source_record_id' => 'source_record_id',
781 'activity_type_id' => 'activity_type_id',
782 'activity_date_time' => 'activity_date_time',
783 'status_id' => 'status_id',
784 'subject' => 'subject',
785 'campaign_id' => 'campaign_id',
786 'assignee_contact_name' => 'assignee_contact_name',
787 'target_contact_name' => 'target_contact_name',
788 'source_contact_id' => 'source_contact_id',
789 'source_contact_name' => 'source_contact_name',
790 'case_id' => 'case_id',
793 foreach ($result['values'] as $id => $activity) {
794 // skip case activities if CiviCase is not enabled OR those actvities which are
795 if ((!empty($activity['case_id']) && !in_array('CiviCase', $enabledComponents)) ||
796 (count($excludeActivityIDs) && in_array($activity['activity_type_id'], $excludeActivityIDs))
801 $activities[$id] = array();
803 // if count is needed, no need to populate the array list with attributes
808 $isBulkActivity = (!$bulkActivityTypeID ||
($bulkActivityTypeID != $activity['activity_type_id']));
809 foreach ($mappingParams as $apiKey => $expectedName) {
810 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
811 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity, array());
812 if ($apiKey == 'target_contact_name' && count($activity['target_contact_name'])) {
813 $activities[$id]['target_contact_counter'] = count($activity['target_contact_name']);
816 if ($isBulkActivity) {
817 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
818 $activities[$id]['mailingId'] = FALSE;
819 if ($accessCiviMail &&
820 ($mailingIDs === TRUE ||
in_array($activity['source_record_id'], $mailingIDs))
822 $activities[$id]['mailingId'] = TRUE;
826 // case related fields
827 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
828 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
830 // fetch case subject for case ID found
831 if (!empty($activity['case_id'])) {
832 $activities[$id]['case_subject'] = CRM_Core_DAO
::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
836 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
837 if ($apiKey == 'activity_type_id') {
838 $activities[$id]['activity_type'] = CRM_Utils_Array
::value($activities[$id][$expectedName], $activityTypes);
840 elseif ($apiKey == 'campaign_id') {
841 $activities[$id]['campaign'] = CRM_Utils_Array
::value($activities[$id][$expectedName], $allCampaigns);
845 // if deleted, wrap in <del>
846 if (!empty($activity['source_contact_id']) &&
847 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
849 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
851 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getParentFor($id, 'civicrm_activity');
854 return $getCount ?
count($activities) : $activities;
858 * Get the list Activities.
862 * @todo - use the api for this - this is working but have temporarily backed out
863 * due to performance issue to be resolved - CRM-20481.
865 * @param array $input
866 * Array of parameters.
868 * - contact_id int contact_id whose activities we want to retrieve
869 * - offset int which row to start from ?
870 * - rowCount int how many rows to fetch
871 * - sort object|array object or array describing sort order for sql query.
872 * - admin boolean if contact is admin
873 * - caseId int case ID
874 * - context string page on which selector is build
875 * - activity_type_id int|string the activitiy types we want to restrict by
878 * Relevant data object values of open activities
880 public static function deprecatedGetActivities($input) {
881 // Step 1: Get the basic activity data.
882 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
887 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
888 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
889 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
890 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
892 $config = CRM_Core_Config
::singleton();
894 $randomNum = md5(uniqid());
895 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
897 $tableFields = array(
898 'activity_id' => 'int unsigned',
899 'activity_date_time' => 'datetime',
900 'source_record_id' => 'int unsigned',
901 'status_id' => 'int unsigned',
902 'subject' => 'varchar(255)',
903 'source_contact_name' => 'varchar(255)',
904 'activity_type_id' => 'int unsigned',
905 'activity_type' => 'varchar(128)',
906 'case_id' => 'int unsigned',
907 'case_subject' => 'varchar(255)',
908 'campaign_id' => 'int unsigned',
911 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
912 $insertValueSQL = array();
913 // The activityTempTable contains the sorted rows
914 // so in order to maintain the sort order as-is we add an auto_increment
915 // field; we can sort by this later to ensure the sort order stays correct.
916 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
917 foreach ($tableFields as $name => $desc) {
918 $sql .= "$name $desc,\n";
919 $insertValueSQL[] = $name;
922 // add unique key on activity_id just to be sure
923 // this cannot be primary key because we need that for the auto_increment
924 // fixed_sort_order field
926 UNIQUE KEY ( activity_id )
927 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
930 CRM_Core_DAO
::executeQuery($sql);
932 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
934 $order = $limit = $groupBy = '';
935 $groupBy = " GROUP BY tbl.activity_id, tbl.activity_type, tbl.case_id, tbl.case_subject ";
937 if (!empty($input['sort'])) {
938 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
939 $orderBy = $input['sort']->orderBy();
940 if (!empty($orderBy)) {
941 $order = " ORDER BY $orderBy";
944 elseif (trim($input['sort'])) {
945 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
946 $order = " ORDER BY $sort ";
951 // context = 'activity' in Activities tab.
952 $order = " ORDER BY tbl.activity_date_time desc ";
955 if (!empty($input['rowCount']) &&
956 $input['rowCount'] > 0
958 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
961 $input['count'] = FALSE;
962 list($sqlClause, $params) = self
::deprecatedGetActivitySQLClause($input);
964 $query = "{$insertSQL}
965 SELECT DISTINCT tbl.* from ( {$sqlClause} )
968 // Filter case activities - CRM-5761.
969 $components = self
::activityComponents();
970 if (!in_array('CiviCase', $components)) {
972 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
973 WHERE civicrm_case_activity.id IS NULL";
976 $query = $query . $groupBy . $order . $limit;
978 $dao = CRM_Core_DAO
::executeQuery($query, $params);
980 // step 2: Get target and assignee contacts for above activities
981 // create temp table for target contacts
982 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
983 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
984 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
985 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
986 ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
988 CRM_Core_DAO
::executeQuery($query);
990 // note that we ignore bulk email for targets, since we don't show it in selector
992 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
993 SELECT ac.activity_id,
998 FROM {$activityTempTable}
999 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1000 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1001 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1002 WHERE ac.record_type_id != %1
1004 $params = array(1 => array($targetID, 'Integer'));
1005 CRM_Core_DAO
::executeQuery($query, $params);
1007 $activityFields = array("ac.activity_id", "ac.contact_id", "ac.record_type_id", "c.sort_name", "c.is_deleted");
1008 $select = CRM_Contact_BAO_Query
::appendAnyValueToSelect($activityFields, "ac.activity_id");
1010 // for each activity insert one target contact
1011 // if we load all target contacts the performance will suffer a lot for mass-activities.
1013 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
1014 {$select}, count(ac.contact_id)
1015 FROM {$activityTempTable}
1016 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1017 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1018 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1019 WHERE ac.record_type_id = %1
1020 GROUP BY ac.activity_id
1023 CRM_Core_DAO
::executeQuery($query, $params);
1025 // step 3: Combine all temp tables to get final query for activity selector
1026 // sort by the original sort order, stored in fixed_sort_order
1028 SELECT {$activityTempTable}.*,
1029 {$activityContactTempTable}.contact_id,
1030 {$activityContactTempTable}.record_type_id,
1031 {$activityContactTempTable}.contact_name,
1032 {$activityContactTempTable}.is_deleted,
1033 {$activityContactTempTable}.counter,
1034 re.parent_id as is_recurring_activity
1035 FROM {$activityTempTable}
1036 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
1037 LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
1038 ORDER BY fixed_sort_order
1041 $dao = CRM_Core_DAO
::executeQuery($query);
1043 // CRM-3553, need to check user has access to target groups.
1044 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
1046 (CRM_Core_Permission
::check('access CiviMail')) ||
1047 (CRM_Mailing_Info
::workflowEnabled() &&
1048 CRM_Core_Permission
::check('create mailings'))
1051 // Get all campaigns.
1052 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
1054 while ($dao->fetch()) {
1055 $activityID = $dao->activity_id
;
1056 $values[$activityID]['activity_id'] = $dao->activity_id
;
1057 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
1058 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
1059 $values[$activityID]['activity_type'] = $dao->activity_type
;
1060 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
1061 $values[$activityID]['status_id'] = $dao->status_id
;
1062 $values[$activityID]['subject'] = $dao->subject
;
1063 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
1064 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity
;
1066 if ($dao->campaign_id
) {
1067 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
1070 if (empty($values[$activityID]['assignee_contact_name'])) {
1071 $values[$activityID]['assignee_contact_name'] = array();
1074 if (empty($values[$activityID]['target_contact_name'])) {
1075 $values[$activityID]['target_contact_name'] = array();
1076 $values[$activityID]['target_contact_counter'] = $dao->counter
;
1079 // if deleted, wrap in <del>
1080 if ($dao->is_deleted
) {
1081 $dao->contact_name
= "<del>{$dao->contact_name}</del>";
1084 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
1085 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
1086 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
1089 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
1090 // build array of target / assignee names
1091 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
1092 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
1094 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
1095 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
1098 // case related fields
1099 $values[$activityID]['case_id'] = $dao->case_id
;
1100 $values[$activityID]['case_subject'] = $dao->case_subject
;
1103 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter
));
1104 $values[$activityID]['mailingId'] = FALSE;
1107 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
1109 $values[$activityID]['mailingId'] = TRUE;
1118 * Get the component id and name if those are enabled and allowed.
1120 * Checks whether logged in user has permission.
1121 * To decide whether we are going to include
1122 * component related activities with core activity retrieve process.
1123 * (what did that just mean?)
1126 * Array of component id and name.
1128 public static function activityComponents() {
1129 $components = array();
1130 $compInfo = CRM_Core_Component
::getEnabledComponents();
1131 foreach ($compInfo as $compObj) {
1132 if (!empty($compObj->info
['showActivitiesInCore'])) {
1133 if ($compObj->info
['name'] == 'CiviCampaign') {
1134 $componentPermission = "administer {$compObj->name}";
1137 $componentPermission = "access {$compObj->name}";
1139 if ($compObj->info
['name'] == 'CiviCase') {
1140 if (CRM_Case_BAO_Case
::accessCiviCase()) {
1141 $components[$compObj->componentID
] = $compObj->info
['name'];
1144 elseif (CRM_Core_Permission
::check($componentPermission)) {
1145 $components[$compObj->componentID
] = $compObj->info
['name'];
1154 * Get the activity Count.
1156 * @param array $input
1157 * Array of parameters.
1159 * - contact_id int contact_id whose activities we want to retrieve
1160 * - admin boolean if contact is admin
1161 * - caseId int case ID
1162 * - context string page on which selector is build
1163 * - activity_type_id int|string the activity types we want to restrict by
1166 * count of activities
1168 public static function getActivitiesCount($input) {
1169 return self
::getActivities($input, TRUE);
1173 * Get the activity Count.
1175 * @param array $input
1176 * Array of parameters.
1178 * - contact_id int contact_id whose activities we want to retrieve
1179 * - admin boolean if contact is admin
1180 * - caseId int case ID
1181 * - context string page on which selector is build
1182 * - activity_type_id int|string the activity types we want to restrict by
1185 * count of activities
1187 public static function deprecatedGetActivitiesCount($input) {
1188 $input['count'] = TRUE;
1189 list($sqlClause, $params) = self
::deprecatedGetActivitySQLClause($input);
1191 //filter case activities - CRM-5761
1192 $components = self
::activityComponents();
1193 if (!in_array('CiviCase', $components)) {
1195 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
1196 FROM ( {$sqlClause} ) as tbl
1197 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
1198 WHERE civicrm_case_activity.id IS NULL";
1201 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
1204 return CRM_Core_DAO
::singleValueQuery($query, $params);
1208 * Get the activity sql clause to pick activities.
1210 * @param array $input
1211 * Array of parameters.
1213 * - contact_id int contact_id whose activities we want to retrieve
1214 * - admin boolean if contact is admin
1215 * - caseId int case ID
1216 * - context string page on which selector is build
1217 * - count boolean are we interested in the count clause only?
1218 * - activity_type_id int|string the activity types we want to restrict by
1221 * count of activities
1223 public static function deprecatedGetActivitySQLClause($input) {
1225 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1227 $config = CRM_Core_Config
::singleton();
1228 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
1229 $sourceWhere = ' ac.contact_id = %1 ';
1230 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1232 $params = array(1 => array($input['contact_id'], 'Integer'));
1235 $commonClauses = array(
1236 "civicrm_option_group.name = 'activity_type'",
1237 "civicrm_activity.is_deleted = 0",
1238 "civicrm_activity.is_current_revision = 1",
1239 "civicrm_activity.is_test= 0",
1242 if (isset($input['activity_date_relative']) ||
1243 (!empty($input['activity_date_low']) ||
!empty($input['activity_date_high']))
1245 list($from, $to) = CRM_Utils_Date
::getFromTo(
1246 CRM_Utils_Array
::value('activity_date_relative', $input, 0),
1247 CRM_Utils_Array
::value('activity_date_low', $input),
1248 CRM_Utils_Array
::value('activity_date_high', $input)
1250 $commonClauses[] = sprintf('civicrm_activity.activity_date_time BETWEEN "%s" AND "%s" ', $from, $to);
1253 if (!empty($input['activity_status_id'])) {
1254 $commonClauses[] = sprintf("civicrm_activity.status_id IN (%s)", $input['activity_status_id']);
1257 // Filter on component IDs.
1258 $components = self
::activityComponents();
1259 if (!empty($components)) {
1260 $componentsIn = implode(',', array_keys($components));
1261 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1264 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1267 // activity type ID clause
1268 if (!empty($input['activity_type_id'])) {
1269 if (is_array($input['activity_type_id'])) {
1270 foreach ($input['activity_type_id'] as $idx => $value) {
1271 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1273 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1276 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1277 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1281 // exclude by activity type clause
1282 if (!empty($input['activity_type_exclude_id'])) {
1283 if (is_array($input['activity_type_exclude_id'])) {
1284 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1285 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1287 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1290 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1291 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1295 $commonClause = implode(' AND ', $commonClauses);
1297 $includeCaseActivities = FALSE;
1298 if (in_array('CiviCase', $components)) {
1299 $includeCaseActivities = TRUE;
1302 // build main activity table select clause
1305 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1306 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1308 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1309 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1312 if (!$input['count']) {
1314 civicrm_activity.activity_date_time,
1315 civicrm_activity.source_record_id,
1316 civicrm_activity.status_id,
1317 civicrm_activity.subject,
1318 contact.sort_name as source_contact_name,
1319 civicrm_option_value.value as activity_type_id,
1320 civicrm_option_value.label as activity_type,
1321 null as case_id, null as case_subject,
1322 civicrm_activity.campaign_id as campaign_id
1326 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)
1331 SELECT civicrm_activity.id as activity_id
1333 from civicrm_activity
1334 left join civicrm_option_value on
1335 civicrm_activity.activity_type_id = civicrm_option_value.value
1336 left join civicrm_option_group on
1337 civicrm_option_group.id = civicrm_option_value.option_group_id
1344 // Build case clause
1345 // or else exclude Inbound Emails that have been filed on a case.
1348 if ($includeCaseActivities) {
1350 if (!$input['count']) {
1352 civicrm_activity.activity_date_time,
1353 civicrm_activity.source_record_id,
1354 civicrm_activity.status_id,
1355 civicrm_activity.subject,
1356 contact.sort_name as source_contact_name,
1357 civicrm_option_value.value as activity_type_id,
1358 civicrm_option_value.label as activity_type,
1359 null as case_id, null as case_subject,
1360 civicrm_activity.campaign_id as campaign_id';
1366 SELECT civicrm_activity.id as activity_id
1368 from civicrm_activity
1369 inner join civicrm_case_activity on
1370 civicrm_case_activity.activity_id = civicrm_activity.id
1371 inner join civicrm_case on
1372 civicrm_case_activity.case_id = civicrm_case.id
1373 inner join civicrm_case_contact on
1374 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1375 left join civicrm_option_value on
1376 civicrm_activity.activity_type_id = civicrm_option_value.value
1377 left join civicrm_option_group on
1378 civicrm_option_group.id = civicrm_option_value.option_group_id
1383 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1384 ( civicrm_option_value.name <> 'Inbound Email' AND
1385 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1391 $returnClause = " {$sourceClause} {$caseClause} ";
1393 return array($returnClause, $params);
1397 * Send the message to all the contacts.
1399 * Also insert a contact activity in each contacts record.
1401 * @param array $contactDetails
1402 * The array of contact details to send the email.
1403 * @param string $subject
1404 * The subject of the message.
1407 * @param string $emailAddress
1408 * Use this 'to' email address instead of the default Primary address.
1409 * @param int $userID
1410 * Use this userID if set.
1411 * @param string $from
1412 * @param array $attachments
1413 * The array of attachments if any.
1416 * @param string $bcc
1418 * @param array $contactIds
1420 * @param string $additionalDetails
1421 * The additional information of CC and BCC appended to the activity Details.
1422 * @param array $contributionIds
1423 * @param int $campaignId
1426 * ( sent, activityId) if any email is sent and activityId
1428 public static function sendEmail(
1436 $attachments = NULL,
1440 $additionalDetails = NULL,
1441 $contributionIds = NULL,
1444 // get the contact details of logged in contact, which we set as from email
1445 if ($userID == NULL) {
1446 $userID = CRM_Core_Session
::getLoggedInContactID();
1449 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1451 return array(count($contactDetails), 0, count($contactDetails));
1453 if (!trim($fromDisplayName)) {
1454 $fromDisplayName = $fromEmail;
1458 // token replacement of addressee/email/postal greetings
1459 // get the tokens added in subject and message
1460 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1461 $messageToken = CRM_Utils_Token
::getTokens($text);
1462 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1463 $allTokens = array_merge($messageToken, $subjectToken);
1466 $from = "$fromDisplayName <$fromEmail>";
1469 //create the meta level record first ( email activity )
1470 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id',
1474 // CRM-6265: save both text and HTML parts in details (if present)
1475 if ($html and $text) {
1476 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1479 $details = $html ?
$html : $text;
1480 $details .= $additionalDetails;
1483 $activityParams = array(
1484 'source_contact_id' => $userID,
1485 'activity_type_id' => $activityTypeID,
1486 'activity_date_time' => date('YmdHis'),
1487 'subject' => $subject,
1488 'details' => $details,
1489 // FIXME: check for name Completed and get ID from that lookup
1491 'campaign_id' => $campaignId,
1494 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1495 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1497 // add the attachments to activity params here
1499 // first process them
1500 $activityParams = array_merge($activityParams,
1505 $activity = self
::create($activityParams);
1507 // get the set of attachments from where they are stored
1508 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1511 $returnProperties = array();
1512 if (isset($messageToken['contact'])) {
1513 foreach ($messageToken['contact'] as $key => $value) {
1514 $returnProperties[$value] = 1;
1518 if (isset($subjectToken['contact'])) {
1519 foreach ($subjectToken['contact'] as $key => $value) {
1520 if (!isset($returnProperties[$value])) {
1521 $returnProperties[$value] = 1;
1526 // get token details for contacts, call only if tokens are used
1528 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1529 list($details) = CRM_Utils_Token
::getTokenDetails(
1534 'CRM_Activity_BAO_Activity'
1540 CRM_Utils_Hook
::tokens($tokens);
1541 $categories = array_keys($tokens);
1543 $escapeSmarty = FALSE;
1544 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1545 $smarty = CRM_Core_Smarty
::singleton();
1546 $escapeSmarty = TRUE;
1549 $contributionDetails = array();
1550 if (!empty($contributionIds)) {
1551 $contributionDetails = CRM_Contribute_BAO_Contribution
::replaceContributionTokens(
1562 $sent = $notSent = array();
1563 foreach ($contactDetails as $values) {
1564 $contactId = $values['contact_id'];
1565 $emailAddress = $values['email'];
1567 if (!empty($contributionDetails)) {
1568 $subject = $contributionDetails[$contactId]['subject'];
1569 $text = $contributionDetails[$contactId]['text'];
1570 $html = $contributionDetails[$contactId]['html'];
1573 if (!empty($details) && is_array($details["{$contactId}"])) {
1574 // unset email from details since it always returns primary email address
1575 unset($details["{$contactId}"]['email']);
1576 unset($details["{$contactId}"]['email_id']);
1577 $values = array_merge($values, $details["{$contactId}"]);
1580 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1581 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1584 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1585 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1586 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1592 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1593 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1594 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1600 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1601 // also add the contact tokens to the template
1602 $smarty->assign_by_ref('contact', $values);
1604 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1605 $tokenText = $smarty->fetch("string:$tokenText");
1606 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1610 if (self
::sendMessage(
1628 return array($sent, $activity->id
);
1634 * @param array $contactDetails
1635 * @param array $activityParams
1636 * @param array $smsParams
1637 * @param $contactIds
1638 * @param int $userID
1641 * @throws CRM_Core_Exception
1643 public static function sendSMS(
1646 &$smsParams = array(),
1650 if ($userID == NULL) {
1651 $userID = CRM_Core_Session
::getLoggedInContactID();
1654 $text = &$activityParams['sms_text_message'];
1657 // token replacement of addressee/email/postal greetings
1658 // get the tokens added in subject and message
1659 $messageToken = CRM_Utils_Token
::getTokens($text);
1661 // Create the meta level record first ( sms activity )
1662 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
1669 $activitySubject = $activityParams['activity_subject'];
1670 $activityParams = array(
1671 'source_contact_id' => $userID,
1672 'activity_type_id' => $activityTypeID,
1673 'activity_date_time' => date('YmdHis'),
1674 'subject' => $activitySubject,
1675 'details' => $details,
1676 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1679 $activity = self
::create($activityParams);
1680 $activityID = $activity->id
;
1682 $returnProperties = array();
1684 if (isset($messageToken['contact'])) {
1685 foreach ($messageToken['contact'] as $key => $value) {
1686 $returnProperties[$value] = 1;
1692 CRM_Utils_Hook
::tokens($tokens);
1693 $categories = array_keys($tokens);
1695 // get token details for contacts, call only if tokens are used
1697 if (!empty($returnProperties) ||
!empty($tokens)) {
1698 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1702 'CRM_Activity_BAO_Activity'
1707 $escapeSmarty = FALSE;
1709 foreach ($contactDetails as $values) {
1710 $contactId = $values['contact_id'];
1712 if (!empty($details) && is_array($details["{$contactId}"])) {
1713 // unset phone from details since it always returns primary number
1714 unset($details["{$contactId}"]['phone']);
1715 unset($details["{$contactId}"]['phone_type_id']);
1716 $values = array_merge($values, $details["{$contactId}"]);
1719 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1720 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1722 // Only send if the phone is of type mobile
1723 if ($values['phone_type_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1724 $smsParams['To'] = $values['phone'];
1727 $smsParams['To'] = '';
1730 $sendResult = self
::sendSMSMessage(
1738 if (PEAR
::isError($sendResult)) {
1739 // Collect all of the PEAR_Error objects
1740 $errMsgs[] = $sendResult;
1747 // If at least one message was sent and no errors
1748 // were generated then return a boolean value of TRUE.
1749 // Otherwise, return FALSE (no messages sent) or
1750 // and array of 1 or more PEAR_Error objects.
1752 if ($success > 0 && count($errMsgs) == 0) {
1755 elseif (count($errMsgs) > 0) {
1759 return array($sent, $activity->id
, $success);
1763 * Send the sms message to a specific contact.
1766 * The contact id of the recipient.
1768 * @param array $smsParams
1769 * The params used for sending sms.
1770 * @param int $activityID
1771 * The activity ID that tracks the message.
1772 * @param int $userID
1774 * @return bool|PEAR_Error
1775 * true on success or PEAR_Error object
1777 public static function sendSMSMessage(
1780 $smsParams = array(),
1785 $toPhoneNumber = "";
1787 if ($smsParams['To']) {
1788 $toPhoneNumber = trim($smsParams['To']);
1791 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1792 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1793 // To get primary mobile phonenumber,if not get the first mobile phonenumber
1794 if (!empty($toPhoneNumbers)) {
1795 $toPhoneNumerDetails = reset($toPhoneNumbers);
1796 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1797 // Contact allows to send sms
1802 // make sure both phone are valid
1803 // and that the recipient wants to receive sms
1804 if (empty($toPhoneNumber) or $toDoNotSms) {
1805 return PEAR
::raiseError(
1806 'Recipient phone number is invalid or recipient does not want to receive SMS',
1812 $recipient = $smsParams['To'];
1813 $smsParams['contact_id'] = $toID;
1814 $smsParams['parent_activity_id'] = $activityID;
1816 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1817 $sendResult = $providerObj->send($recipient, $smsParams, $tokenText, NULL, $userID);
1818 if (PEAR
::isError($sendResult)) {
1822 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1823 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1825 // add activity target record for every sms that is send
1826 $activityTargetParams = array(
1827 'activity_id' => $activityID,
1828 'contact_id' => $toID,
1829 'record_type_id' => $targetID,
1831 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1837 * Send the message to a specific contact.
1839 * @param string $from
1840 * The name and email of the sender.
1841 * @param int $fromID
1843 * The contact id of the recipient.
1844 * @param string $subject
1845 * The subject of the message.
1846 * @param $text_message
1847 * @param $html_message
1848 * @param string $emailAddress
1849 * Use this 'to' email address instead of the default Primary address.
1850 * @param int $activityID
1851 * The activity ID that tracks the message.
1852 * @param null $attachments
1857 * TRUE if successful else FALSE.
1859 public static function sendMessage(
1868 $attachments = NULL,
1872 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1873 if ($emailAddress) {
1874 $toEmail = trim($emailAddress);
1877 // make sure both email addresses are valid
1878 // and that the recipient wants to receive email
1879 if (empty($toEmail) or $toDoNotEmail) {
1882 if (!trim($toDisplayName)) {
1883 $toDisplayName = $toEmail;
1886 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1887 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1889 // create the params array
1890 $mailParams = array(
1891 'groupName' => 'Activity Email Sender',
1893 'toName' => $toDisplayName,
1894 'toEmail' => $toEmail,
1895 'subject' => $subject,
1898 'text' => $text_message,
1899 'html' => $html_message,
1900 'attachments' => $attachments,
1903 if (!CRM_Utils_Mail
::send($mailParams)) {
1907 // add activity target record for every mail that is send
1908 $activityTargetParams = array(
1909 'activity_id' => $activityID,
1910 'contact_id' => $toID,
1911 'record_type_id' => $targetID,
1913 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1918 * Combine all the importable fields from the lower levels object.
1920 * The ordering is important, since currently we do not have a weight
1921 * scheme. Adding weight is super important and should be done in the
1922 * next week or so, before this can be called complete.
1924 * @param bool $status
1927 * array of importable Fields
1929 public static function &importableFields($status = FALSE) {
1930 if (!self
::$_importableFields) {
1931 if (!self
::$_importableFields) {
1932 self
::$_importableFields = array();
1935 $fields = array('' => array('title' => ts('- do not import -')));
1938 $fields = array('' => array('title' => ts('- Activity Fields -')));
1941 $tmpFields = CRM_Activity_DAO_Activity
::import();
1942 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1944 // Using new Dedupe rule.
1945 $ruleParams = array(
1946 'contact_type' => 'Individual',
1947 'used' => 'Unsupervised',
1949 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1951 $tmpConatctField = array();
1952 if (is_array($fieldsArray)) {
1953 foreach ($fieldsArray as $value) {
1954 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1959 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1960 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1961 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1964 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1965 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1966 $fields = array_merge($fields, $tmpConatctField);
1967 $fields = array_merge($fields, $tmpFields);
1968 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1969 self
::$_importableFields = $fields;
1971 return self
::$_importableFields;
1975 * @deprecated - use the api instead.
1977 * Get the Activities of a target contact.
1979 * @param int $contactId
1980 * Id of the contact whose activities need to find.
1983 * array of activity fields
1985 public static function getContactActivity($contactId) {
1986 // @todo remove this function entirely.
1987 $activities = array();
1988 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1989 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1990 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1991 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1993 // First look for activities where contactId is one of the targets
1995 SELECT activity_id, record_type_id
1996 FROM civicrm_activity_contact
1997 WHERE contact_id = $contactId
1999 $dao = CRM_Core_DAO
::executeQuery($query);
2000 while ($dao->fetch()) {
2001 if ($dao->record_type_id
== $targetID) {
2002 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
2004 elseif ($dao->record_type_id
== $assigneeID) {
2005 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
2008 // do source stuff here
2009 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
2013 $activityIds = array_keys($activities);
2014 if (count($activityIds) < 1) {
2018 $activityIds = implode(',', $activityIds);
2020 SELECT activity.id as activity_id,
2022 subject, location, activity_date_time, details, status_id
2023 FROM civicrm_activity activity
2024 WHERE activity.id IN ($activityIds)";
2026 $dao = CRM_Core_DAO
::executeQuery($query);
2028 while ($dao->fetch()) {
2029 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
2030 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
2031 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
2032 $activities[$dao->activity_id
]['location'] = $dao->location
;
2033 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
2034 $activities[$dao->activity_id
]['details'] = $dao->details
;
2035 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
2036 $activities[$dao->activity_id
]['activity_name'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id
);
2037 $activities[$dao->activity_id
]['status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id
);
2039 // set to null if not set
2040 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
2041 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
2048 * Add activity for Membership/Event/Contribution.
2050 * @param object $activity
2051 * (reference) particular component object.
2052 * @param string $activityType
2053 * For Membership Signup or Renewal.
2054 * @param int $targetContactID
2055 * @param array $params
2056 * Activity params to override.
2060 public static function addActivity(
2062 $activityType = 'Membership Signup',
2063 $targetContactID = NULL,
2066 $date = date('YmdHis');
2067 if ($activity->__table
== 'civicrm_membership') {
2068 $component = 'Membership';
2070 elseif ($activity->__table
== 'civicrm_participant') {
2071 if ($activityType != 'Email') {
2072 $activityType = 'Event Registration';
2074 $component = 'Event';
2076 elseif ($activity->__table
== 'civicrm_contribution') {
2077 // create activity record only for Completed Contributions
2078 if ($activity->contribution_status_id
!= 1) {
2081 $activityType = $component = 'Contribution';
2083 // retrieve existing activity based on source_record_id and activity_type
2084 if (empty($params['id'])) {
2085 $params['id'] = CRM_Utils_Array
::value('id', civicrm_api3('Activity', 'Get', array(
2086 'source_record_id' => $activity->id
,
2087 'activity_type_id' => $activityType,
2090 if (!empty($params['id'])) {
2091 // CRM-13237 : if activity record found, update it with campaign id of contribution
2092 $params['campaign_id'] = $activity->campaign_id
;
2095 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
2098 $activityParams = array(
2099 'source_contact_id' => $activity->contact_id
,
2100 'source_record_id' => $activity->id
,
2101 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
2102 'activity_date_time' => $date,
2103 'is_test' => $activity->is_test
,
2104 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
2105 'skipRecentView' => TRUE,
2106 'campaign_id' => $activity->campaign_id
,
2108 $activityParams = array_merge($activityParams, $params);
2110 if (empty($activityParams['subject'])) {
2111 $activityParams['subject'] = self
::getActivitySubject($activity);
2114 if (!empty($activity->activity_id
)) {
2115 $activityParams['id'] = $activity->activity_id
;
2117 // create activity with target contacts
2118 $id = CRM_Core_Session
::getLoggedInContactID();
2120 $activityParams['source_contact_id'] = $id;
2121 $activityParams['target_contact_id'][] = $activity->contact_id
;
2125 if (property_exists($activity, 'details')) {
2126 $activityParams['details'] = $activity->details
;
2129 if ($targetContactID) {
2130 $activityParams['target_contact_id'][] = $targetContactID;
2132 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
2133 // deal with any exceptions.
2134 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
2135 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
2141 * Get activity subject on basis of component object.
2143 * @param object $entityObj
2144 * particular component object.
2148 public static function getActivitySubject($entityObj) {
2149 switch ($entityObj->__table
) {
2150 case 'civicrm_membership':
2151 $membershipType = CRM_Member_PseudoConstant
::membershipType($entityObj->membership_type_id
);
2152 $subject = $membershipType ?
$membershipType : ts('Membership');
2154 if (is_array($subject)) {
2155 $subject = implode(", ", $subject);
2158 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
2159 $subject .= " - {$entityObj->source}";
2162 if ($entityObj->owner_membership_id
) {
2163 list($displayName) = CRM_Contact_BAO_Contact
::getDisplayAndImage(CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id
, 'contact_id'));
2164 $subject .= sprintf(' (by %s)', $displayName);
2167 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $entityObj->status_id
, 'label');
2170 case 'civicrm_participant':
2171 $event = CRM_Event_BAO_Event
::getEvents(1, $entityObj->event_id
, TRUE, FALSE);
2172 $roles = CRM_Event_PseudoConstant
::participantRole();
2173 $status = CRM_Event_PseudoConstant
::participantStatus();
2174 $subject = $event[$entityObj->event_id
];
2176 if (!empty($roles[$entityObj->role_id
])) {
2177 $subject .= ' - ' . $roles[$entityObj->role_id
];
2179 if (!empty($status[$entityObj->status_id
])) {
2180 $subject .= ' - ' . $status[$entityObj->status_id
];
2185 case 'civicrm_contribution':
2186 $subject = CRM_Utils_Money
::format($entityObj->total_amount
, $entityObj->currency
);
2187 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
2188 $subject .= " - {$entityObj->source}";
2196 * Get Parent activity for currently viewed activity.
2198 * @param int $activityId
2199 * Current activity id.
2202 * Id of parent activity otherwise false.
2204 public static function getParentActivity($activityId) {
2205 static $parentActivities = array();
2207 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
2209 if (!array_key_exists($activityId, $parentActivities)) {
2210 $parentActivities[$activityId] = array();
2212 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2217 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
2220 return $parentActivities[$activityId];
2224 * Get total count of prior revision of currently viewed activity.
2226 * @param $activityID
2227 * Current activity id.
2230 * $params count of prior activities otherwise false.
2232 public static function getPriorCount($activityID) {
2233 static $priorCounts = array();
2235 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2237 if (!array_key_exists($activityID, $priorCounts)) {
2238 $priorCounts[$activityID] = array();
2239 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2246 SELECT count( id ) AS cnt
2247 FROM civicrm_activity
2248 WHERE ( id = {$originalID} OR original_id = {$originalID} )
2249 AND is_current_revision = 0
2250 AND id < {$activityID}
2252 $params = array(1 => array($originalID, 'Integer'));
2253 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
2255 $priorCounts[$activityID] = $count ?
$count : 0;
2258 return $priorCounts[$activityID];
2262 * Get all prior activities of currently viewed activity.
2264 * @param $activityID
2265 * Current activity id.
2266 * @param bool $onlyPriorRevisions
2269 * prior activities info.
2271 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
2272 static $priorActivities = array();
2274 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2275 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2277 if (!array_key_exists($index, $priorActivities)) {
2278 $priorActivities[$index] = array();
2280 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2285 $originalID = $activityID;
2289 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2290 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2291 WHERE (ca.id = %1 OR ca.original_id = %1)
2292 AND cl.entity_table = 'civicrm_activity'
2293 AND cl.entity_id = ca.id
2294 AND cl.modified_id = c.id
2296 if ($onlyPriorRevisions) {
2297 $query .= " AND ca.id < {$activityID}";
2299 $query .= " ORDER BY ca.id DESC";
2301 $params = array(1 => array($originalID, 'Integer'));
2302 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2304 while ($dao->fetch()) {
2305 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
2306 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
2307 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
2312 return $priorActivities[$index];
2316 * Find the latest revision of a given activity.
2318 * @param int $activityID
2319 * Prior activity id.
2322 * current activity id.
2324 public static function getLatestActivityId($activityID) {
2325 static $latestActivityIds = array();
2327 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2329 if (!array_key_exists($activityID, $latestActivityIds)) {
2330 $latestActivityIds[$activityID] = array();
2332 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2337 $activityID = $originalID;
2339 $params = array(1 => array($activityID, 'Integer'));
2340 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2342 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2345 return $latestActivityIds[$activityID];
2349 * Create a follow up a given activity.
2351 * @param int $activityId
2352 * activity id of parent activity.
2353 * @param array $params
2355 * @return CRM_Activity_BAO_Activity|null|object
2357 public static function createFollowupActivity($activityId, $params) {
2362 $followupParams = array();
2363 $followupParams['parent_id'] = $activityId;
2364 $followupParams['source_contact_id'] = CRM_Core_Session
::getLoggedInContactID();
2365 $followupParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
2366 'activity_status_id',
2370 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2371 // Get Subject of Follow-up Activiity, CRM-4491
2372 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2373 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2375 // Create target contact for followup.
2376 if (!empty($params['target_contact_id'])) {
2377 $followupParams['target_contact_id'] = $params['target_contact_id'];
2380 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2381 $params['followup_date_time']
2383 $followupActivity = self
::create($followupParams);
2385 return $followupActivity;
2389 * Get Activity specific File according activity type Id.
2391 * @param int $activityTypeId
2393 * @param string $crmDir
2395 * @return string|bool
2396 * if file exists returns $activityTypeFile activity filename otherwise false.
2398 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2399 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2401 if ($activityTypes[$activityTypeId]['name']) {
2402 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2408 global $civicrm_root;
2409 $config = CRM_Core_Config
::singleton();
2410 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2411 if (empty($config->customPHPPathDir
)) {
2414 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2419 return $activityTypeFile;
2423 * Restore the activity.
2425 * @param array $params
2427 * @return CRM_Activity_DAO_Activity
2429 public static function restoreActivity(&$params) {
2430 $activity = new CRM_Activity_DAO_Activity();
2431 $activity->copyValues($params);
2433 $activity->is_deleted
= 0;
2434 $result = $activity->save();
2440 * Return list of activity statuses of a given type.
2442 * Note: activity status options use the "grouping" field to distinguish status types.
2443 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2449 public static function getStatusesByType($type) {
2450 if (!isset(Civi
::$statics[__CLASS__
][__FUNCTION__
])) {
2451 $statuses = civicrm_api3('OptionValue', 'get', array(
2452 'option_group_id' => 'activity_status',
2453 'return' => array('value', 'name', 'filter'),
2454 'options' => array('limit' => 0),
2456 Civi
::$statics[__CLASS__
][__FUNCTION__
] = $statuses['values'];
2459 foreach (Civi
::$statics[__CLASS__
][__FUNCTION__
] as $status) {
2460 if ($status['filter'] == $type) {
2461 $ret[$status['value']] = $status['name'];
2468 * Check if activity is overdue.
2470 * @param array $activity
2474 public static function isOverdue($activity) {
2475 return array_key_exists($activity['status_id'], self
::getStatusesByType(self
::INCOMPLETE
)) && CRM_Utils_Date
::overdue($activity['activity_date_time']);
2479 * Get the exportable fields for Activities.
2481 * @param string $name
2482 * If it is called by case $name = Case else $name = Activity.
2485 * array of exportable Fields
2487 public static function &exportableFields($name = 'Activity') {
2488 if (!isset(self
::$_exportableFields[$name])) {
2489 self
::$_exportableFields[$name] = array();
2491 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2492 // my case hence we have defined fields as case_*
2493 if ($name == 'Activity') {
2494 $exportableFields = CRM_Activity_DAO_Activity
::export();
2495 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2496 $exportableFields['source_contact'] = array(
2497 'title' => ts('Source Contact'),
2498 'type' => CRM_Utils_Type
::T_STRING
,
2501 $Activityfields = array(
2502 'activity_type' => array(
2503 'title' => ts('Activity Type'),
2504 'name' => 'activity_type',
2505 'type' => CRM_Utils_Type
::T_STRING
,
2506 'searchByLabel' => TRUE,
2508 'activity_status' => array(
2509 'title' => ts('Activity Status'),
2510 'name' => 'activity_status',
2511 'type' => CRM_Utils_Type
::T_STRING
,
2512 'searchByLabel' => TRUE,
2514 'activity_priority' => array(
2515 'title' => ts('Activity Priority'),
2516 'name' => 'activity_priority',
2517 'type' => CRM_Utils_Type
::T_STRING
,
2518 'searchByLabel' => TRUE,
2521 $fields = array_merge($Activityfields, $exportableFields);
2524 // Set title to activity fields.
2526 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2527 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2528 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2529 'case_scheduled_activity_date' => array(
2530 'title' => ts('Activity Scheduled Date'),
2531 'type' => CRM_Utils_Type
::T_DATE
,
2533 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2534 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2535 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2536 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2537 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2538 'case_activity_is_auto' => array(
2539 'title' => ts('Activity Auto-generated?'),
2540 'type' => CRM_Utils_Type
::T_BOOLEAN
,
2545 // add custom data for case activities
2546 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2548 self
::$_exportableFields[$name] = $fields;
2550 return self
::$_exportableFields[$name];
2554 * Get the allowed profile fields for Activities.
2557 * array of activity profile Fields
2559 public static function getProfileFields() {
2560 $exportableFields = self
::exportableFields('Activity');
2561 $skipFields = array(
2564 'source_contact_id',
2566 'activity_campaign',
2568 'is_current_revision',
2569 'activity_is_deleted',
2571 $config = CRM_Core_Config
::singleton();
2572 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2573 $skipFields[] = 'activity_engagement_level';
2576 foreach ($skipFields as $field) {
2577 if (isset($exportableFields[$field])) {
2578 unset($exportableFields[$field]);
2582 // hack to use 'activity_type_id' instead of 'activity_type'
2583 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2584 unset($exportableFields['activity_status']);
2586 return $exportableFields;
2590 * This function deletes the activity record related to contact record.
2592 * This is conditional on there being no target and assignee record
2593 * with other contacts.
2595 * @param int $contactId
2600 public static function cleanupActivity($contactId) {
2605 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2606 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2608 $transaction = new CRM_Core_Transaction();
2610 // delete activity if there is no record in civicrm_activity_contact
2611 // pointing to any other contact record
2612 $activityContact = new CRM_Activity_DAO_ActivityContact();
2613 $activityContact->contact_id
= $contactId;
2614 $activityContact->record_type_id
= $sourceID;
2615 $activityContact->find();
2617 while ($activityContact->fetch()) {
2618 // delete activity_contact record for the deleted contact
2619 $activityContact->delete();
2621 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2622 $activityContactOther->activity_id
= $activityContact->activity_id
;
2624 // delete activity only if no other contacts connected
2625 if (!$activityContactOther->find(TRUE)) {
2626 $activityParams = array('id' => $activityContact->activity_id
);
2627 $result = self
::deleteActivity($activityParams);
2630 $activityContactOther->free();
2633 $activityContact->free();
2634 $transaction->commit();
2640 * Does user has sufficient permission for view/edit activity record.
2642 * @param int $activityId
2643 * Activity record id.
2644 * @param int $action
2649 public static function checkPermission($activityId, $action) {
2652 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2657 $activity = new CRM_Activity_DAO_Activity();
2658 $activity->id
= $activityId;
2659 if (!$activity->find(TRUE)) {
2663 // Component related permissions.
2664 $compPermissions = array(
2665 'CiviCase' => array(
2666 'administer CiviCase',
2667 'access my cases and activities',
2668 'access all cases and activities',
2670 'CiviMail' => array('access CiviMail'),
2671 'CiviEvent' => array('access CiviEvent'),
2672 'CiviGrant' => array('access CiviGrant'),
2673 'CiviPledge' => array('access CiviPledge'),
2674 'CiviMember' => array('access CiviMember'),
2675 'CiviReport' => array('access CiviReport'),
2676 'CiviContribute' => array('access CiviContribute'),
2677 'CiviCampaign' => array('administer CiviCampaign'),
2680 // Return early when it is case activity.
2681 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2682 // Check for civicase related permission.
2683 if ($isCaseActivity) {
2685 foreach ($compPermissions['CiviCase'] as $per) {
2686 if (CRM_Core_Permission
::check($per)) {
2692 // Check for case specific permissions.
2695 if ($action == CRM_Core_Action
::UPDATE
) {
2698 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2700 $activity->activity_type_id
2707 // First check the component permission.
2710 FROM civicrm_option_value val
2711 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2712 WHERE val.value = %2";
2714 1 => array('activity_type', 'String'),
2715 2 => array($activity->activity_type_id
, 'Integer'),
2717 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2720 $componentName = CRM_Core_Component
::getComponentName($componentId);
2721 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2723 // Here we are interesting in any single permission.
2724 if (is_array($compPermission)) {
2725 foreach ($compPermission as $per) {
2726 if (CRM_Core_Permission
::check($per)) {
2734 // Check for this permission related to contact.
2735 $permission = CRM_Core_Permission
::VIEW
;
2736 if ($action == CRM_Core_Action
::UPDATE
) {
2737 $permission = CRM_Core_Permission
::EDIT
;
2740 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2741 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2742 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2743 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2745 // Check for source contact.
2746 if (!$componentId ||
$allow) {
2747 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2748 // Account for possibility of activity not having a source contact (as it may have been deleted).
2749 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission) : TRUE;
2752 // Check for target and assignee contacts.
2754 // First check for supper permission.
2755 $supPermission = 'view all contacts';
2756 if ($action == CRM_Core_Action
::UPDATE
) {
2757 $supPermission = 'edit all contacts';
2759 $allow = CRM_Core_Permission
::check($supPermission);
2761 // User might have sufficient permission, through acls.
2764 // Get the target contacts.
2765 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2766 foreach ($targetContacts as $cnt => $contactId) {
2767 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2773 // Get the assignee contacts.
2775 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2776 foreach ($assigneeContacts as $cnt => $contactId) {
2777 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2790 * Wrapper for ajax activity selector.
2792 * @param array $params
2793 * Associated array for params record id.
2796 * Associated array of contact activities
2798 public static function getContactActivitySelector(&$params) {
2799 // Format the params.
2800 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2801 $params['rowCount'] = $params['rp'];
2802 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2803 $params['caseId'] = NULL;
2804 $context = CRM_Utils_Array
::value('context', $params);
2805 $showContactOverlay = !CRM_Utils_String
::startsWith($context, "dashlet");
2806 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2807 'option_group_id' => "activity_type",
2808 'options' => array('limit' => 0),
2810 $activityIcons = array();
2811 foreach ($activityTypeInfo['values'] as $type) {
2812 if (!empty($type['icon'])) {
2813 $activityIcons[$type['value']] = $type['icon'];
2817 // Get contact activities.
2818 $activities = CRM_Activity_BAO_Activity
::deprecatedGetActivities($params);
2821 $params['total'] = CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($params);
2823 // Format params and add links.
2824 $contactActivities = array();
2826 if (!empty($activities)) {
2827 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2829 // Check logged in user for permission.
2830 $page = new CRM_Core_Page();
2831 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2832 $permissions = array($page->_permission
);
2833 if (CRM_Core_Permission
::check('delete activities')) {
2834 $permissions[] = CRM_Core_Permission
::DELETE
;
2837 $mask = CRM_Core_Action
::mask($permissions);
2839 foreach ($activities as $activityId => $values) {
2840 $activity = array();
2841 $activity['DT_RowId'] = $activityId;
2842 // Add class to this row if overdue.
2843 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2844 if (self
::isOverdue($values)) {
2845 $activity['DT_RowClass'] .= ' status-overdue';
2848 $activity['DT_RowClass'] .= ' status-ontime';
2851 $activity['DT_RowAttr'] = array();
2852 $activity['DT_RowAttr']['data-entity'] = 'activity';
2853 $activity['DT_RowAttr']['data-id'] = $activityId;
2855 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ?
'<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2856 $activity['subject'] = $values['subject'];
2858 $activity['source_contact_name'] = '';
2859 if ($params['contact_id'] == $values['source_contact_id']) {
2860 $activity['source_contact_name'] = $values['source_contact_name'];
2862 elseif ($values['source_contact_id']) {
2864 if ($showContactOverlay) {
2865 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2866 CRM_Contact_BAO_Contact
::getContactType($values['source_contact_id']),
2868 $values['source_contact_id']);
2870 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System
::href($values['source_contact_name'],
2871 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2874 $activity['source_contact_name'] = '<em>n/a</em>';
2877 $activity['target_contact_name'] = '';
2878 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2879 $activity['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2880 'civicrm/mailing/report/event',
2881 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2883 elseif (!empty($values['recipients'])) {
2884 $activity['target_contact_name'] = $values['recipients'];
2886 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2887 $activity['target_contact_name'] = '';
2888 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2889 $targetTypeImage = "";
2890 $targetLink = CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2891 if ($showContactOverlay) {
2892 $targetTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2893 CRM_Contact_BAO_Contact
::getContactType($tcID),
2896 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2899 $activity['target_contact_name'] .= $targetLink;
2903 if ($extraCount = $values['target_contact_counter'] - 1) {
2904 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2906 if ($showContactOverlay) {
2907 $activity['target_contact_name'] .= "</div> ";
2910 elseif (!$values['target_contact_name']) {
2911 $activity['target_contact_name'] = '<em>n/a</em>';
2914 $activity['assignee_contact_name'] = '';
2915 if (empty($values['assignee_contact_name'])) {
2916 $activity['assignee_contact_name'] = '<em>n/a</em>';
2918 elseif (!empty($values['assignee_contact_name'])) {
2920 $activity['assignee_contact_name'] = '';
2921 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2922 if ($acID && $count < 5) {
2923 $assigneeTypeImage = "";
2924 $assigneeLink = CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2925 if ($showContactOverlay) {
2926 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2927 CRM_Contact_BAO_Contact
::getContactType($acID),
2930 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2933 $activity['assignee_contact_name'] .= $assigneeLink;
2938 $activity['assignee_contact_name'] .= "; ";
2940 if ($showContactOverlay) {
2941 $activity['assignee_contact_name'] .= "</div> ";
2945 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2952 $activity['activity_date_time'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2953 $activity['status_id'] = $activityStatus[$values['status_id']];
2956 $activity['links'] = '';
2957 $accessMailingReport = FALSE;
2958 if (!empty($values['mailingId'])) {
2959 $accessMailingReport = TRUE;
2962 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2963 CRM_Utils_Array
::value('activity_type_id', $values),
2964 CRM_Utils_Array
::value('source_record_id', $values),
2965 $accessMailingReport,
2966 CRM_Utils_Array
::value('activity_id', $values)
2969 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2971 $activity['links'] = CRM_Core_Action
::formLink($actionLinks,
2974 'id' => $values['activity_id'],
2975 'cid' => $params['contact_id'],
2977 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2983 $values['activity_id']
2986 if ($values['is_recurring_activity']) {
2987 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2990 array_push($contactActivities, $activity);
2994 $activitiesDT = array();
2995 $activitiesDT['data'] = $contactActivities;
2996 $activitiesDT['recordsTotal'] = $params['total'];
2997 $activitiesDT['recordsFiltered'] = $params['total'];
2999 return $activitiesDT;
3003 * Copy custom fields and attachments from an existing activity to another.
3005 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
3007 * @param array $params
3009 public static function copyExtendedActivityData($params) {
3010 // attach custom data to the new activity
3011 $customParams = $htmlType = array();
3012 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
3014 if (!empty($customValues)) {
3015 $fieldIds = implode(', ', array_keys($customValues));
3016 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
3017 $result = CRM_Core_DAO
::executeQuery($sql);
3019 while ($result->fetch()) {
3020 $htmlType[] = $result->id
;
3023 foreach ($customValues as $key => $value) {
3024 if ($value !== NULL) {
3026 if (in_array($key, $htmlType)) {
3027 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
3028 $customParams["custom_{$key}_-1"] = array(
3029 'name' => $fileValues[0],
3030 'path' => $fileValues[1],
3034 $customParams["custom_{$key}_-1"] = $value;
3038 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_activity',
3039 $params['mainActivityId'], 'Activity'
3043 // copy activity attachments ( if any )
3044 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
3048 * Get activity contact.
3050 * @param int $activityId
3051 * @param int $recordTypeID
3052 * @param string $column
3056 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
3057 $activityContact = new CRM_Activity_BAO_ActivityContact();
3058 $activityContact->activity_id
= $activityId;
3059 if ($recordTypeID) {
3060 $activityContact->record_type_id
= $recordTypeID;
3062 if ($activityContact->find(TRUE)) {
3063 return $activityContact->$column;
3069 * Get source contact id.
3071 * @param int $activityId
3075 public static function getSourceContactID($activityId) {
3076 static $sourceID = NULL;
3078 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3079 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
3082 return self
::getActivityContact($activityId, $sourceID);
3088 * @todo Document what this is for.
3090 * @param array $params
3092 public function setApiFilter(&$params) {
3093 if (!empty($params['target_contact_id'])) {
3095 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3096 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3097 $obj = new CRM_Activity_BAO_ActivityContact();
3098 $params['return.target_contact_id'] = 1;
3099 $this->joinAdd($obj, 'LEFT');
3100 $this->selectAdd('civicrm_activity.*');
3101 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
3106 * Send activity as attachment.
3108 * @param object $activity
3109 * @param array $mailToContacts
3110 * @param array $params
3114 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
3115 if (!CRM_Utils_Array
::crmIsEmptyArray($mailToContacts)) {
3116 $clientID = CRM_Utils_Array
::value('client_id', $params);
3117 $caseID = CRM_Utils_Array
::value('case_id', $params);
3119 $ics = new CRM_Activity_BAO_ICalendar($activity);
3120 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity', $activity->id
);
3121 $ics->addAttachment($attachments, $mailToContacts);
3123 $result = CRM_Case_BAO_Case
::sendActivityCopy($clientID, $activity->id
, $mailToContacts, $attachments, $caseID);