3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
601 $subjectToMatch = CRM_Utils_Array
::value('subject', $params);
602 if (preg_match('/\[case #([0-9a-h]{7})\]/', $subjectToMatch, $matches)) {
603 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
605 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '" . CRM_Core_DAO
::escapeString($hash) . "'";
607 elseif (preg_match('/\[case #(\d+)\]/', $subjectToMatch, $matches)) {
608 $query = "SELECT id FROM civicrm_case WHERE id = '" . CRM_Core_DAO
::escapeString($matches[1]) . "'";
610 if (!empty($matches)) {
612 'activity_id' => $activity->id
,
613 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
615 if ($caseParams['case_id']) {
616 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
619 self
::logActivityAction($activity, "Case details for {$matches[1]} not found while recording an activity on case.");
622 if (!empty($params['id'])) {
623 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
626 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
633 * Create an activity.
635 * @todo elaborate on what this does.
637 * @param CRM_Core_DAO_Activity $activity
638 * @param string $logMessage
642 public static function logActivityAction($activity, $logMessage = NULL) {
643 $id = CRM_Core_Session
::getLoggedInContactID();
645 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
646 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
647 $id = self
::getActivityContact($activity->id
, $sourceID);
650 'entity_table' => 'civicrm_activity',
651 'entity_id' => $activity->id
,
652 'modified_id' => $id,
653 'modified_date' => date('YmdHis'),
654 'data' => $logMessage,
656 CRM_Core_BAO_Log
::add($logParams);
661 * Get the list Activities.
663 * @param array $params
664 * Array of parameters.
666 * - contact_id int contact_id whose activities we want to retrieve
667 * - offset int which row to start from ?
668 * - rowCount int how many rows to fetch
669 * - sort object|array object or array describing sort order for sql query.
670 * - admin boolean if contact is admin
671 * - caseId int case ID
672 * - context string page on which selector is build
673 * - activity_type_id int|string the activitiy types we want to restrict by
674 * @param bool $getCount
675 * Get count of the activities
678 * Relevant data object values of open activities
679 * @throws \CiviCRM_API3_Exception
681 public static function getActivities($params, $getCount = FALSE) {
682 $activities = array();
684 // Activity.Get API params
685 $activityParams = array(
687 'is_current_revision' => 1,
689 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
691 'activity_date_time',
694 'source_contact_name',
695 'assignee_contact_id',
697 'target_contact_name',
698 'assignee_contact_name',
706 'check_permissions' => 1,
708 'offset' => CRM_Utils_Array
::value('offset', $params, 0),
712 if (!empty($params['activity_status_id'])) {
713 $activityParams['activity_status_id'] = array('IN' => explode(',', $params['activity_status_id']));
716 $activityParams['activity_type_id'] = self
::filterActivityTypes($params);
718 if (!empty($params['rowCount']) &&
719 $params['rowCount'] > 0
721 $activityParams['options']['limit'] = $params['rowCount'];
723 // set limit = 0 if we need to fetch the activity count
725 $activityParams['options']['limit'] = 0;
728 if (!empty($params['sort'])) {
729 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
730 $order = $params['sort']->orderBy();
732 elseif (trim($params['sort'])) {
733 $order = CRM_Utils_Type
::escape($params['sort'], 'String');
737 $activityParams['options']['sort'] = empty($order) ?
"activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
740 // 1. we should use Activity.Getcount for fetching count only, but in order to check that
741 // current logged in user has permission to view Case activities we are performing filtering out those activities from list (see below).
742 // This logic need to be incorporated in Activity.get definition
743 $result = civicrm_api3('Activity', 'Get', $activityParams);
745 $enabledComponents = self
::activityComponents();
746 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
747 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
749 // CRM-3553, need to check user has access to target groups.
750 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
751 $accessCiviMail = ((CRM_Core_Permission
::check('access CiviMail')) ||
752 (CRM_Mailing_Info
::workflowEnabled() && CRM_Core_Permission
::check('create mailings'))
755 $mappingParams = array(
756 'id' => 'activity_id',
757 'source_record_id' => 'source_record_id',
758 'activity_type_id' => 'activity_type_id',
759 'activity_date_time' => 'activity_date_time',
760 'status_id' => 'status_id',
761 'subject' => 'subject',
762 'campaign_id' => 'campaign_id',
763 'assignee_contact_name' => 'assignee_contact_name',
764 'target_contact_name' => 'target_contact_name',
765 'source_contact_id' => 'source_contact_id',
766 'source_contact_name' => 'source_contact_name',
767 'case_id' => 'case_id',
770 foreach ($result['values'] as $id => $activity) {
771 // skip case activities if CiviCase is not enabled OR those actvities which are
772 if (!empty($activity['case_id']) && !in_array('CiviCase', $enabledComponents)) {
776 $activities[$id] = array();
778 // if count is needed, no need to populate the array list with attributes
783 $isBulkActivity = (!$bulkActivityTypeID ||
($bulkActivityTypeID != $activity['activity_type_id']));
784 foreach ($mappingParams as $apiKey => $expectedName) {
785 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
786 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity, array());
787 if ($apiKey == 'target_contact_name' && count($activity['target_contact_name'])) {
788 $activities[$id]['target_contact_counter'] = count($activity['target_contact_name']);
791 if ($isBulkActivity) {
792 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
793 $activities[$id]['mailingId'] = FALSE;
794 if ($accessCiviMail &&
795 ($mailingIDs === TRUE ||
in_array($activity['source_record_id'], $mailingIDs))
797 $activities[$id]['mailingId'] = TRUE;
801 // case related fields
802 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
803 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
805 // fetch case subject for case ID found
806 if (!empty($activity['case_id'])) {
807 $activities[$id]['case_subject'] = CRM_Core_DAO
::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
811 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
812 if ($apiKey == 'activity_type_id') {
813 $activities[$id]['activity_type'] = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $activities[$id][$expectedName]);
815 elseif ($apiKey == 'campaign_id') {
816 $activities[$id]['campaign'] = CRM_Utils_Array
::value($activities[$id][$expectedName], $allCampaigns);
820 // if deleted, wrap in <del>
821 if (!empty($activity['source_contact_id']) &&
822 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
824 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
826 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getParentFor($id, 'civicrm_activity');
829 return $getCount ?
count($activities) : $activities;
833 * Filter the activity types to only return the ones we actually asked for
834 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
837 * @return array|null (Use in Activity.get API activity_type_id)
839 public static function filterActivityTypes($params) {
840 $activityTypes = array();
842 // If no activity types are specified, get all the active ones
843 if (empty($params['activity_type_id'])) {
844 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'get');
847 // If no activity types are specified or excluded, return the list of all active ones
848 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
849 if (!empty($activityTypes)) {
850 return array('IN' => array_keys($activityTypes));
855 // If we have specified activity types, build a list to return, excluding the ones we don't want.
856 if (!empty($params['activity_type_id'])) {
857 if (!is_array($params['activity_type_id'])) {
858 // Turn it into array if only one specified, so we don't duplicate processing below
859 $params['activity_type_id'] = array($params['activity_type_id'] => $params['activity_type_id']);
861 foreach ($params['activity_type_id'] as $value) {
862 // Add each activity type that was specified to list
863 $value = CRM_Utils_Type
::escape($value, 'Positive');
864 $activityTypes[$value] = $value;
868 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
869 if (!empty($params['activity_type_exclude_id'])) {
870 if (!is_array($params['activity_type_exclude_id'])) {
871 // Turn it into array if only one specified, so we don't duplicate processing below
872 $params['activity_type_exclude_id'] = array($params['activity_type_exclude_id'] => $params['activity_type_exclude_id']);
874 foreach ($params['activity_type_exclude_id'] as $value) {
875 // Remove each activity type from list if it should be excluded
876 $value = CRM_Utils_Type
::escape($value, 'Positive');
877 if (array_key_exists($value, $activityTypes)) {
878 unset($activityTypes[$value]);
883 return array('IN' => array_keys($activityTypes));
887 * Get the list Activities.
891 * @todo - use the api for this - this is working but have temporarily backed out
892 * due to performance issue to be resolved - CRM-20481.
894 * @param array $input
895 * Array of parameters.
897 * - contact_id int contact_id whose activities we want to retrieve
898 * - offset int which row to start from ?
899 * - rowCount int how many rows to fetch
900 * - sort object|array object or array describing sort order for sql query.
901 * - admin boolean if contact is admin
902 * - caseId int case ID
903 * - context string page on which selector is build
904 * - activity_type_id int|string the activitiy types we want to restrict by
907 * Relevant data object values of open activities
909 public static function deprecatedGetActivities($input) {
910 // Step 1: Get the basic activity data.
911 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
916 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
917 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
918 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
919 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
921 $config = CRM_Core_Config
::singleton();
923 $randomNum = md5(uniqid());
924 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
926 $tableFields = array(
927 'activity_id' => 'int unsigned',
928 'activity_date_time' => 'datetime',
929 'source_record_id' => 'int unsigned',
930 'status_id' => 'int unsigned',
931 'subject' => 'varchar(255)',
932 'source_contact_name' => 'varchar(255)',
933 'activity_type_id' => 'int unsigned',
934 'activity_type' => 'varchar(128)',
935 'case_id' => 'int unsigned',
936 'case_subject' => 'varchar(255)',
937 'campaign_id' => 'int unsigned',
940 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
941 $insertValueSQL = $selectColumns = array();
942 // The activityTempTable contains the sorted rows
943 // so in order to maintain the sort order as-is we add an auto_increment
944 // field; we can sort by this later to ensure the sort order stays correct.
945 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
946 foreach ($tableFields as $name => $desc) {
947 $sql .= "$name $desc,\n";
948 $insertValueSQL[] = $name;
949 if ($name == 'source_contact_name' && CRM_Utils_SQL
::supportsFullGroupBy()) {
950 $selectColumns[] = "ANY_VALUE(tbl.$name)";
953 $selectColumns[] = "tbl.$name";
957 // add unique key on activity_id just to be sure
958 // this cannot be primary key because we need that for the auto_increment
959 // fixed_sort_order field
961 UNIQUE KEY ( activity_id )
962 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
965 CRM_Core_DAO
::executeQuery($sql);
967 $insertSQL = "INSERT IGNORE INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
969 $order = $limit = $groupBy = '';
970 $groupBy = " GROUP BY tbl.activity_id, tbl.activity_type, tbl.case_id, tbl.case_subject ";
972 if (!empty($input['sort'])) {
973 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
974 $orderBy = $input['sort']->orderBy();
975 if (!empty($orderBy)) {
976 $order = " ORDER BY $orderBy";
979 elseif (trim($input['sort'])) {
980 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
981 $order = " ORDER BY $sort ";
986 // context = 'activity' in Activities tab.
987 $order = " ORDER BY tbl.activity_date_time desc ";
990 if (!empty($input['rowCount']) &&
991 $input['rowCount'] > 0
993 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
996 $input['count'] = FALSE;
997 list($sqlClause, $params) = self
::deprecatedGetActivitySQLClause($input);
999 $query = sprintf("{$insertSQL} \n SELECT DISTINCT %s from ( %s ) \n as tbl ", implode(', ', $selectColumns), $sqlClause);
1001 // Filter case activities - CRM-5761.
1002 $components = self
::activityComponents();
1003 if (!in_array('CiviCase', $components)) {
1005 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
1006 WHERE civicrm_case_activity.id IS NULL";
1009 $query = $query . $groupBy . $order . $limit;
1011 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1013 // step 2: Get target and assignee contacts for above activities
1014 // create temp table for target contacts
1015 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
1016 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
1017 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
1018 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
1019 ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
1021 CRM_Core_DAO
::executeQuery($query);
1023 // note that we ignore bulk email for targets, since we don't show it in selector
1025 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
1026 SELECT ac.activity_id,
1031 FROM {$activityTempTable}
1032 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1033 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1034 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1035 WHERE ac.record_type_id != %1
1037 $params = array(1 => array($targetID, 'Integer'));
1038 CRM_Core_DAO
::executeQuery($query, $params);
1040 $activityFields = array("ac.activity_id", "ac.contact_id", "ac.record_type_id", "c.sort_name", "c.is_deleted");
1041 $select = CRM_Contact_BAO_Query
::appendAnyValueToSelect($activityFields, "ac.activity_id");
1043 // for each activity insert one target contact
1044 // if we load all target contacts the performance will suffer a lot for mass-activities.
1046 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
1047 {$select}, count(ac.contact_id)
1048 FROM {$activityTempTable}
1049 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1050 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1051 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1052 WHERE ac.record_type_id = %1
1053 GROUP BY ac.activity_id
1056 CRM_Core_DAO
::executeQuery($query, $params);
1058 // step 3: Combine all temp tables to get final query for activity selector
1059 // sort by the original sort order, stored in fixed_sort_order
1061 SELECT {$activityTempTable}.*,
1062 {$activityContactTempTable}.contact_id,
1063 {$activityContactTempTable}.record_type_id,
1064 {$activityContactTempTable}.contact_name,
1065 {$activityContactTempTable}.is_deleted,
1066 {$activityContactTempTable}.counter,
1067 re.parent_id as is_recurring_activity
1068 FROM {$activityTempTable}
1069 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
1070 LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
1071 ORDER BY fixed_sort_order
1074 $dao = CRM_Core_DAO
::executeQuery($query);
1076 // CRM-3553, need to check user has access to target groups.
1077 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
1079 (CRM_Core_Permission
::check('access CiviMail')) ||
1080 (CRM_Mailing_Info
::workflowEnabled() &&
1081 CRM_Core_Permission
::check('create mailings'))
1084 // Get all campaigns.
1085 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
1087 while ($dao->fetch()) {
1088 $activityID = $dao->activity_id
;
1089 $values[$activityID]['activity_id'] = $dao->activity_id
;
1090 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
1091 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
1092 $values[$activityID]['activity_type'] = $dao->activity_type
;
1093 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
1094 $values[$activityID]['status_id'] = $dao->status_id
;
1095 $values[$activityID]['subject'] = $dao->subject
;
1096 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
1097 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity
;
1099 if ($dao->campaign_id
) {
1100 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
1103 if (empty($values[$activityID]['assignee_contact_name'])) {
1104 $values[$activityID]['assignee_contact_name'] = array();
1107 if (empty($values[$activityID]['target_contact_name'])) {
1108 $values[$activityID]['target_contact_name'] = array();
1109 $values[$activityID]['target_contact_counter'] = $dao->counter
;
1112 // if deleted, wrap in <del>
1113 if ($dao->is_deleted
) {
1114 $dao->contact_name
= "<del>{$dao->contact_name}</del>";
1117 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
1118 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
1119 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
1122 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
1123 // build array of target / assignee names
1124 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
1125 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
1127 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
1128 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
1131 // case related fields
1132 $values[$activityID]['case_id'] = $dao->case_id
;
1133 $values[$activityID]['case_subject'] = $dao->case_subject
;
1136 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter
));
1137 $values[$activityID]['mailingId'] = FALSE;
1140 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
1142 $values[$activityID]['mailingId'] = TRUE;
1151 * Get the component id and name if those are enabled and allowed.
1153 * Checks whether logged in user has permission.
1154 * To decide whether we are going to include
1155 * component related activities with core activity retrieve process.
1156 * (what did that just mean?)
1159 * Array of component id and name.
1161 public static function activityComponents() {
1162 $components = array();
1163 $compInfo = CRM_Core_Component
::getEnabledComponents();
1164 foreach ($compInfo as $compObj) {
1165 if (!empty($compObj->info
['showActivitiesInCore'])) {
1166 if ($compObj->info
['name'] == 'CiviCampaign') {
1167 $componentPermission = "administer {$compObj->name}";
1170 $componentPermission = "access {$compObj->name}";
1172 if ($compObj->info
['name'] == 'CiviCase') {
1173 if (CRM_Case_BAO_Case
::accessCiviCase()) {
1174 $components[$compObj->componentID
] = $compObj->info
['name'];
1177 elseif (CRM_Core_Permission
::check($componentPermission)) {
1178 $components[$compObj->componentID
] = $compObj->info
['name'];
1187 * Get the activity Count.
1189 * @param array $input
1190 * Array of parameters.
1192 * - contact_id int contact_id whose activities we want to retrieve
1193 * - admin boolean if contact is admin
1194 * - caseId int case ID
1195 * - context string page on which selector is build
1196 * - activity_type_id int|string the activity types we want to restrict by
1199 * count of activities
1201 public static function getActivitiesCount($input) {
1202 return self
::getActivities($input, TRUE);
1206 * Get the activity Count.
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 * - activity_type_id int|string the activity types we want to restrict by
1220 * count of activities
1222 public static function deprecatedGetActivitiesCount($input) {
1223 $input['count'] = TRUE;
1224 list($sqlClause, $params) = self
::deprecatedGetActivitySQLClause($input);
1226 //filter case activities - CRM-5761
1227 $components = self
::activityComponents();
1228 if (!in_array('CiviCase', $components)) {
1230 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
1231 FROM ( {$sqlClause} ) as tbl
1232 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
1233 WHERE civicrm_case_activity.id IS NULL";
1236 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
1239 return CRM_Core_DAO
::singleValueQuery($query, $params);
1243 * Get the activity sql clause to pick activities.
1247 * @param array $input
1248 * Array of parameters.
1250 * - contact_id int contact_id whose activities we want to retrieve
1251 * - admin boolean if contact is admin
1252 * - caseId int case ID
1253 * - context string page on which selector is build
1254 * - count boolean are we interested in the count clause only?
1255 * - activity_type_id int|string the activity types we want to restrict by
1258 * count of activities
1260 public static function deprecatedGetActivitySQLClause($input) {
1262 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1264 $config = CRM_Core_Config
::singleton();
1265 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
1266 $sourceWhere = ' ac.contact_id = %1 ';
1267 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1269 $params = array(1 => array($input['contact_id'], 'Integer'));
1272 $commonClauses = array(
1273 "civicrm_option_group.name = 'activity_type'",
1274 "civicrm_activity.is_deleted = 0",
1275 "civicrm_activity.is_current_revision = 1",
1276 "civicrm_activity.is_test= 0",
1279 if (isset($input['activity_date_relative']) ||
1280 (!empty($input['activity_date_low']) ||
!empty($input['activity_date_high']))
1282 list($from, $to) = CRM_Utils_Date
::getFromTo(
1283 CRM_Utils_Array
::value('activity_date_relative', $input, 0),
1284 CRM_Utils_Array
::value('activity_date_low', $input),
1285 CRM_Utils_Array
::value('activity_date_high', $input)
1287 $commonClauses[] = sprintf('civicrm_activity.activity_date_time BETWEEN "%s" AND "%s" ', $from, $to);
1290 if (!empty($input['activity_status_id'])) {
1291 $commonClauses[] = sprintf("civicrm_activity.status_id IN (%s)", $input['activity_status_id']);
1294 // Filter on component IDs.
1295 $components = self
::activityComponents();
1296 if (!empty($components)) {
1297 $componentsIn = implode(',', array_keys($components));
1298 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1301 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1304 // activity type ID clause
1305 if (!empty($input['activity_type_id'])) {
1306 if (is_array($input['activity_type_id'])) {
1307 foreach ($input['activity_type_id'] as $idx => $value) {
1308 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1310 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1313 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1314 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1318 // exclude by activity type clause
1319 if (!empty($input['activity_type_exclude_id'])) {
1320 if (is_array($input['activity_type_exclude_id'])) {
1321 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1322 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1324 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1327 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1328 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1332 $commonClause = implode(' AND ', $commonClauses);
1334 $includeCaseActivities = FALSE;
1335 if (in_array('CiviCase', $components)) {
1336 $includeCaseActivities = TRUE;
1339 // build main activity table select clause
1342 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1343 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1345 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1346 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1349 if (!$input['count']) {
1351 civicrm_activity.activity_date_time,
1352 civicrm_activity.source_record_id,
1353 civicrm_activity.status_id,
1354 civicrm_activity.subject,
1355 contact.sort_name as source_contact_name,
1356 civicrm_option_value.value as activity_type_id,
1357 civicrm_option_value.label as activity_type,
1358 null as case_id, null as case_subject,
1359 civicrm_activity.campaign_id as campaign_id
1363 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)
1368 SELECT civicrm_activity.id as activity_id
1370 from civicrm_activity
1371 left join civicrm_option_value on
1372 civicrm_activity.activity_type_id = civicrm_option_value.value
1373 left join civicrm_option_group on
1374 civicrm_option_group.id = civicrm_option_value.option_group_id
1381 // Build case clause
1382 // or else exclude Inbound Emails that have been filed on a case.
1385 if ($includeCaseActivities) {
1387 if (!$input['count']) {
1389 civicrm_activity.activity_date_time,
1390 civicrm_activity.source_record_id,
1391 civicrm_activity.status_id,
1392 civicrm_activity.subject,
1393 contact.sort_name as source_contact_name,
1394 civicrm_option_value.value as activity_type_id,
1395 civicrm_option_value.label as activity_type,
1396 null as case_id, null as case_subject,
1397 civicrm_activity.campaign_id as campaign_id';
1403 SELECT civicrm_activity.id as activity_id
1405 from civicrm_activity
1406 inner join civicrm_case_activity on
1407 civicrm_case_activity.activity_id = civicrm_activity.id
1408 inner join civicrm_case on
1409 civicrm_case_activity.case_id = civicrm_case.id
1410 inner join civicrm_case_contact on
1411 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1412 left join civicrm_option_value on
1413 civicrm_activity.activity_type_id = civicrm_option_value.value
1414 left join civicrm_option_group on
1415 civicrm_option_group.id = civicrm_option_value.option_group_id
1420 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1421 ( civicrm_option_value.name <> 'Inbound Email' AND
1422 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1428 $returnClause = " {$sourceClause} {$caseClause} ";
1430 return array($returnClause, $params);
1434 * Send the message to all the contacts.
1436 * Also insert a contact activity in each contacts record.
1438 * @param array $contactDetails
1439 * The array of contact details to send the email.
1440 * @param string $subject
1441 * The subject of the message.
1444 * @param string $emailAddress
1445 * Use this 'to' email address instead of the default Primary address.
1446 * @param int $userID
1447 * Use this userID if set.
1448 * @param string $from
1449 * @param array $attachments
1450 * The array of attachments if any.
1453 * @param string $bcc
1455 * @param array $contactIds
1457 * @param string $additionalDetails
1458 * The additional information of CC and BCC appended to the activity Details.
1459 * @param array $contributionIds
1460 * @param int $campaignId
1463 * ( sent, activityId) if any email is sent and activityId
1465 public static function sendEmail(
1473 $attachments = NULL,
1477 $additionalDetails = NULL,
1478 $contributionIds = NULL,
1481 // get the contact details of logged in contact, which we set as from email
1482 if ($userID == NULL) {
1483 $userID = CRM_Core_Session
::getLoggedInContactID();
1486 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1488 return array(count($contactDetails), 0, count($contactDetails));
1490 if (!trim($fromDisplayName)) {
1491 $fromDisplayName = $fromEmail;
1495 // token replacement of addressee/email/postal greetings
1496 // get the tokens added in subject and message
1497 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1498 $messageToken = CRM_Utils_Token
::getTokens($text);
1499 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1500 $allTokens = array_merge($messageToken, $subjectToken);
1503 $from = "$fromDisplayName <$fromEmail>";
1506 //create the meta level record first ( email activity )
1507 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
1509 // CRM-6265: save both text and HTML parts in details (if present)
1510 if ($html and $text) {
1511 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1514 $details = $html ?
$html : $text;
1515 $details .= $additionalDetails;
1518 $activityParams = array(
1519 'source_contact_id' => $userID,
1520 'activity_type_id' => $activityTypeID,
1521 'activity_date_time' => date('YmdHis'),
1522 'subject' => $subject,
1523 'details' => $details,
1524 // FIXME: check for name Completed and get ID from that lookup
1525 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1526 'campaign_id' => $campaignId,
1529 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1530 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1532 // add the attachments to activity params here
1534 // first process them
1535 $activityParams = array_merge($activityParams,
1540 $activity = self
::create($activityParams);
1542 // get the set of attachments from where they are stored
1543 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1546 $returnProperties = array();
1547 if (isset($messageToken['contact'])) {
1548 foreach ($messageToken['contact'] as $key => $value) {
1549 $returnProperties[$value] = 1;
1553 if (isset($subjectToken['contact'])) {
1554 foreach ($subjectToken['contact'] as $key => $value) {
1555 if (!isset($returnProperties[$value])) {
1556 $returnProperties[$value] = 1;
1561 // get token details for contacts, call only if tokens are used
1563 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1564 list($details) = CRM_Utils_Token
::getTokenDetails(
1569 'CRM_Activity_BAO_Activity'
1575 CRM_Utils_Hook
::tokens($tokens);
1576 $categories = array_keys($tokens);
1578 $escapeSmarty = FALSE;
1579 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1580 $smarty = CRM_Core_Smarty
::singleton();
1581 $escapeSmarty = TRUE;
1584 $contributionDetails = array();
1585 if (!empty($contributionIds)) {
1586 $contributionDetails = CRM_Contribute_BAO_Contribution
::replaceContributionTokens(
1597 $sent = $notSent = array();
1598 foreach ($contactDetails as $values) {
1599 $contactId = $values['contact_id'];
1600 $emailAddress = $values['email'];
1602 if (!empty($contributionDetails)) {
1603 $subject = $contributionDetails[$contactId]['subject'];
1604 $text = $contributionDetails[$contactId]['text'];
1605 $html = $contributionDetails[$contactId]['html'];
1608 if (!empty($details) && is_array($details["{$contactId}"])) {
1609 // unset email from details since it always returns primary email address
1610 unset($details["{$contactId}"]['email']);
1611 unset($details["{$contactId}"]['email_id']);
1612 $values = array_merge($values, $details["{$contactId}"]);
1615 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1616 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1619 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1620 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1621 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1627 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1628 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1629 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1635 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1636 // also add the contact tokens to the template
1637 $smarty->assign_by_ref('contact', $values);
1639 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1640 $tokenText = $smarty->fetch("string:$tokenText");
1641 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1645 if (self
::sendMessage(
1663 return array($sent, $activity->id
);
1667 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1669 * @param array $contactDetails
1670 * @param array $activityParams
1671 * @param array $smsProviderParams
1672 * @param array $contactIds
1673 * @param int $sourceContactId This is the source contact Id
1675 * @return array(bool $sent, int $activityId, int $success)
1676 * @throws CRM_Core_Exception
1678 public static function sendSMS(
1679 &$contactDetails = NULL,
1681 &$smsProviderParams = array(),
1682 &$contactIds = NULL,
1683 $sourceContactId = NULL
1685 if (!CRM_Core_Permission
::check('send SMS')) {
1686 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1689 if (!isset($contactDetails) && !isset($contactIds)) {
1690 Throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1692 // Populate $contactDetails and $contactIds if only one is set
1693 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1694 foreach ($contactIds as $id) {
1696 $contactDetails[] = civicrm_api3('Contact', 'getsingle', array('contact_id' => $id));
1698 catch (Exception
$e) {
1699 // Contact Id doesn't exist
1703 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1704 foreach ($contactDetails as $contact) {
1705 $contactIds[] = $contact['contact_id'];
1709 // Get logged in User Id
1710 if (empty($sourceContactId)) {
1711 $sourceContactId = CRM_Core_Session
::getLoggedInContactID();
1714 $text = &$activityParams['sms_text_message'];
1716 // Create the meta level record first ( sms activity )
1717 $activityParams = array(
1718 'source_contact_id' => $sourceContactId,
1719 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
1720 'activity_date_time' => date('YmdHis'),
1721 'subject' => $activityParams['activity_subject'],
1723 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1725 $activity = self
::create($activityParams);
1726 $activityID = $activity->id
;
1729 // token replacement of addressee/email/postal greetings
1730 // get the tokens added in subject and message
1731 $messageToken = CRM_Utils_Token
::getTokens($text);
1732 $returnProperties = array();
1733 if (isset($messageToken['contact'])) {
1734 foreach ($messageToken['contact'] as $key => $value) {
1735 $returnProperties[$value] = 1;
1740 CRM_Utils_Hook
::tokens($tokens);
1741 $categories = array_keys($tokens);
1742 // get token details for contacts, call only if tokens are used
1743 $tokenDetails = array();
1744 if (!empty($returnProperties) ||
!empty($tokens)) {
1745 list($tokenDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
1749 'CRM_Activity_BAO_Activity'
1755 foreach ($contactDetails as $contact) {
1756 $contactId = $contact['contact_id'];
1759 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
1760 // unset phone from details since it always returns primary number
1761 unset($tokenDetails["{$contactId}"]['phone']);
1762 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1763 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
1765 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1766 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1768 // Only send if the phone is of type mobile
1769 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1770 $smsProviderParams['To'] = $contact['phone'];
1773 $smsProviderParams['To'] = '';
1776 $sendResult = self
::sendSMSMessage(
1784 if (PEAR
::isError($sendResult)) {
1785 // Collect all of the PEAR_Error objects
1786 $errMsgs[] = $sendResult;
1793 // If at least one message was sent and no errors
1794 // were generated then return a boolean value of TRUE.
1795 // Otherwise, return FALSE (no messages sent) or
1796 // and array of 1 or more PEAR_Error objects.
1798 if ($success > 0 && count($errMsgs) == 0) {
1801 elseif (count($errMsgs) > 0) {
1805 return array($sent, $activity->id
, $success);
1809 * Send the sms message to a specific contact.
1812 * The contact id of the recipient.
1814 * @param array $smsProviderParams
1815 * The params used for sending sms.
1816 * @param int $activityID
1817 * The activity ID that tracks the message.
1818 * @param int $sourceContactID
1820 * @return bool|PEAR_Error
1821 * true on success or PEAR_Error object
1823 public static function sendSMSMessage(
1826 $smsProviderParams = array(),
1828 $sourceContactID = NULL
1831 $toPhoneNumber = NULL;
1833 if ($smsProviderParams['To']) {
1834 // If phone number is specified use it
1835 $toPhoneNumber = trim($smsProviderParams['To']);
1838 // No phone number specified, so find a suitable one for the contact
1839 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1840 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1841 // To get primary mobile phonenumber, if not get the first mobile phonenumber
1842 if (!empty($toPhoneNumbers)) {
1843 $toPhoneNumberDetails = reset($toPhoneNumbers);
1844 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
1845 // Contact allows to send sms
1850 // make sure both phone are valid
1851 // and that the recipient wants to receive sms
1852 if (empty($toPhoneNumber) or $doNotSms) {
1853 return PEAR
::raiseError(
1854 'Recipient phone number is invalid or recipient does not want to receive SMS',
1860 $recipient = $smsProviderParams['To'];
1861 $smsProviderParams['contact_id'] = $toID;
1862 $smsProviderParams['parent_activity_id'] = $activityID;
1864 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsProviderParams['provider_id']));
1865 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
1866 if (PEAR
::isError($sendResult)) {
1870 // add activity target record for every sms that is sent
1871 $targetID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
1872 $activityTargetParams = array(
1873 'activity_id' => $activityID,
1874 'contact_id' => $toID,
1875 'record_type_id' => $targetID,
1877 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1883 * Send the message to a specific contact.
1885 * @param string $from
1886 * The name and email of the sender.
1887 * @param int $fromID
1889 * The contact id of the recipient.
1890 * @param string $subject
1891 * The subject of the message.
1892 * @param $text_message
1893 * @param $html_message
1894 * @param string $emailAddress
1895 * Use this 'to' email address instead of the default Primary address.
1896 * @param int $activityID
1897 * The activity ID that tracks the message.
1898 * @param null $attachments
1903 * TRUE if successful else FALSE.
1905 public static function sendMessage(
1914 $attachments = NULL,
1918 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1919 if ($emailAddress) {
1920 $toEmail = trim($emailAddress);
1923 // make sure both email addresses are valid
1924 // and that the recipient wants to receive email
1925 if (empty($toEmail) or $toDoNotEmail) {
1928 if (!trim($toDisplayName)) {
1929 $toDisplayName = $toEmail;
1932 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1933 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1935 // create the params array
1936 $mailParams = array(
1937 'groupName' => 'Activity Email Sender',
1939 'toName' => $toDisplayName,
1940 'toEmail' => $toEmail,
1941 'subject' => $subject,
1944 'text' => $text_message,
1945 'html' => $html_message,
1946 'attachments' => $attachments,
1949 if (!CRM_Utils_Mail
::send($mailParams)) {
1953 // add activity target record for every mail that is send
1954 $activityTargetParams = array(
1955 'activity_id' => $activityID,
1956 'contact_id' => $toID,
1957 'record_type_id' => $targetID,
1959 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1964 * Combine all the importable fields from the lower levels object.
1966 * The ordering is important, since currently we do not have a weight
1967 * scheme. Adding weight is super important and should be done in the
1968 * next week or so, before this can be called complete.
1970 * @param bool $status
1973 * array of importable Fields
1975 public static function &importableFields($status = FALSE) {
1976 if (!self
::$_importableFields) {
1977 if (!self
::$_importableFields) {
1978 self
::$_importableFields = array();
1981 $fields = array('' => array('title' => ts('- do not import -')));
1984 $fields = array('' => array('title' => ts('- Activity Fields -')));
1987 $tmpFields = CRM_Activity_DAO_Activity
::import();
1988 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1990 // Using new Dedupe rule.
1991 $ruleParams = array(
1992 'contact_type' => 'Individual',
1993 'used' => 'Unsupervised',
1995 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1997 $tmpConatctField = array();
1998 if (is_array($fieldsArray)) {
1999 foreach ($fieldsArray as $value) {
2000 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2005 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
2006 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
2007 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
2010 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
2011 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
2012 $fields = array_merge($fields, $tmpConatctField);
2013 $fields = array_merge($fields, $tmpFields);
2014 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2015 self
::$_importableFields = $fields;
2017 return self
::$_importableFields;
2021 * @deprecated - use the api instead.
2023 * Get the Activities of a target contact.
2025 * @param int $contactId
2026 * Id of the contact whose activities need to find.
2029 * array of activity fields
2031 public static function getContactActivity($contactId) {
2032 // @todo remove this function entirely.
2033 $activities = array();
2034 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2035 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2036 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2037 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2039 // First look for activities where contactId is one of the targets
2041 SELECT activity_id, record_type_id
2042 FROM civicrm_activity_contact
2043 WHERE contact_id = $contactId
2045 $dao = CRM_Core_DAO
::executeQuery($query);
2046 while ($dao->fetch()) {
2047 if ($dao->record_type_id
== $targetID) {
2048 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
2050 elseif ($dao->record_type_id
== $assigneeID) {
2051 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
2054 // do source stuff here
2055 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
2059 $activityIds = array_keys($activities);
2060 if (count($activityIds) < 1) {
2064 $activityIds = implode(',', $activityIds);
2066 SELECT activity.id as activity_id,
2068 subject, location, activity_date_time, details, status_id
2069 FROM civicrm_activity activity
2070 WHERE activity.id IN ($activityIds)";
2072 $dao = CRM_Core_DAO
::executeQuery($query);
2074 while ($dao->fetch()) {
2075 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
2076 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
2077 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
2078 $activities[$dao->activity_id
]['location'] = $dao->location
;
2079 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
2080 $activities[$dao->activity_id
]['details'] = $dao->details
;
2081 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
2082 $activities[$dao->activity_id
]['activity_name'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id
);
2083 $activities[$dao->activity_id
]['status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id
);
2085 // set to null if not set
2086 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
2087 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
2094 * Add activity for Membership/Event/Contribution.
2096 * @param object $activity
2097 * (reference) particular component object.
2098 * @param string $activityType
2099 * For Membership Signup or Renewal.
2100 * @param int $targetContactID
2101 * @param array $params
2102 * Activity params to override.
2106 public static function addActivity(
2108 $activityType = 'Membership Signup',
2109 $targetContactID = NULL,
2112 $date = date('YmdHis');
2113 if ($activity->__table
== 'civicrm_membership') {
2114 $component = 'Membership';
2116 elseif ($activity->__table
== 'civicrm_participant') {
2117 if ($activityType != 'Email') {
2118 $activityType = 'Event Registration';
2120 $component = 'Event';
2122 elseif ($activity->__table
== 'civicrm_contribution') {
2123 // create activity record only for Completed Contributions
2124 $contributionCompletedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
2125 if ($activity->contribution_status_id
!= $contributionCompletedStatusId) {
2128 $activityType = $component = 'Contribution';
2130 // retrieve existing activity based on source_record_id and activity_type
2131 if (empty($params['id'])) {
2132 $params['id'] = CRM_Utils_Array
::value('id', civicrm_api3('Activity', 'Get', array(
2133 'source_record_id' => $activity->id
,
2134 'activity_type_id' => $activityType,
2137 if (!empty($params['id'])) {
2138 // CRM-13237 : if activity record found, update it with campaign id of contribution
2139 $params['campaign_id'] = $activity->campaign_id
;
2142 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
2145 $activityParams = array(
2146 'source_contact_id' => $activity->contact_id
,
2147 'source_record_id' => $activity->id
,
2148 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
2149 'activity_date_time' => $date,
2150 'is_test' => $activity->is_test
,
2151 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
2152 'skipRecentView' => TRUE,
2153 'campaign_id' => $activity->campaign_id
,
2155 $activityParams = array_merge($activityParams, $params);
2157 if (empty($activityParams['subject'])) {
2158 $activityParams['subject'] = self
::getActivitySubject($activity);
2161 if (!empty($activity->activity_id
)) {
2162 $activityParams['id'] = $activity->activity_id
;
2164 // create activity with target contacts
2165 $id = CRM_Core_Session
::getLoggedInContactID();
2167 $activityParams['source_contact_id'] = $id;
2168 $activityParams['target_contact_id'][] = $activity->contact_id
;
2172 if (property_exists($activity, 'details')) {
2173 $activityParams['details'] = $activity->details
;
2176 if ($targetContactID) {
2177 $activityParams['target_contact_id'][] = $targetContactID;
2179 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
2180 // deal with any exceptions.
2181 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
2182 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
2188 * Get activity subject on basis of component object.
2190 * @param object $entityObj
2191 * particular component object.
2195 public static function getActivitySubject($entityObj) {
2196 switch ($entityObj->__table
) {
2197 case 'civicrm_membership':
2198 $membershipType = CRM_Member_PseudoConstant
::membershipType($entityObj->membership_type_id
);
2199 $subject = $membershipType ?
$membershipType : ts('Membership');
2201 if (is_array($subject)) {
2202 $subject = implode(", ", $subject);
2205 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
2206 $subject .= " - {$entityObj->source}";
2209 if ($entityObj->owner_membership_id
) {
2210 list($displayName) = CRM_Contact_BAO_Contact
::getDisplayAndImage(CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id
, 'contact_id'));
2211 $subject .= sprintf(' (by %s)', $displayName);
2214 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $entityObj->status_id
, 'label');
2217 case 'civicrm_participant':
2218 $event = CRM_Event_BAO_Event
::getEvents(1, $entityObj->event_id
, TRUE, FALSE);
2219 $roles = CRM_Event_PseudoConstant
::participantRole();
2220 $status = CRM_Event_PseudoConstant
::participantStatus();
2221 $subject = $event[$entityObj->event_id
];
2223 if (!empty($roles[$entityObj->role_id
])) {
2224 $subject .= ' - ' . $roles[$entityObj->role_id
];
2226 if (!empty($status[$entityObj->status_id
])) {
2227 $subject .= ' - ' . $status[$entityObj->status_id
];
2232 case 'civicrm_contribution':
2233 $subject = CRM_Utils_Money
::format($entityObj->total_amount
, $entityObj->currency
);
2234 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
2235 $subject .= " - {$entityObj->source}";
2238 // Amount and source could exceed max length of subject column.
2239 return CRM_Utils_String
::ellipsify($subject, 255);
2244 * Get Parent activity for currently viewed activity.
2246 * @param int $activityId
2247 * Current activity id.
2250 * Id of parent activity otherwise false.
2252 public static function getParentActivity($activityId) {
2253 static $parentActivities = array();
2255 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
2257 if (!array_key_exists($activityId, $parentActivities)) {
2258 $parentActivities[$activityId] = array();
2260 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2265 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
2268 return $parentActivities[$activityId];
2272 * Get total count of prior revision of currently viewed activity.
2274 * @param $activityID
2275 * Current activity id.
2278 * $params count of prior activities otherwise false.
2280 public static function getPriorCount($activityID) {
2281 static $priorCounts = array();
2283 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2285 if (!array_key_exists($activityID, $priorCounts)) {
2286 $priorCounts[$activityID] = array();
2287 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2294 SELECT count( id ) AS cnt
2295 FROM civicrm_activity
2296 WHERE ( id = {$originalID} OR original_id = {$originalID} )
2297 AND is_current_revision = 0
2298 AND id < {$activityID}
2300 $params = array(1 => array($originalID, 'Integer'));
2301 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
2303 $priorCounts[$activityID] = $count ?
$count : 0;
2306 return $priorCounts[$activityID];
2310 * Get all prior activities of currently viewed activity.
2312 * @param $activityID
2313 * Current activity id.
2314 * @param bool $onlyPriorRevisions
2317 * prior activities info.
2319 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
2320 static $priorActivities = array();
2322 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2323 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2325 if (!array_key_exists($index, $priorActivities)) {
2326 $priorActivities[$index] = array();
2328 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2333 $originalID = $activityID;
2337 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2338 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2339 WHERE (ca.id = %1 OR ca.original_id = %1)
2340 AND cl.entity_table = 'civicrm_activity'
2341 AND cl.entity_id = ca.id
2342 AND cl.modified_id = c.id
2344 if ($onlyPriorRevisions) {
2345 $query .= " AND ca.id < {$activityID}";
2347 $query .= " ORDER BY ca.id DESC";
2349 $params = array(1 => array($originalID, 'Integer'));
2350 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2352 while ($dao->fetch()) {
2353 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
2354 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
2355 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
2360 return $priorActivities[$index];
2364 * Find the latest revision of a given activity.
2366 * @param int $activityID
2367 * Prior activity id.
2370 * current activity id.
2372 public static function getLatestActivityId($activityID) {
2373 static $latestActivityIds = array();
2375 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2377 if (!array_key_exists($activityID, $latestActivityIds)) {
2378 $latestActivityIds[$activityID] = array();
2380 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2385 $activityID = $originalID;
2387 $params = array(1 => array($activityID, 'Integer'));
2388 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2390 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2393 return $latestActivityIds[$activityID];
2397 * Create a follow up a given activity.
2399 * @param int $activityId
2400 * activity id of parent activity.
2401 * @param array $params
2403 * @return CRM_Activity_BAO_Activity|null|object
2405 public static function createFollowupActivity($activityId, $params) {
2410 $followupParams = array();
2411 $followupParams['parent_id'] = $activityId;
2412 $followupParams['source_contact_id'] = CRM_Core_Session
::getLoggedInContactID();
2413 $followupParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2415 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2416 // Get Subject of Follow-up Activiity, CRM-4491
2417 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2418 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2420 // Create target contact for followup.
2421 if (!empty($params['target_contact_id'])) {
2422 $followupParams['target_contact_id'] = $params['target_contact_id'];
2425 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2426 $params['followup_date_time']
2428 $followupActivity = self
::create($followupParams);
2430 return $followupActivity;
2434 * Get Activity specific File according activity type Id.
2436 * @param int $activityTypeId
2438 * @param string $crmDir
2440 * @return string|bool
2441 * if file exists returns $activityTypeFile activity filename otherwise false.
2443 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2444 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2446 if ($activityTypes[$activityTypeId]['name']) {
2447 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2453 global $civicrm_root;
2454 $config = CRM_Core_Config
::singleton();
2455 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2456 if (empty($config->customPHPPathDir
)) {
2459 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2464 return $activityTypeFile;
2468 * Restore the activity.
2470 * @param array $params
2472 * @return CRM_Activity_DAO_Activity
2474 public static function restoreActivity(&$params) {
2475 $activity = new CRM_Activity_DAO_Activity();
2476 $activity->copyValues($params);
2478 $activity->is_deleted
= 0;
2479 $result = $activity->save();
2485 * Return list of activity statuses of a given type.
2487 * Note: activity status options use the "grouping" field to distinguish status types.
2488 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2494 public static function getStatusesByType($type) {
2495 if (!isset(Civi
::$statics[__CLASS__
][__FUNCTION__
])) {
2496 $statuses = civicrm_api3('OptionValue', 'get', array(
2497 'option_group_id' => 'activity_status',
2498 'return' => array('value', 'name', 'filter'),
2499 'options' => array('limit' => 0),
2501 Civi
::$statics[__CLASS__
][__FUNCTION__
] = $statuses['values'];
2504 foreach (Civi
::$statics[__CLASS__
][__FUNCTION__
] as $status) {
2505 if ($status['filter'] == $type) {
2506 $ret[$status['value']] = $status['name'];
2513 * Check if activity is overdue.
2515 * @param array $activity
2519 public static function isOverdue($activity) {
2520 return array_key_exists($activity['status_id'], self
::getStatusesByType(self
::INCOMPLETE
)) && CRM_Utils_Date
::overdue($activity['activity_date_time']);
2524 * Get the exportable fields for Activities.
2526 * @param string $name
2527 * If it is called by case $name = Case else $name = Activity.
2530 * array of exportable Fields
2532 public static function &exportableFields($name = 'Activity') {
2533 if (!isset(self
::$_exportableFields[$name])) {
2534 self
::$_exportableFields[$name] = array();
2536 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2537 // my case hence we have defined fields as case_*
2538 if ($name == 'Activity') {
2539 $exportableFields = CRM_Activity_DAO_Activity
::export();
2540 $exportableFields['source_contact_id'] = [
2541 'title' => ts('Source Contact ID'),
2542 'type' => CRM_Utils_Type
::T_INT
,
2544 $exportableFields['source_contact'] = array(
2545 'title' => ts('Source Contact'),
2546 'type' => CRM_Utils_Type
::T_STRING
,
2549 $Activityfields = array(
2550 'activity_type' => array(
2551 'title' => ts('Activity Type'),
2552 'name' => 'activity_type',
2553 'type' => CRM_Utils_Type
::T_STRING
,
2554 'searchByLabel' => TRUE,
2556 'activity_status' => array(
2557 'title' => ts('Activity Status'),
2558 'name' => 'activity_status',
2559 'type' => CRM_Utils_Type
::T_STRING
,
2560 'searchByLabel' => TRUE,
2562 'activity_priority' => array(
2563 'title' => ts('Activity Priority'),
2564 'name' => 'activity_priority',
2565 'type' => CRM_Utils_Type
::T_STRING
,
2566 'searchByLabel' => TRUE,
2569 $fields = array_merge($Activityfields, $exportableFields);
2572 // Set title to activity fields.
2574 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2575 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2576 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2577 'case_scheduled_activity_date' => array(
2578 'title' => ts('Activity Scheduled Date'),
2579 'type' => CRM_Utils_Type
::T_DATE
,
2581 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2582 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2583 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2584 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2585 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2586 'case_activity_is_auto' => array(
2587 'title' => ts('Activity Auto-generated?'),
2588 'type' => CRM_Utils_Type
::T_BOOLEAN
,
2593 // add custom data for case activities
2594 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2596 self
::$_exportableFields[$name] = $fields;
2598 return self
::$_exportableFields[$name];
2602 * Get the allowed profile fields for Activities.
2605 * array of activity profile Fields
2607 public static function getProfileFields() {
2608 $exportableFields = self
::exportableFields('Activity');
2609 $skipFields = array(
2612 'source_contact_id',
2614 'activity_campaign',
2616 'is_current_revision',
2617 'activity_is_deleted',
2619 $config = CRM_Core_Config
::singleton();
2620 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2621 $skipFields[] = 'activity_engagement_level';
2624 foreach ($skipFields as $field) {
2625 if (isset($exportableFields[$field])) {
2626 unset($exportableFields[$field]);
2630 // hack to use 'activity_type_id' instead of 'activity_type'
2631 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2632 unset($exportableFields['activity_status']);
2634 return $exportableFields;
2638 * This function deletes the activity record related to contact record.
2640 * This is conditional on there being no target and assignee record
2641 * with other contacts.
2643 * @param int $contactId
2648 public static function cleanupActivity($contactId) {
2653 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2654 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2656 $transaction = new CRM_Core_Transaction();
2658 // delete activity if there is no record in civicrm_activity_contact
2659 // pointing to any other contact record
2660 $activityContact = new CRM_Activity_DAO_ActivityContact();
2661 $activityContact->contact_id
= $contactId;
2662 $activityContact->record_type_id
= $sourceID;
2663 $activityContact->find();
2665 while ($activityContact->fetch()) {
2666 // delete activity_contact record for the deleted contact
2667 $activityContact->delete();
2669 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2670 $activityContactOther->activity_id
= $activityContact->activity_id
;
2672 // delete activity only if no other contacts connected
2673 if (!$activityContactOther->find(TRUE)) {
2674 $activityParams = array('id' => $activityContact->activity_id
);
2675 $result = self
::deleteActivity($activityParams);
2678 $activityContactOther->free();
2681 $activityContact->free();
2682 $transaction->commit();
2688 * Does user has sufficient permission for view/edit activity record.
2690 * @param int $activityId
2691 * Activity record id.
2692 * @param int $action
2697 public static function checkPermission($activityId, $action) {
2700 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2705 $activity = new CRM_Activity_DAO_Activity();
2706 $activity->id
= $activityId;
2707 if (!$activity->find(TRUE)) {
2711 // Component related permissions.
2712 $compPermissions = array(
2713 'CiviCase' => array(
2714 'administer CiviCase',
2715 'access my cases and activities',
2716 'access all cases and activities',
2718 'CiviMail' => array('access CiviMail'),
2719 'CiviEvent' => array('access CiviEvent'),
2720 'CiviGrant' => array('access CiviGrant'),
2721 'CiviPledge' => array('access CiviPledge'),
2722 'CiviMember' => array('access CiviMember'),
2723 'CiviReport' => array('access CiviReport'),
2724 'CiviContribute' => array('access CiviContribute'),
2725 'CiviCampaign' => array('administer CiviCampaign'),
2728 // Return early when it is case activity.
2729 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2730 // Check for civicase related permission.
2731 if ($isCaseActivity) {
2733 foreach ($compPermissions['CiviCase'] as $per) {
2734 if (CRM_Core_Permission
::check($per)) {
2740 // Check for case specific permissions.
2743 if ($action == CRM_Core_Action
::UPDATE
) {
2746 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2748 $activity->activity_type_id
2755 // First check the component permission.
2758 FROM civicrm_option_value val
2759 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2760 WHERE val.value = %2";
2762 1 => array('activity_type', 'String'),
2763 2 => array($activity->activity_type_id
, 'Integer'),
2765 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2768 $componentName = CRM_Core_Component
::getComponentName($componentId);
2769 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2771 // Here we are interesting in any single permission.
2772 if (is_array($compPermission)) {
2773 foreach ($compPermission as $per) {
2774 if (CRM_Core_Permission
::check($per)) {
2782 // Check for this permission related to contact.
2783 $permission = CRM_Core_Permission
::VIEW
;
2784 if ($action == CRM_Core_Action
::UPDATE
) {
2785 $permission = CRM_Core_Permission
::EDIT
;
2788 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2789 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2790 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2791 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2793 // Check for source contact.
2794 if (!$componentId ||
$allow) {
2795 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2796 // Account for possibility of activity not having a source contact (as it may have been deleted).
2797 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission) : TRUE;
2800 // Check for target and assignee contacts.
2802 // First check for supper permission.
2803 $supPermission = 'view all contacts';
2804 if ($action == CRM_Core_Action
::UPDATE
) {
2805 $supPermission = 'edit all contacts';
2807 $allow = CRM_Core_Permission
::check($supPermission);
2809 // User might have sufficient permission, through acls.
2812 // Get the target contacts.
2813 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2814 foreach ($targetContacts as $cnt => $contactId) {
2815 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2821 // Get the assignee contacts.
2823 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2824 foreach ($assigneeContacts as $cnt => $contactId) {
2825 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2838 * Wrapper for ajax activity selector.
2840 * @param array $params
2841 * Associated array for params record id.
2844 * Associated array of contact activities
2846 public static function getContactActivitySelector(&$params) {
2847 // Format the params.
2848 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2849 $params['rowCount'] = $params['rp'];
2850 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2851 $params['caseId'] = NULL;
2852 $context = CRM_Utils_Array
::value('context', $params);
2853 $showContactOverlay = !CRM_Utils_String
::startsWith($context, "dashlet");
2854 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2855 'option_group_id' => "activity_type",
2856 'options' => array('limit' => 0),
2858 $activityIcons = array();
2859 foreach ($activityTypeInfo['values'] as $type) {
2860 if (!empty($type['icon'])) {
2861 $activityIcons[$type['value']] = $type['icon'];
2865 // Get contact activities.
2866 $activities = CRM_Activity_BAO_Activity
::deprecatedGetActivities($params);
2869 $params['total'] = CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($params);
2871 // Format params and add links.
2872 $contactActivities = array();
2874 if (!empty($activities)) {
2875 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2877 // Check logged in user for permission.
2878 $page = new CRM_Core_Page();
2879 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2880 $permissions = array($page->_permission
);
2881 if (CRM_Core_Permission
::check('delete activities')) {
2882 $permissions[] = CRM_Core_Permission
::DELETE
;
2885 $mask = CRM_Core_Action
::mask($permissions);
2887 foreach ($activities as $activityId => $values) {
2888 $activity = array();
2889 $activity['DT_RowId'] = $activityId;
2890 // Add class to this row if overdue.
2891 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2892 if (self
::isOverdue($values)) {
2893 $activity['DT_RowClass'] .= ' status-overdue';
2896 $activity['DT_RowClass'] .= ' status-ontime';
2899 $activity['DT_RowAttr'] = array();
2900 $activity['DT_RowAttr']['data-entity'] = 'activity';
2901 $activity['DT_RowAttr']['data-id'] = $activityId;
2903 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ?
'<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2904 $activity['subject'] = $values['subject'];
2906 $activity['source_contact_name'] = '';
2907 if ($params['contact_id'] == $values['source_contact_id']) {
2908 $activity['source_contact_name'] = $values['source_contact_name'];
2910 elseif ($values['source_contact_id']) {
2912 if ($showContactOverlay) {
2913 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2914 CRM_Contact_BAO_Contact
::getContactType($values['source_contact_id']),
2916 $values['source_contact_id']);
2918 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System
::href($values['source_contact_name'],
2919 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2922 $activity['source_contact_name'] = '<em>n/a</em>';
2925 $activity['target_contact_name'] = '';
2926 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2927 $activity['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2928 'civicrm/mailing/report/event',
2929 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2931 elseif (!empty($values['recipients'])) {
2932 $activity['target_contact_name'] = $values['recipients'];
2934 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2935 $activity['target_contact_name'] = '';
2936 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2937 $targetTypeImage = "";
2938 $targetLink = CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2939 if ($showContactOverlay) {
2940 $targetTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2941 CRM_Contact_BAO_Contact
::getContactType($tcID),
2944 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2947 $activity['target_contact_name'] .= $targetLink;
2951 if ($extraCount = $values['target_contact_counter'] - 1) {
2952 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2954 if ($showContactOverlay) {
2955 $activity['target_contact_name'] .= "</div> ";
2958 elseif (!$values['target_contact_name']) {
2959 $activity['target_contact_name'] = '<em>n/a</em>';
2962 $activity['assignee_contact_name'] = '';
2963 if (empty($values['assignee_contact_name'])) {
2964 $activity['assignee_contact_name'] = '<em>n/a</em>';
2966 elseif (!empty($values['assignee_contact_name'])) {
2968 $activity['assignee_contact_name'] = '';
2969 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2970 if ($acID && $count < 5) {
2971 $assigneeTypeImage = "";
2972 $assigneeLink = CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2973 if ($showContactOverlay) {
2974 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2975 CRM_Contact_BAO_Contact
::getContactType($acID),
2978 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2981 $activity['assignee_contact_name'] .= $assigneeLink;
2986 $activity['assignee_contact_name'] .= "; ";
2988 if ($showContactOverlay) {
2989 $activity['assignee_contact_name'] .= "</div> ";
2993 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
3000 $activity['activity_date_time'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
3001 $activity['status_id'] = $activityStatus[$values['status_id']];
3004 $activity['links'] = '';
3005 $accessMailingReport = FALSE;
3006 if (!empty($values['mailingId'])) {
3007 $accessMailingReport = TRUE;
3010 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
3011 CRM_Utils_Array
::value('activity_type_id', $values),
3012 CRM_Utils_Array
::value('source_record_id', $values),
3013 $accessMailingReport,
3014 CRM_Utils_Array
::value('activity_id', $values)
3017 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
3019 $activity['links'] = CRM_Core_Action
::formLink($actionLinks,
3022 'id' => $values['activity_id'],
3023 'cid' => $params['contact_id'],
3025 'caseid' => CRM_Utils_Array
::value('case_id', $values),
3031 $values['activity_id']
3034 if ($values['is_recurring_activity']) {
3035 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($values['activity_id'], 'civicrm_activity');
3038 array_push($contactActivities, $activity);
3042 $activitiesDT = array();
3043 $activitiesDT['data'] = $contactActivities;
3044 $activitiesDT['recordsTotal'] = $params['total'];
3045 $activitiesDT['recordsFiltered'] = $params['total'];
3047 return $activitiesDT;
3051 * Copy custom fields and attachments from an existing activity to another.
3053 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
3055 * @param array $params
3057 public static function copyExtendedActivityData($params) {
3058 // attach custom data to the new activity
3059 $customParams = $htmlType = array();
3060 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
3062 if (!empty($customValues)) {
3063 $fieldIds = implode(', ', array_keys($customValues));
3064 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
3065 $result = CRM_Core_DAO
::executeQuery($sql);
3067 while ($result->fetch()) {
3068 $htmlType[] = $result->id
;
3071 foreach ($customValues as $key => $value) {
3072 if ($value !== NULL) {
3074 if (in_array($key, $htmlType)) {
3075 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
3076 $customParams["custom_{$key}_-1"] = array(
3077 'name' => $fileValues[0],
3078 'path' => $fileValues[1],
3082 $customParams["custom_{$key}_-1"] = $value;
3086 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_activity',
3087 $params['mainActivityId'], 'Activity'
3091 // copy activity attachments ( if any )
3092 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
3096 * Get activity contact.
3098 * @param int $activityId
3099 * @param int $recordTypeID
3100 * @param string $column
3104 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
3105 $activityContact = new CRM_Activity_BAO_ActivityContact();
3106 $activityContact->activity_id
= $activityId;
3107 if ($recordTypeID) {
3108 $activityContact->record_type_id
= $recordTypeID;
3110 if ($activityContact->find(TRUE)) {
3111 return $activityContact->$column;
3117 * Get source contact id.
3119 * @param int $activityId
3123 public static function getSourceContactID($activityId) {
3124 static $sourceID = NULL;
3126 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3127 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
3130 return self
::getActivityContact($activityId, $sourceID);
3136 * @todo Document what this is for.
3138 * @param array $params
3140 public function setApiFilter(&$params) {
3141 if (!empty($params['target_contact_id'])) {
3143 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3144 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3145 $obj = new CRM_Activity_BAO_ActivityContact();
3146 $params['return.target_contact_id'] = 1;
3147 $this->joinAdd($obj, 'LEFT');
3148 $this->selectAdd('civicrm_activity.*');
3149 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
3154 * Send activity as attachment.
3156 * @param object $activity
3157 * @param array $mailToContacts
3158 * @param array $params
3162 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
3163 if (!CRM_Utils_Array
::crmIsEmptyArray($mailToContacts)) {
3164 $clientID = CRM_Utils_Array
::value('client_id', $params);
3165 $caseID = CRM_Utils_Array
::value('case_id', $params);
3167 $ics = new CRM_Activity_BAO_ICalendar($activity);
3168 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity', $activity->id
);
3169 $ics->addAttachment($attachments, $mailToContacts);
3171 $result = CRM_Case_BAO_Case
::sendActivityCopy($clientID, $activity->id
, $mailToContacts, $attachments, $caseID);