3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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
676 * Relevant data object values of open activities
677 * @throws \CiviCRM_API3_Exception
679 public static function getActivities($params) {
680 $activities = array();
682 // Activity.Get API params
683 $activityParams = self
::getActivityParamsForDashboardFunctions($params);
685 if (!empty($params['rowCount']) &&
686 $params['rowCount'] > 0
688 $activityParams['options']['limit'] = $params['rowCount'];
691 if (!empty($params['sort'])) {
692 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
693 $order = $params['sort']->orderBy();
695 elseif (trim($params['sort'])) {
696 $order = CRM_Utils_Type
::escape($params['sort'], 'String');
700 $activityParams['options']['sort'] = empty($order) ?
"activity_date_time DESC" : str_replace('activity_type ', 'activity_type_id.label ', $order);
702 $activityParams['return'] = [
703 'activity_date_time',
706 'source_contact_name',
707 'assignee_contact_id',
709 'assignee_contact_name',
717 foreach (['case_id' => 'CiviCase', 'campaign_id' => 'CiviCampaign'] as $attr => $component) {
718 if (in_array($component, self
::activityComponents())) {
719 $activityParams['return'][] = $attr;
722 $result = civicrm_api3('Activity', 'Get', $activityParams);
724 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
725 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
727 // CRM-3553, need to check user has access to target groups.
728 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
729 $accessCiviMail = ((CRM_Core_Permission
::check('access CiviMail')) ||
730 (CRM_Mailing_Info
::workflowEnabled() && CRM_Core_Permission
::check('create mailings'))
733 $mappingParams = array(
734 'id' => 'activity_id',
735 'source_record_id' => 'source_record_id',
736 'activity_type_id' => 'activity_type_id',
737 'activity_date_time' => 'activity_date_time',
738 'status_id' => 'status_id',
739 'subject' => 'subject',
740 'campaign_id' => 'campaign_id',
741 'assignee_contact_name' => 'assignee_contact_name',
742 'source_contact_id' => 'source_contact_id',
743 'source_contact_name' => 'source_contact_name',
744 'case_id' => 'case_id',
747 foreach ($result['values'] as $id => $activity) {
749 $activities[$id] = array();
751 $isBulkActivity = (!$bulkActivityTypeID ||
($bulkActivityTypeID === $activity['activity_type_id']));
752 $activities[$id]['target_contact_counter'] = count($activity['target_contact_id']);
753 if ($activities[$id]['target_contact_counter']) {
755 $activities[$id]['target_contact_name'][$activity['target_contact_id'][0]] = civicrm_api3('Contact', 'getvalue', ['id' => $activity['target_contact_id'][0], 'return' => 'sort_name']);
757 catch (CiviCRM_API3_Exception
$e) {
758 // Really they should have names but a fatal here feels wrong.
759 $activities[$id]['target_contact_name'] = '';
762 foreach ($mappingParams as $apiKey => $expectedName) {
763 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
764 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity, array());
766 if ($isBulkActivity) {
767 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
768 $activities[$id]['mailingId'] = FALSE;
769 if ($accessCiviMail &&
770 ($mailingIDs === TRUE ||
in_array($activity['source_record_id'], $mailingIDs))
772 $activities[$id]['mailingId'] = TRUE;
776 // case related fields
777 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
778 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
780 // fetch case subject for case ID found
781 if (!empty($activity['case_id'])) {
782 $activities[$id]['case_subject'] = CRM_Core_DAO
::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
786 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
787 if ($apiKey == 'activity_type_id') {
788 $activities[$id]['activity_type'] = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $activities[$id][$expectedName]);
790 elseif ($apiKey == 'campaign_id') {
791 $activities[$id]['campaign'] = CRM_Utils_Array
::value($activities[$id][$expectedName], $allCampaigns);
795 // if deleted, wrap in <del>
796 if (!empty($activity['source_contact_id']) &&
797 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
799 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
801 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getParentFor($id, 'civicrm_activity');
808 * Filter the activity types to only return the ones we actually asked for
809 * Uses params['activity_type_id'] and params['activity_type_exclude_id']
812 * @return array|null (Use in Activity.get API activity_type_id)
814 public static function filterActivityTypes($params) {
815 $activityTypes = array();
817 // If no activity types are specified, get all the active ones
818 if (empty($params['activity_type_id'])) {
819 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'get');
822 // If no activity types are specified or excluded, return the list of all active ones
823 if (empty($params['activity_type_id']) && empty($params['activity_type_exclude_id'])) {
824 if (!empty($activityTypes)) {
825 return array('IN' => array_keys($activityTypes));
830 // If we have specified activity types, build a list to return, excluding the ones we don't want.
831 if (!empty($params['activity_type_id'])) {
832 if (!is_array($params['activity_type_id'])) {
833 // Turn it into array if only one specified, so we don't duplicate processing below
834 $params['activity_type_id'] = array($params['activity_type_id'] => $params['activity_type_id']);
836 foreach ($params['activity_type_id'] as $value) {
837 // Add each activity type that was specified to list
838 $value = CRM_Utils_Type
::escape($value, 'Positive');
839 $activityTypes[$value] = $value;
843 // Build the list of activity types to exclude (from $params['activity_type_exclude_id'])
844 if (!empty($params['activity_type_exclude_id'])) {
845 if (!is_array($params['activity_type_exclude_id'])) {
846 // Turn it into array if only one specified, so we don't duplicate processing below
847 $params['activity_type_exclude_id'] = array($params['activity_type_exclude_id'] => $params['activity_type_exclude_id']);
849 foreach ($params['activity_type_exclude_id'] as $value) {
850 // Remove each activity type from list if it should be excluded
851 $value = CRM_Utils_Type
::escape($value, 'Positive');
852 if (array_key_exists($value, $activityTypes)) {
853 unset($activityTypes[$value]);
858 return array('IN' => array_keys($activityTypes));
862 * Get the list Activities.
866 * @todo - use the api for this - this is working but have temporarily backed out
867 * due to performance issue to be resolved - CRM-20481.
869 * @param array $input
870 * Array of parameters.
872 * - contact_id int contact_id whose activities we want to retrieve
873 * - offset int which row to start from ?
874 * - rowCount int how many rows to fetch
875 * - sort object|array object or array describing sort order for sql query.
876 * - admin boolean if contact is admin
877 * - caseId int case ID
878 * - context string page on which selector is build
879 * - activity_type_id int|string the activitiy types we want to restrict by
882 * Relevant data object values of open activities
884 public static function deprecatedGetActivities($input) {
885 // Step 1: Get the basic activity data.
886 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
891 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
892 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
893 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
894 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
896 $config = CRM_Core_Config
::singleton();
898 $activityTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('actdetail')->getName();
900 $tableFields = array(
901 'activity_id' => 'int unsigned',
902 'activity_date_time' => 'datetime',
903 'source_record_id' => 'int unsigned',
904 'status_id' => 'int unsigned',
905 'subject' => 'varchar(255)',
906 'source_contact_name' => 'varchar(255)',
907 'activity_type_id' => 'int unsigned',
908 'activity_type' => 'varchar(128)',
909 'case_id' => 'int unsigned',
910 'case_subject' => 'varchar(255)',
911 'campaign_id' => 'int unsigned',
914 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
915 $insertValueSQL = $selectColumns = array();
916 // The activityTempTable contains the sorted rows
917 // so in order to maintain the sort order as-is we add an auto_increment
918 // field; we can sort by this later to ensure the sort order stays correct.
919 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
920 foreach ($tableFields as $name => $desc) {
921 $sql .= "$name $desc,\n";
922 $insertValueSQL[] = $name;
923 if ($name == 'source_contact_name' && CRM_Utils_SQL
::supportsFullGroupBy()) {
924 $selectColumns[] = "ANY_VALUE(tbl.$name)";
927 $selectColumns[] = "tbl.$name";
931 // add unique key on activity_id just to be sure
932 // this cannot be primary key because we need that for the auto_increment
933 // fixed_sort_order field
935 UNIQUE KEY ( activity_id )
936 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
939 CRM_Core_DAO
::executeQuery($sql);
941 $insertSQL = "INSERT IGNORE INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
943 $order = $limit = $groupBy = '';
944 $groupBy = " GROUP BY tbl.activity_id, tbl.activity_type, tbl.case_id, tbl.case_subject ";
946 if (!empty($input['sort'])) {
947 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
948 $orderBy = $input['sort']->orderBy();
949 if (!empty($orderBy)) {
950 $order = " ORDER BY $orderBy";
953 elseif (trim($input['sort'])) {
954 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
955 $order = " ORDER BY $sort ";
960 // context = 'activity' in Activities tab.
961 $order = " ORDER BY tbl.activity_date_time desc ";
964 if (!empty($input['rowCount']) &&
965 $input['rowCount'] > 0
967 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
970 $input['count'] = FALSE;
971 list($sqlClause, $params) = self
::deprecatedGetActivitySQLClause($input);
973 $query = sprintf("{$insertSQL} \n SELECT DISTINCT %s from ( %s ) \n as tbl ", implode(', ', $selectColumns), $sqlClause);
975 // Filter case activities - CRM-5761.
976 $components = self
::activityComponents();
977 if (!in_array('CiviCase', $components)) {
979 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
980 WHERE civicrm_case_activity.id IS NULL";
983 $query = $query . $groupBy . $order . $limit;
985 $dao = CRM_Core_DAO
::executeQuery($query, $params);
987 // step 2: Get target and assignee contacts for above activities
988 // create temp table for target contacts
989 $activityContactTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('actcontact')->getName();
990 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
991 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
992 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
993 ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
995 CRM_Core_DAO
::executeQuery($query);
997 // note that we ignore bulk email for targets, since we don't show it in selector
999 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
1000 SELECT ac.activity_id,
1005 FROM {$activityTempTable}
1006 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1007 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1008 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1009 WHERE ac.record_type_id != %1
1011 $params = array(1 => array($targetID, 'Integer'));
1012 CRM_Core_DAO
::executeQuery($query, $params);
1014 $activityFields = array("ac.activity_id", "ac.contact_id", "ac.record_type_id", "c.sort_name", "c.is_deleted");
1015 $select = CRM_Contact_BAO_Query
::appendAnyValueToSelect($activityFields, "ac.activity_id");
1017 // for each activity insert one target contact
1018 // if we load all target contacts the performance will suffer a lot for mass-activities.
1020 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
1021 {$select}, count(ac.contact_id)
1022 FROM {$activityTempTable}
1023 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
1024 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
1025 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
1026 WHERE ac.record_type_id = %1
1027 GROUP BY ac.activity_id
1030 CRM_Core_DAO
::executeQuery($query, $params);
1032 // step 3: Combine all temp tables to get final query for activity selector
1033 // sort by the original sort order, stored in fixed_sort_order
1035 SELECT {$activityTempTable}.*,
1036 {$activityContactTempTable}.contact_id,
1037 {$activityContactTempTable}.record_type_id,
1038 {$activityContactTempTable}.contact_name,
1039 {$activityContactTempTable}.is_deleted,
1040 {$activityContactTempTable}.counter,
1041 re.parent_id as is_recurring_activity
1042 FROM {$activityTempTable}
1043 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
1044 LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
1045 ORDER BY fixed_sort_order
1048 $dao = CRM_Core_DAO
::executeQuery($query);
1050 // CRM-3553, need to check user has access to target groups.
1051 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
1053 (CRM_Core_Permission
::check('access CiviMail')) ||
1054 (CRM_Mailing_Info
::workflowEnabled() &&
1055 CRM_Core_Permission
::check('create mailings'))
1058 // Get all campaigns.
1059 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
1061 while ($dao->fetch()) {
1062 $activityID = $dao->activity_id
;
1063 $values[$activityID]['activity_id'] = $dao->activity_id
;
1064 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
1065 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
1066 $values[$activityID]['activity_type'] = $dao->activity_type
;
1067 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
1068 $values[$activityID]['status_id'] = $dao->status_id
;
1069 $values[$activityID]['subject'] = $dao->subject
;
1070 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
1071 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity
;
1073 if ($dao->campaign_id
) {
1074 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
1077 if (empty($values[$activityID]['assignee_contact_name'])) {
1078 $values[$activityID]['assignee_contact_name'] = array();
1081 if (empty($values[$activityID]['target_contact_name'])) {
1082 $values[$activityID]['target_contact_name'] = array();
1083 $values[$activityID]['target_contact_counter'] = $dao->counter
;
1086 // if deleted, wrap in <del>
1087 if ($dao->is_deleted
) {
1088 $dao->contact_name
= "<del>{$dao->contact_name}</del>";
1091 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
1092 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
1093 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
1096 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
1097 // build array of target / assignee names
1098 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
1099 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
1101 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
1102 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
1105 // case related fields
1106 $values[$activityID]['case_id'] = $dao->case_id
;
1107 $values[$activityID]['case_subject'] = $dao->case_subject
;
1110 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter
));
1111 $values[$activityID]['mailingId'] = FALSE;
1114 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
1116 $values[$activityID]['mailingId'] = TRUE;
1127 public function addSelectWhereClause() {
1128 $clauses = parent
::addSelectWhereClause();
1129 if (!CRM_Core_Permission
::check('view all activities')) {
1130 $permittedActivityTypeIDs = self
::getPermittedActivityTypes();
1131 if (empty($permittedActivityTypeIDs)) {
1132 // This just prevents a mysql fail if they have no access - should be extremely edge case.
1133 $permittedActivityTypeIDs = [0];
1135 $clauses['activity_type_id'] = ('IN (' . implode(', ', $permittedActivityTypeIDs) . ')');
1141 * Get an array of components that are accessible by the currenct user.
1143 * This means checking if they are enabled and if the user has appropriate permission.
1145 * For most components the permission is access component (e.g 'access CiviContribute').
1146 * Exceptions as CiviCampaign (administer CiviCampaign) and CiviCase
1147 * (accesses a case function which enforces edit all cases or edit my cases. Case
1148 * permissions are also handled on a per activity basis).
1150 * Checks whether logged in user has permission to the component.
1152 * @param bool $excludeComponentHandledActivities
1153 * Should we exclude components whose display is handled in the components.
1154 * In practice this means should we include CiviCase in the results. Presumbaly
1155 * at the time it was decided case activities should be shown in the case framework and
1156 * that this concept might be extended later. In practice most places that
1157 * call this then re-add CiviCase in some way so it's all a bit... odd.
1159 * @return array Array of component id and name.
1160 * Array of component id and name.
1162 public static function activityComponents($excludeComponentHandledActivities = TRUE) {
1163 $components = array();
1164 $compInfo = CRM_Core_Component
::getEnabledComponents();
1165 foreach ($compInfo as $compObj) {
1166 $includeComponent = !$excludeComponentHandledActivities ||
!empty($compObj->info
['showActivitiesInCore']);
1167 if ($includeComponent) {
1168 if ($compObj->info
['name'] == 'CiviCampaign') {
1169 $componentPermission = "administer {$compObj->name}";
1172 $componentPermission = "access {$compObj->name}";
1174 if ($compObj->info
['name'] == 'CiviCase') {
1175 if (CRM_Case_BAO_Case
::accessCiviCase()) {
1176 $components[$compObj->componentID
] = $compObj->info
['name'];
1179 elseif (CRM_Core_Permission
::check($componentPermission)) {
1180 $components[$compObj->componentID
] = $compObj->info
['name'];
1189 * Get the activity Count.
1191 * @param array $input
1192 * Array of parameters.
1194 * - contact_id int contact_id whose activities we want to retrieve
1195 * - admin boolean if contact is admin
1196 * - caseId int case ID
1197 * - context string page on which selector is build
1198 * - activity_type_id int|string the activity types we want to restrict by
1201 * count of activities
1203 public static function getActivitiesCount($input) {
1204 $activityParams = self
::getActivityParamsForDashboardFunctions($input);
1205 return civicrm_api3('Activity', 'getcount', $activityParams);
1209 * Get the activity Count.
1213 * @param array $input
1214 * Array of parameters.
1216 * - contact_id int contact_id whose activities we want to retrieve
1217 * - admin boolean if contact is admin
1218 * - caseId int case ID
1219 * - context string page on which selector is build
1220 * - activity_type_id int|string the activity types we want to restrict by
1223 * count of activities
1225 public static function deprecatedGetActivitiesCount($input) {
1226 $input['count'] = TRUE;
1227 list($sqlClause, $params) = self
::deprecatedGetActivitySQLClause($input);
1229 //filter case activities - CRM-5761
1230 $components = self
::activityComponents();
1231 if (!in_array('CiviCase', $components)) {
1233 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
1234 FROM ( {$sqlClause} ) as tbl
1235 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
1236 WHERE civicrm_case_activity.id IS NULL";
1239 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
1242 return CRM_Core_DAO
::singleValueQuery($query, $params);
1246 * Get the activity sql clause to pick activities.
1250 * @param array $input
1251 * Array of parameters.
1253 * - contact_id int contact_id whose activities we want to retrieve
1254 * - admin boolean if contact is admin
1255 * - caseId int case ID
1256 * - context string page on which selector is build
1257 * - count boolean are we interested in the count clause only?
1258 * - activity_type_id int|string the activity types we want to restrict by
1261 * count of activities
1263 public static function deprecatedGetActivitySQLClause($input) {
1265 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1267 $config = CRM_Core_Config
::singleton();
1268 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
1269 $sourceWhere = ' ac.contact_id = %1 ';
1270 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1272 $params = array(1 => array($input['contact_id'], 'Integer'));
1275 $commonClauses = array(
1276 "civicrm_option_group.name = 'activity_type'",
1277 "civicrm_activity.is_deleted = 0",
1278 "civicrm_activity.is_current_revision = 1",
1279 "civicrm_activity.is_test= 0",
1282 if (isset($input['activity_date_relative']) ||
1283 (!empty($input['activity_date_low']) ||
!empty($input['activity_date_high']))
1285 list($from, $to) = CRM_Utils_Date
::getFromTo(
1286 CRM_Utils_Array
::value('activity_date_relative', $input, 0),
1287 CRM_Utils_Array
::value('activity_date_low', $input),
1288 CRM_Utils_Array
::value('activity_date_high', $input)
1290 $commonClauses[] = sprintf('civicrm_activity.activity_date_time BETWEEN "%s" AND "%s" ', $from, $to);
1293 if (!empty($input['activity_status_id'])) {
1294 $commonClauses[] = sprintf("civicrm_activity.status_id IN (%s)", $input['activity_status_id']);
1297 // Filter on component IDs.
1298 $components = self
::activityComponents();
1299 if (!empty($components)) {
1300 $componentsIn = implode(',', array_keys($components));
1301 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1304 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1307 // activity type ID clause
1308 if (!empty($input['activity_type_id'])) {
1309 if (is_array($input['activity_type_id'])) {
1310 foreach ($input['activity_type_id'] as $idx => $value) {
1311 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1313 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1316 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1317 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1321 // exclude by activity type clause
1322 if (!empty($input['activity_type_exclude_id'])) {
1323 if (is_array($input['activity_type_exclude_id'])) {
1324 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1325 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1327 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1330 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1331 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1335 $commonClause = implode(' AND ', $commonClauses);
1337 $includeCaseActivities = FALSE;
1338 if (in_array('CiviCase', $components)) {
1339 $includeCaseActivities = TRUE;
1342 // build main activity table select clause
1345 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1346 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1348 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1349 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1352 if (!$input['count']) {
1354 civicrm_activity.activity_date_time,
1355 civicrm_activity.source_record_id,
1356 civicrm_activity.status_id,
1357 civicrm_activity.subject,
1358 contact.sort_name as source_contact_name,
1359 civicrm_option_value.value as activity_type_id,
1360 civicrm_option_value.label as activity_type,
1361 null as case_id, null as case_subject,
1362 civicrm_activity.campaign_id as campaign_id
1366 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)
1371 SELECT civicrm_activity.id as activity_id
1373 from civicrm_activity
1374 left join civicrm_option_value on
1375 civicrm_activity.activity_type_id = civicrm_option_value.value
1376 left join civicrm_option_group on
1377 civicrm_option_group.id = civicrm_option_value.option_group_id
1384 // Build case clause
1385 // or else exclude Inbound Emails that have been filed on a case.
1388 if ($includeCaseActivities) {
1390 if (!$input['count']) {
1392 civicrm_activity.activity_date_time,
1393 civicrm_activity.source_record_id,
1394 civicrm_activity.status_id,
1395 civicrm_activity.subject,
1396 contact.sort_name as source_contact_name,
1397 civicrm_option_value.value as activity_type_id,
1398 civicrm_option_value.label as activity_type,
1399 null as case_id, null as case_subject,
1400 civicrm_activity.campaign_id as campaign_id';
1406 SELECT civicrm_activity.id as activity_id
1408 from civicrm_activity
1409 inner join civicrm_case_activity on
1410 civicrm_case_activity.activity_id = civicrm_activity.id
1411 inner join civicrm_case on
1412 civicrm_case_activity.case_id = civicrm_case.id
1413 inner join civicrm_case_contact on
1414 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1415 left join civicrm_option_value on
1416 civicrm_activity.activity_type_id = civicrm_option_value.value
1417 left join civicrm_option_group on
1418 civicrm_option_group.id = civicrm_option_value.option_group_id
1423 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1424 ( civicrm_option_value.name <> 'Inbound Email' AND
1425 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1431 $returnClause = " {$sourceClause} {$caseClause} ";
1433 return array($returnClause, $params);
1437 * Send the message to all the contacts.
1439 * Also insert a contact activity in each contacts record.
1441 * @param array $contactDetails
1442 * The array of contact details to send the email.
1443 * @param string $subject
1444 * The subject of the message.
1447 * @param string $emailAddress
1448 * Use this 'to' email address instead of the default Primary address.
1449 * @param int $userID
1450 * Use this userID if set.
1451 * @param string $from
1452 * @param array $attachments
1453 * The array of attachments if any.
1456 * @param string $bcc
1458 * @param array $contactIds
1460 * @param string $additionalDetails
1461 * The additional information of CC and BCC appended to the activity Details.
1462 * @param array $contributionIds
1463 * @param int $campaignId
1466 * ( sent, activityId) if any email is sent and activityId
1468 public static function sendEmail(
1476 $attachments = NULL,
1480 $additionalDetails = NULL,
1481 $contributionIds = NULL,
1484 // get the contact details of logged in contact, which we set as from email
1485 if ($userID == NULL) {
1486 $userID = CRM_Core_Session
::getLoggedInContactID();
1489 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1491 return array(count($contactDetails), 0, count($contactDetails));
1493 if (!trim($fromDisplayName)) {
1494 $fromDisplayName = $fromEmail;
1498 // token replacement of addressee/email/postal greetings
1499 // get the tokens added in subject and message
1500 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1501 $messageToken = CRM_Utils_Token
::getTokens($text);
1502 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1503 $allTokens = array_merge($messageToken, $subjectToken);
1506 $from = "$fromDisplayName <$fromEmail>";
1509 //create the meta level record first ( email activity )
1510 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email');
1512 // CRM-6265: save both text and HTML parts in details (if present)
1513 if ($html and $text) {
1514 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1517 $details = $html ?
$html : $text;
1518 $details .= $additionalDetails;
1521 $activityParams = array(
1522 'source_contact_id' => $userID,
1523 'activity_type_id' => $activityTypeID,
1524 'activity_date_time' => date('YmdHis'),
1525 'subject' => $subject,
1526 'details' => $details,
1527 // FIXME: check for name Completed and get ID from that lookup
1528 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1529 'campaign_id' => $campaignId,
1532 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1533 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1535 // add the attachments to activity params here
1537 // first process them
1538 $activityParams = array_merge($activityParams,
1543 $activity = self
::create($activityParams);
1545 // get the set of attachments from where they are stored
1546 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1549 $returnProperties = array();
1550 if (isset($messageToken['contact'])) {
1551 foreach ($messageToken['contact'] as $key => $value) {
1552 $returnProperties[$value] = 1;
1556 if (isset($subjectToken['contact'])) {
1557 foreach ($subjectToken['contact'] as $key => $value) {
1558 if (!isset($returnProperties[$value])) {
1559 $returnProperties[$value] = 1;
1564 // get token details for contacts, call only if tokens are used
1566 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1567 list($details) = CRM_Utils_Token
::getTokenDetails(
1572 'CRM_Activity_BAO_Activity'
1578 CRM_Utils_Hook
::tokens($tokens);
1579 $categories = array_keys($tokens);
1581 $escapeSmarty = FALSE;
1582 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1583 $smarty = CRM_Core_Smarty
::singleton();
1584 $escapeSmarty = TRUE;
1587 $contributionDetails = array();
1588 if (!empty($contributionIds)) {
1589 $contributionDetails = CRM_Contribute_BAO_Contribution
::replaceContributionTokens(
1600 $sent = $notSent = array();
1601 foreach ($contactDetails as $values) {
1602 $contactId = $values['contact_id'];
1603 $emailAddress = $values['email'];
1605 if (!empty($contributionDetails)) {
1606 $subject = $contributionDetails[$contactId]['subject'];
1607 $text = $contributionDetails[$contactId]['text'];
1608 $html = $contributionDetails[$contactId]['html'];
1611 if (!empty($details) && is_array($details["{$contactId}"])) {
1612 // unset email from details since it always returns primary email address
1613 unset($details["{$contactId}"]['email']);
1614 unset($details["{$contactId}"]['email_id']);
1615 $values = array_merge($values, $details["{$contactId}"]);
1618 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1619 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1622 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1623 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1624 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1630 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1631 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1632 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1638 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1639 // also add the contact tokens to the template
1640 $smarty->assign_by_ref('contact', $values);
1642 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1643 $tokenText = $smarty->fetch("string:$tokenText");
1644 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1648 if (self
::sendMessage(
1666 return array($sent, $activity->id
);
1670 * Send SMS. Returns: bool $sent, int $activityId, int $success (number of sent SMS)
1672 * @param array $contactDetails
1673 * @param array $activityParams
1674 * @param array $smsProviderParams
1675 * @param array $contactIds
1676 * @param int $sourceContactId This is the source contact Id
1678 * @return array(bool $sent, int $activityId, int $success)
1679 * @throws CRM_Core_Exception
1681 public static function sendSMS(
1682 &$contactDetails = NULL,
1684 &$smsProviderParams = array(),
1685 &$contactIds = NULL,
1686 $sourceContactId = NULL
1688 if (!CRM_Core_Permission
::check('send SMS')) {
1689 throw new CRM_Core_Exception("You do not have the 'send SMS' permission");
1692 if (!isset($contactDetails) && !isset($contactIds)) {
1693 Throw new CRM_Core_Exception('You must specify either $contactDetails or $contactIds');
1695 // Populate $contactDetails and $contactIds if only one is set
1696 if (is_array($contactIds) && !empty($contactIds) && empty($contactDetails)) {
1697 foreach ($contactIds as $id) {
1699 $contactDetails[] = civicrm_api3('Contact', 'getsingle', array('contact_id' => $id));
1701 catch (Exception
$e) {
1702 // Contact Id doesn't exist
1706 elseif (is_array($contactDetails) && !empty($contactDetails) && empty($contactIds)) {
1707 foreach ($contactDetails as $contact) {
1708 $contactIds[] = $contact['contact_id'];
1712 // Get logged in User Id
1713 if (empty($sourceContactId)) {
1714 $sourceContactId = CRM_Core_Session
::getLoggedInContactID();
1717 $text = &$activityParams['sms_text_message'];
1719 // Create the meta level record first ( sms activity )
1720 $activityParams = array(
1721 'source_contact_id' => $sourceContactId,
1722 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS'),
1723 'activity_date_time' => date('YmdHis'),
1724 'subject' => $activityParams['activity_subject'],
1726 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
1728 $activity = self
::create($activityParams);
1729 $activityID = $activity->id
;
1732 // token replacement of addressee/email/postal greetings
1733 // get the tokens added in subject and message
1734 $messageToken = CRM_Utils_Token
::getTokens($text);
1735 $returnProperties = array();
1736 if (isset($messageToken['contact'])) {
1737 foreach ($messageToken['contact'] as $key => $value) {
1738 $returnProperties[$value] = 1;
1743 CRM_Utils_Hook
::tokens($tokens);
1744 $categories = array_keys($tokens);
1745 // get token details for contacts, call only if tokens are used
1746 $tokenDetails = array();
1747 if (!empty($returnProperties) ||
!empty($tokens)) {
1748 list($tokenDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
1752 'CRM_Activity_BAO_Activity'
1758 foreach ($contactDetails as $contact) {
1759 $contactId = $contact['contact_id'];
1762 if (!empty($tokenDetails) && is_array($tokenDetails["{$contactId}"])) {
1763 // unset phone from details since it always returns primary number
1764 unset($tokenDetails["{$contactId}"]['phone']);
1765 unset($tokenDetails["{$contactId}"]['phone_type_id']);
1766 $contact = array_merge($contact, $tokenDetails["{$contactId}"]);
1768 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $contact, FALSE, $messageToken, FALSE, FALSE);
1769 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $contact, $categories, FALSE, FALSE);
1771 // Only send if the phone is of type mobile
1772 if ($contact['phone_type_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile')) {
1773 $smsProviderParams['To'] = $contact['phone'];
1776 $smsProviderParams['To'] = '';
1779 $doNotSms = CRM_Utils_Array
::value('do_not_sms', $contact, 0);
1782 $errMsgs[] = PEAR
::raiseError('Contact Does not accept SMS', NULL, PEAR_ERROR_RETURN
);
1785 $sendResult = self
::sendSMSMessage(
1793 if (PEAR
::isError($sendResult)) {
1794 // Collect all of the PEAR_Error objects
1795 $errMsgs[] = $sendResult;
1803 // If at least one message was sent and no errors
1804 // were generated then return a boolean value of TRUE.
1805 // Otherwise, return FALSE (no messages sent) or
1806 // and array of 1 or more PEAR_Error objects.
1808 if ($success > 0 && count($errMsgs) == 0) {
1811 elseif (count($errMsgs) > 0) {
1815 return array($sent, $activity->id
, $success);
1819 * Send the sms message to a specific contact.
1822 * The contact id of the recipient.
1824 * @param array $smsProviderParams
1825 * The params used for sending sms.
1826 * @param int $activityID
1827 * The activity ID that tracks the message.
1828 * @param int $sourceContactID
1830 * @return bool|PEAR_Error
1831 * true on success or PEAR_Error object
1833 public static function sendSMSMessage(
1836 $smsProviderParams = array(),
1838 $sourceContactID = NULL
1840 $toPhoneNumber = NULL;
1841 if ($smsProviderParams['To']) {
1842 // If phone number is specified use it
1843 $toPhoneNumber = trim($smsProviderParams['To']);
1846 // No phone number specified, so find a suitable one for the contact
1847 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1848 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1849 // To get primary mobile phonenumber, if not get the first mobile phonenumber
1850 if (!empty($toPhoneNumbers)) {
1851 $toPhoneNumberDetails = reset($toPhoneNumbers);
1852 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
1853 // Contact allows to send sms
1857 // make sure both phone are valid
1858 // and that the recipient wants to receive sms
1859 if (empty($toPhoneNumber)) {
1860 return PEAR
::raiseError(
1861 'Recipient phone number is invalid or recipient does not want to receive SMS',
1867 $recipient = $toPhoneNumber;
1868 $smsProviderParams['contact_id'] = $toID;
1869 $smsProviderParams['parent_activity_id'] = $activityID;
1871 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsProviderParams['provider_id']));
1872 $sendResult = $providerObj->send($recipient, $smsProviderParams, $tokenText, NULL, $sourceContactID);
1873 if (PEAR
::isError($sendResult)) {
1877 // add activity target record for every sms that is sent
1878 $targetID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
1879 $activityTargetParams = array(
1880 'activity_id' => $activityID,
1881 'contact_id' => $toID,
1882 'record_type_id' => $targetID,
1884 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1890 * Send the message to a specific contact.
1892 * @param string $from
1893 * The name and email of the sender.
1894 * @param int $fromID
1896 * The contact id of the recipient.
1897 * @param string $subject
1898 * The subject of the message.
1899 * @param $text_message
1900 * @param $html_message
1901 * @param string $emailAddress
1902 * Use this 'to' email address instead of the default Primary address.
1903 * @param int $activityID
1904 * The activity ID that tracks the message.
1905 * @param null $attachments
1910 * TRUE if successful else FALSE.
1912 public static function sendMessage(
1921 $attachments = NULL,
1925 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1926 if ($emailAddress) {
1927 $toEmail = trim($emailAddress);
1930 // make sure both email addresses are valid
1931 // and that the recipient wants to receive email
1932 if (empty($toEmail) or $toDoNotEmail) {
1935 if (!trim($toDisplayName)) {
1936 $toDisplayName = $toEmail;
1939 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1940 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1942 // create the params array
1943 $mailParams = array(
1944 'groupName' => 'Activity Email Sender',
1946 'toName' => $toDisplayName,
1947 'toEmail' => $toEmail,
1948 'subject' => $subject,
1951 'text' => $text_message,
1952 'html' => $html_message,
1953 'attachments' => $attachments,
1956 if (!CRM_Utils_Mail
::send($mailParams)) {
1960 // add activity target record for every mail that is send
1961 $activityTargetParams = array(
1962 'activity_id' => $activityID,
1963 'contact_id' => $toID,
1964 'record_type_id' => $targetID,
1966 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1971 * Combine all the importable fields from the lower levels object.
1973 * The ordering is important, since currently we do not have a weight
1974 * scheme. Adding weight is super important and should be done in the
1975 * next week or so, before this can be called complete.
1977 * @param bool $status
1980 * array of importable Fields
1982 public static function &importableFields($status = FALSE) {
1983 if (!self
::$_importableFields) {
1984 if (!self
::$_importableFields) {
1985 self
::$_importableFields = array();
1988 $fields = array('' => array('title' => ts('- do not import -')));
1991 $fields = array('' => array('title' => ts('- Activity Fields -')));
1994 $tmpFields = CRM_Activity_DAO_Activity
::import();
1995 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1997 // Using new Dedupe rule.
1998 $ruleParams = array(
1999 'contact_type' => 'Individual',
2000 'used' => 'Unsupervised',
2002 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
2004 $tmpConatctField = array();
2005 if (is_array($fieldsArray)) {
2006 foreach ($fieldsArray as $value) {
2007 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2012 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
2013 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
2014 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
2017 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
2018 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
2019 $fields = array_merge($fields, $tmpConatctField);
2020 $fields = array_merge($fields, $tmpFields);
2021 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2022 self
::$_importableFields = $fields;
2024 return self
::$_importableFields;
2028 * @deprecated - use the api instead.
2030 * Get the Activities of a target contact.
2032 * @param int $contactId
2033 * Id of the contact whose activities need to find.
2036 * array of activity fields
2038 public static function getContactActivity($contactId) {
2039 // @todo remove this function entirely.
2040 $activities = array();
2041 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2042 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2043 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2044 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2046 // First look for activities where contactId is one of the targets
2048 SELECT activity_id, record_type_id
2049 FROM civicrm_activity_contact
2050 WHERE contact_id = $contactId
2052 $dao = CRM_Core_DAO
::executeQuery($query);
2053 while ($dao->fetch()) {
2054 if ($dao->record_type_id
== $targetID) {
2055 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
2057 elseif ($dao->record_type_id
== $assigneeID) {
2058 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
2061 // do source stuff here
2062 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
2066 $activityIds = array_keys($activities);
2067 if (count($activityIds) < 1) {
2071 $activityIds = implode(',', $activityIds);
2073 SELECT activity.id as activity_id,
2075 subject, location, activity_date_time, details, status_id
2076 FROM civicrm_activity activity
2077 WHERE activity.id IN ($activityIds)";
2079 $dao = CRM_Core_DAO
::executeQuery($query);
2081 while ($dao->fetch()) {
2082 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
2083 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
2084 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
2085 $activities[$dao->activity_id
]['location'] = $dao->location
;
2086 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
2087 $activities[$dao->activity_id
]['details'] = $dao->details
;
2088 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
2089 $activities[$dao->activity_id
]['activity_name'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $dao->activity_type_id
);
2090 $activities[$dao->activity_id
]['status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status_id
);
2092 // set to null if not set
2093 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
2094 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
2101 * Add activity for Membership/Event/Contribution.
2103 * @param object $activity
2104 * (reference) particular component object.
2105 * @param string $activityType
2106 * For Membership Signup or Renewal.
2107 * @param int $targetContactID
2108 * @param array $params
2109 * Activity params to override.
2113 public static function addActivity(
2115 $activityType = 'Membership Signup',
2116 $targetContactID = NULL,
2119 $date = date('YmdHis');
2120 if ($activity->__table
== 'civicrm_membership') {
2121 $component = 'Membership';
2123 elseif ($activity->__table
== 'civicrm_participant') {
2124 if ($activityType != 'Email') {
2125 $activityType = 'Event Registration';
2127 $component = 'Event';
2129 elseif ($activity->__table
== 'civicrm_contribution') {
2130 // create activity record only for Completed Contributions
2131 $contributionCompletedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
2132 if ($activity->contribution_status_id
!= $contributionCompletedStatusId) {
2135 $activityType = $component = 'Contribution';
2137 // retrieve existing activity based on source_record_id and activity_type
2138 if (empty($params['id'])) {
2139 $params['id'] = CRM_Utils_Array
::value('id', civicrm_api3('Activity', 'Get', array(
2140 'source_record_id' => $activity->id
,
2141 'activity_type_id' => $activityType,
2144 if (!empty($params['id'])) {
2145 // CRM-13237 : if activity record found, update it with campaign id of contribution
2146 $params['campaign_id'] = $activity->campaign_id
;
2149 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
2152 $activityParams = array(
2153 'source_contact_id' => $activity->contact_id
,
2154 'source_record_id' => $activity->id
,
2155 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
2156 'activity_date_time' => $date,
2157 'is_test' => $activity->is_test
,
2158 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
2159 'skipRecentView' => TRUE,
2160 'campaign_id' => $activity->campaign_id
,
2162 $activityParams = array_merge($activityParams, $params);
2164 if (empty($activityParams['subject'])) {
2165 $activityParams['subject'] = self
::getActivitySubject($activity);
2168 if (!empty($activity->activity_id
)) {
2169 $activityParams['id'] = $activity->activity_id
;
2171 // create activity with target contacts
2172 $id = CRM_Core_Session
::getLoggedInContactID();
2174 $activityParams['source_contact_id'] = $id;
2175 $activityParams['target_contact_id'][] = $activity->contact_id
;
2179 if (property_exists($activity, 'details')) {
2180 $activityParams['details'] = $activity->details
;
2183 if ($targetContactID) {
2184 $activityParams['target_contact_id'][] = $targetContactID;
2186 // @todo - use api - remove lots of wrangling above. Remove deprecated fatal & let form layer
2187 // deal with any exceptions.
2188 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
2189 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
2195 * Get activity subject on basis of component object.
2197 * @param object $entityObj
2198 * particular component object.
2202 public static function getActivitySubject($entityObj) {
2203 switch ($entityObj->__table
) {
2204 case 'civicrm_membership':
2205 $membershipType = CRM_Member_PseudoConstant
::membershipType($entityObj->membership_type_id
);
2206 $subject = $membershipType ?
$membershipType : ts('Membership');
2208 if (is_array($subject)) {
2209 $subject = implode(", ", $subject);
2212 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
2213 $subject .= " - {$entityObj->source}";
2216 if ($entityObj->owner_membership_id
) {
2217 list($displayName) = CRM_Contact_BAO_Contact
::getDisplayAndImage(CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $entityObj->owner_membership_id
, 'contact_id'));
2218 $subject .= sprintf(' (by %s)', $displayName);
2221 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $entityObj->status_id
, 'label');
2224 case 'civicrm_participant':
2225 $event = CRM_Event_BAO_Event
::getEvents(1, $entityObj->event_id
, TRUE, FALSE);
2226 $roles = CRM_Event_PseudoConstant
::participantRole();
2227 $status = CRM_Event_PseudoConstant
::participantStatus();
2228 $subject = $event[$entityObj->event_id
];
2230 if (!empty($roles[$entityObj->role_id
])) {
2231 $subject .= ' - ' . $roles[$entityObj->role_id
];
2233 if (!empty($status[$entityObj->status_id
])) {
2234 $subject .= ' - ' . $status[$entityObj->status_id
];
2239 case 'civicrm_contribution':
2240 $subject = CRM_Utils_Money
::format($entityObj->total_amount
, $entityObj->currency
);
2241 if (!CRM_Utils_System
::isNull($entityObj->source
)) {
2242 $subject .= " - {$entityObj->source}";
2245 // Amount and source could exceed max length of subject column.
2246 return CRM_Utils_String
::ellipsify($subject, 255);
2251 * Get Parent activity for currently viewed activity.
2253 * @param int $activityId
2254 * Current activity id.
2257 * Id of parent activity otherwise false.
2259 public static function getParentActivity($activityId) {
2260 static $parentActivities = array();
2262 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
2264 if (!array_key_exists($activityId, $parentActivities)) {
2265 $parentActivities[$activityId] = array();
2267 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2272 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
2275 return $parentActivities[$activityId];
2279 * Get total count of prior revision of currently viewed activity.
2281 * @param $activityID
2282 * Current activity id.
2285 * $params count of prior activities otherwise false.
2287 public static function getPriorCount($activityID) {
2288 static $priorCounts = array();
2290 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2292 if (!array_key_exists($activityID, $priorCounts)) {
2293 $priorCounts[$activityID] = array();
2294 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2301 SELECT count( id ) AS cnt
2302 FROM civicrm_activity
2303 WHERE ( id = {$originalID} OR original_id = {$originalID} )
2304 AND is_current_revision = 0
2305 AND id < {$activityID}
2307 $params = array(1 => array($originalID, 'Integer'));
2308 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
2310 $priorCounts[$activityID] = $count ?
$count : 0;
2313 return $priorCounts[$activityID];
2317 * Get all prior activities of currently viewed activity.
2319 * @param $activityID
2320 * Current activity id.
2321 * @param bool $onlyPriorRevisions
2324 * prior activities info.
2326 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
2327 static $priorActivities = array();
2329 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2330 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2332 if (!array_key_exists($index, $priorActivities)) {
2333 $priorActivities[$index] = array();
2335 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2340 $originalID = $activityID;
2344 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2345 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2346 WHERE (ca.id = %1 OR ca.original_id = %1)
2347 AND cl.entity_table = 'civicrm_activity'
2348 AND cl.entity_id = ca.id
2349 AND cl.modified_id = c.id
2351 if ($onlyPriorRevisions) {
2352 $query .= " AND ca.id < {$activityID}";
2354 $query .= " ORDER BY ca.id DESC";
2356 $params = array(1 => array($originalID, 'Integer'));
2357 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2359 while ($dao->fetch()) {
2360 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
2361 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
2362 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
2366 return $priorActivities[$index];
2370 * Find the latest revision of a given activity.
2372 * @param int $activityID
2373 * Prior activity id.
2376 * current activity id.
2378 public static function getLatestActivityId($activityID) {
2379 static $latestActivityIds = array();
2381 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2383 if (!array_key_exists($activityID, $latestActivityIds)) {
2384 $latestActivityIds[$activityID] = array();
2386 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2391 $activityID = $originalID;
2393 $params = array(1 => array($activityID, 'Integer'));
2394 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2396 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2399 return $latestActivityIds[$activityID];
2403 * Create a follow up a given activity.
2405 * @param int $activityId
2406 * activity id of parent activity.
2407 * @param array $params
2409 * @return CRM_Activity_BAO_Activity|null|object
2411 public static function createFollowupActivity($activityId, $params) {
2416 $followupParams = array();
2417 $followupParams['parent_id'] = $activityId;
2418 $followupParams['source_contact_id'] = CRM_Core_Session
::getLoggedInContactID();
2419 $followupParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2421 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2422 // Get Subject of Follow-up Activiity, CRM-4491
2423 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2424 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2426 // Create target contact for followup.
2427 if (!empty($params['target_contact_id'])) {
2428 $followupParams['target_contact_id'] = $params['target_contact_id'];
2431 $followupParams['activity_date_time'] = $params['followup_date'];
2432 $followupActivity = self
::create($followupParams);
2434 return $followupActivity;
2438 * Get Activity specific File according activity type Id.
2440 * @param int $activityTypeId
2442 * @param string $crmDir
2444 * @return string|bool
2445 * if file exists returns $activityTypeFile activity filename otherwise false.
2447 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2448 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2450 if ($activityTypes[$activityTypeId]['name']) {
2451 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2457 global $civicrm_root;
2458 $config = CRM_Core_Config
::singleton();
2459 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2460 if (empty($config->customPHPPathDir
)) {
2463 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2468 return $activityTypeFile;
2472 * Restore the activity.
2474 * @param array $params
2476 * @return CRM_Activity_DAO_Activity
2478 public static function restoreActivity(&$params) {
2479 $activity = new CRM_Activity_DAO_Activity();
2480 $activity->copyValues($params);
2482 $activity->is_deleted
= 0;
2483 $result = $activity->save();
2489 * Return list of activity statuses of a given type.
2491 * Note: activity status options use the "grouping" field to distinguish status types.
2492 * Types are defined in class constants INCOMPLETE, COMPLETED, CANCELLED
2498 public static function getStatusesByType($type) {
2499 if (!isset(Civi
::$statics[__CLASS__
][__FUNCTION__
])) {
2500 $statuses = civicrm_api3('OptionValue', 'get', array(
2501 'option_group_id' => 'activity_status',
2502 'return' => array('value', 'name', 'filter'),
2503 'options' => array('limit' => 0),
2505 Civi
::$statics[__CLASS__
][__FUNCTION__
] = $statuses['values'];
2508 foreach (Civi
::$statics[__CLASS__
][__FUNCTION__
] as $status) {
2509 if ($status['filter'] == $type) {
2510 $ret[$status['value']] = $status['name'];
2517 * Check if activity is overdue.
2519 * @param array $activity
2523 public static function isOverdue($activity) {
2524 return array_key_exists($activity['status_id'], self
::getStatusesByType(self
::INCOMPLETE
)) && CRM_Utils_Date
::overdue($activity['activity_date_time']);
2528 * Get the exportable fields for Activities.
2530 * @param string $name
2531 * If it is called by case $name = Case else $name = Activity.
2534 * array of exportable Fields
2536 public static function exportableFields($name = 'Activity') {
2537 self
::$_exportableFields[$name] = array();
2539 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
2540 // my case hence we have defined fields as case_*
2541 if ($name == 'Activity') {
2542 $exportableFields = CRM_Activity_DAO_Activity
::export();
2543 $exportableFields['source_contact_id'] = [
2544 'title' => ts('Source Contact ID'),
2545 'type' => CRM_Utils_Type
::T_INT
,
2547 $exportableFields['source_contact'] = array(
2548 'title' => ts('Source Contact'),
2549 'type' => CRM_Utils_Type
::T_STRING
,
2552 $Activityfields = array(
2553 'activity_type' => array(
2554 'title' => ts('Activity Type'),
2555 'name' => 'activity_type',
2556 'type' => CRM_Utils_Type
::T_STRING
,
2557 'searchByLabel' => TRUE,
2559 'activity_status' => array(
2560 'title' => ts('Activity Status'),
2561 'name' => 'activity_status',
2562 'type' => CRM_Utils_Type
::T_STRING
,
2563 'searchByLabel' => TRUE,
2565 'activity_priority' => array(
2566 'title' => ts('Activity Priority'),
2567 'name' => 'activity_priority',
2568 'type' => CRM_Utils_Type
::T_STRING
,
2569 'searchByLabel' => TRUE,
2572 $fields = array_merge($Activityfields, $exportableFields);
2575 // Set title to activity fields.
2577 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2578 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2579 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2580 'case_scheduled_activity_date' => array(
2581 'title' => ts('Activity Scheduled Date'),
2582 'type' => CRM_Utils_Type
::T_DATE
,
2584 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2585 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2586 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2587 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2588 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2589 'case_activity_is_auto' => array(
2590 'title' => ts('Activity Auto-generated?'),
2591 'type' => CRM_Utils_Type
::T_BOOLEAN
,
2596 // add custom data for case activities
2597 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2599 self
::$_exportableFields[$name] = $fields;
2600 return self
::$_exportableFields[$name];
2604 * Get the allowed profile fields for Activities.
2607 * array of activity profile Fields
2609 public static function getProfileFields() {
2610 $exportableFields = self
::exportableFields('Activity');
2611 $skipFields = array(
2614 'source_contact_id',
2616 'activity_campaign',
2618 'is_current_revision',
2619 'activity_is_deleted',
2621 $config = CRM_Core_Config
::singleton();
2622 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2623 $skipFields[] = 'activity_engagement_level';
2626 foreach ($skipFields as $field) {
2627 if (isset($exportableFields[$field])) {
2628 unset($exportableFields[$field]);
2632 // hack to use 'activity_type_id' instead of 'activity_type'
2633 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2634 unset($exportableFields['activity_status']);
2636 return $exportableFields;
2640 * This function deletes the activity record related to contact record.
2642 * This is conditional on there being no target and assignee record
2643 * with other contacts.
2645 * @param int $contactId
2650 public static function cleanupActivity($contactId) {
2655 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2656 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2658 $transaction = new CRM_Core_Transaction();
2660 // delete activity if there is no record in civicrm_activity_contact
2661 // pointing to any other contact record
2662 $activityContact = new CRM_Activity_DAO_ActivityContact();
2663 $activityContact->contact_id
= $contactId;
2664 $activityContact->record_type_id
= $sourceID;
2665 $activityContact->find();
2667 while ($activityContact->fetch()) {
2668 // delete activity_contact record for the deleted contact
2669 $activityContact->delete();
2671 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2672 $activityContactOther->activity_id
= $activityContact->activity_id
;
2674 // delete activity only if no other contacts connected
2675 if (!$activityContactOther->find(TRUE)) {
2676 $activityParams = array('id' => $activityContact->activity_id
);
2677 $result = self
::deleteActivity($activityParams);
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 if (!self
::hasPermissionForActivityType($activity->activity_type_id
)) {
2712 // this check is redundant for api access / anything that calls the selectWhereClause
2713 // to determine ACLs.
2716 // Return early when it is case activity.
2717 // Check for CiviCase related permission.
2718 if (CRM_Case_BAO_Case
::isCaseActivity($activityId)) {
2719 return self
::isContactPermittedAccessToCaseActivity($activityId, $action, $activity->activity_type_id
);
2722 // Check for this permission related to contact.
2723 $permission = CRM_Core_Permission
::VIEW
;
2724 if ($action == CRM_Core_Action
::UPDATE
) {
2725 $permission = CRM_Core_Permission
::EDIT
;
2728 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2729 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2730 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2731 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2733 // Check for source contact.
2734 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2735 // Account for possibility of activity not having a source contact (as it may have been deleted).
2736 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission) : TRUE;
2741 // Check for target and assignee contacts.
2742 // First check for supper permission.
2743 $supPermission = 'view all contacts';
2744 if ($action == CRM_Core_Action
::UPDATE
) {
2745 $supPermission = 'edit all contacts';
2747 $allow = CRM_Core_Permission
::check($supPermission);
2749 // User might have sufficient permission, through acls.
2752 // Get the target contacts.
2753 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2754 foreach ($targetContacts as $cnt => $contactId) {
2755 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2761 // Get the assignee contacts.
2763 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2764 foreach ($assigneeContacts as $cnt => $contactId) {
2765 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2777 * Check if the logged in user has permission for the given case activity.
2779 * @param int $activityId
2780 * @param int $action
2781 * @param int $activityTypeID
2785 protected static function isContactPermittedAccessToCaseActivity($activityId, $action, $activityTypeID) {
2787 if ($action == CRM_Core_Action
::UPDATE
) {
2790 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2799 * Check if the logged in user has permission to access the given activity type.
2801 * @param int $activityTypeID
2805 protected static function hasPermissionForActivityType($activityTypeID) {
2806 $permittedActivityTypes = self
::getPermittedActivityTypes();
2807 return isset($permittedActivityTypes[$activityTypeID]);
2811 * Get the activity types the user is permitted to access.
2813 * The types are filtered by the components they have access to. ie. a user
2814 * with access CiviContribute but not CiviMember will see contribution related
2815 * activities and activities with no component (e.g meetings) but not member related ones.
2819 protected static function getPermittedActivityTypes() {
2820 $userID = (int) CRM_Core_Session
::getLoggedInContactID();
2821 if (!isset(Civi
::$statics[__CLASS__
]['permitted_activity_types'][$userID])) {
2822 $permittedActivityTypes = [];
2823 $components = self
::activityComponents(FALSE);
2824 $componentClause = empty($components) ?
'' : (' OR component_id IN (' . implode(', ', array_keys($components)) . ')');
2826 $types = CRM_Core_DAO
::executeQuery(
2828 SELECT option_value.value activity_type_id
2829 FROM civicrm_option_value option_value
2830 INNER JOIN civicrm_option_group grp ON (grp.id = option_group_id AND grp.name = 'activity_type')
2831 WHERE component_id IS NULL $componentClause")->fetchAll();
2832 foreach ($types as $type) {
2833 $permittedActivityTypes[$type['activity_type_id']] = (int) $type['activity_type_id'];
2835 Civi
::$statics[__CLASS__
]['permitted_activity_types'][$userID] = $permittedActivityTypes;
2837 return Civi
::$statics[__CLASS__
]['permitted_activity_types'][$userID];
2844 protected static function getActivityParamsForDashboardFunctions($params) {
2847 'is_current_revision' => 1,
2849 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
2850 'check_permissions' => 1,
2852 'offset' => CRM_Utils_Array
::value('offset', $params, 0),
2856 if (!empty($params['activity_status_id'])) {
2857 $activityParams['activity_status_id'] = ['IN' => explode(',', $params['activity_status_id'])];
2860 $activityParams['activity_type_id'] = self
::filterActivityTypes($params);
2861 $enabledComponents = self
::activityComponents();
2862 // @todo - should we move this to activity get api.
2864 'case_id' => 'CiviCase',
2865 'campaign_id' => 'CiviCampaign'
2866 ] as $attr => $component) {
2867 if (!in_array($component, $enabledComponents)) {
2868 $activityParams[$attr] = ['IS NULL' => 1];
2871 return $activityParams;
2875 * Checks if user has permissions to edit inbound e-mails, either bsic info
2876 * or both basic information and content.
2880 public function checkEditInboundEmailsPermissions() {
2881 if (CRM_Core_Permission
::check('edit inbound email basic information')
2882 || CRM_Core_Permission
::check('edit inbound email basic information and content')
2891 * Wrapper for ajax activity selector.
2893 * @param array $params
2894 * Associated array for params record id.
2897 * Associated array of contact activities
2899 public static function getContactActivitySelector(&$params) {
2900 // Format the params.
2901 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2902 $params['rowCount'] = $params['rp'];
2903 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2904 $params['caseId'] = NULL;
2905 $context = CRM_Utils_Array
::value('context', $params);
2906 $showContactOverlay = !CRM_Utils_String
::startsWith($context, "dashlet");
2907 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2908 'option_group_id' => "activity_type",
2909 'options' => array('limit' => 0),
2911 $activityIcons = array();
2912 foreach ($activityTypeInfo['values'] as $type) {
2913 if (!empty($type['icon'])) {
2914 $activityIcons[$type['value']] = $type['icon'];
2918 // Get contact activities.
2919 $activities = CRM_Activity_BAO_Activity
::deprecatedGetActivities($params);
2922 $params['total'] = CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($params);
2924 // Format params and add links.
2925 $contactActivities = array();
2927 if (!empty($activities)) {
2928 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2930 // Check logged in user for permission.
2931 $page = new CRM_Core_Page();
2932 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2933 $permissions = array($page->_permission
);
2934 if (CRM_Core_Permission
::check('delete activities')) {
2935 $permissions[] = CRM_Core_Permission
::DELETE
;
2938 $mask = CRM_Core_Action
::mask($permissions);
2940 foreach ($activities as $activityId => $values) {
2941 $activity = array();
2942 $activity['DT_RowId'] = $activityId;
2943 // Add class to this row if overdue.
2944 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2945 if (self
::isOverdue($values)) {
2946 $activity['DT_RowClass'] .= ' status-overdue';
2949 $activity['DT_RowClass'] .= ' status-ontime';
2952 $activity['DT_RowAttr'] = array();
2953 $activity['DT_RowAttr']['data-entity'] = 'activity';
2954 $activity['DT_RowAttr']['data-id'] = $activityId;
2956 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ?
'<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2957 $activity['subject'] = $values['subject'];
2959 $activity['source_contact_name'] = '';
2960 if ($params['contact_id'] == $values['source_contact_id']) {
2961 $activity['source_contact_name'] = $values['source_contact_name'];
2963 elseif ($values['source_contact_id']) {
2965 if ($showContactOverlay) {
2966 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2967 CRM_Contact_BAO_Contact
::getContactType($values['source_contact_id']),
2969 $values['source_contact_id']);
2971 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System
::href($values['source_contact_name'],
2972 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2975 $activity['source_contact_name'] = '<em>n/a</em>';
2978 $activity['target_contact_name'] = '';
2979 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2980 $activity['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2981 'civicrm/mailing/report/event',
2982 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2984 elseif (!empty($values['recipients'])) {
2985 $activity['target_contact_name'] = $values['recipients'];
2987 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2988 $activity['target_contact_name'] = '';
2989 $firstTargetName = reset($values['target_contact_name']);
2990 $firstTargetContactID = key($values['target_contact_name']);
2992 $targetLink = CRM_Utils_System
::href($firstTargetName, 'civicrm/contact/view', "reset=1&cid={$firstTargetContactID}");
2993 if ($showContactOverlay) {
2994 $targetTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2995 CRM_Contact_BAO_Contact
::getContactType($firstTargetContactID),
2997 $firstTargetContactID);
2998 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
3001 $activity['target_contact_name'] .= $targetLink;
3004 if ($extraCount = $values['target_contact_counter'] - 1) {
3005 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
3007 if ($showContactOverlay) {
3008 $activity['target_contact_name'] .= "</div> ";
3011 elseif (!$values['target_contact_name']) {
3012 $activity['target_contact_name'] = '<em>n/a</em>';
3015 $activity['assignee_contact_name'] = '';
3016 if (empty($values['assignee_contact_name'])) {
3017 $activity['assignee_contact_name'] = '<em>n/a</em>';
3019 elseif (!empty($values['assignee_contact_name'])) {
3021 $activity['assignee_contact_name'] = '';
3022 foreach ($values['assignee_contact_name'] as $acID => $acName) {
3023 if ($acID && $count < 5) {
3024 $assigneeTypeImage = "";
3025 $assigneeLink = CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
3026 if ($showContactOverlay) {
3027 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
3028 CRM_Contact_BAO_Contact
::getContactType($acID),
3031 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
3034 $activity['assignee_contact_name'] .= $assigneeLink;
3039 $activity['assignee_contact_name'] .= "; ";
3041 if ($showContactOverlay) {
3042 $activity['assignee_contact_name'] .= "</div> ";
3046 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
3053 $activity['activity_date_time'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
3054 $activity['status_id'] = $activityStatus[$values['status_id']];
3057 $activity['links'] = '';
3058 $accessMailingReport = FALSE;
3059 if (!empty($values['mailingId'])) {
3060 $accessMailingReport = TRUE;
3063 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
3064 CRM_Utils_Array
::value('activity_type_id', $values),
3065 CRM_Utils_Array
::value('source_record_id', $values),
3066 $accessMailingReport,
3067 CRM_Utils_Array
::value('activity_id', $values)
3070 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
3072 $activity['links'] = CRM_Core_Action
::formLink($actionLinks,
3075 'id' => $values['activity_id'],
3076 'cid' => $params['contact_id'],
3078 'caseid' => CRM_Utils_Array
::value('case_id', $values),
3084 $values['activity_id']
3087 if ($values['is_recurring_activity']) {
3088 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($values['activity_id'], 'civicrm_activity');
3091 array_push($contactActivities, $activity);
3095 $activitiesDT = array();
3096 $activitiesDT['data'] = $contactActivities;
3097 $activitiesDT['recordsTotal'] = $params['total'];
3098 $activitiesDT['recordsFiltered'] = $params['total'];
3100 return $activitiesDT;
3104 * Copy custom fields and attachments from an existing activity to another.
3106 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
3108 * @param array $params
3110 public static function copyExtendedActivityData($params) {
3111 // attach custom data to the new activity
3112 $customParams = $htmlType = array();
3113 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
3115 if (!empty($customValues)) {
3116 $fieldIds = implode(', ', array_keys($customValues));
3117 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
3118 $result = CRM_Core_DAO
::executeQuery($sql);
3120 while ($result->fetch()) {
3121 $htmlType[] = $result->id
;
3124 foreach ($customValues as $key => $value) {
3125 if ($value !== NULL) {
3127 if (in_array($key, $htmlType)) {
3128 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
3129 $customParams["custom_{$key}_-1"] = array(
3130 'name' => $fileValues[0],
3131 'type' => $fileValues[1],
3135 $customParams["custom_{$key}_-1"] = $value;
3139 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_activity',
3140 $params['mainActivityId'], 'Activity'
3144 // copy activity attachments ( if any )
3145 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
3149 * Get activity contact.
3151 * @param int $activityId
3152 * @param int $recordTypeID
3153 * @param string $column
3157 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
3158 $activityContact = new CRM_Activity_BAO_ActivityContact();
3159 $activityContact->activity_id
= $activityId;
3160 if ($recordTypeID) {
3161 $activityContact->record_type_id
= $recordTypeID;
3163 if ($activityContact->find(TRUE)) {
3164 return $activityContact->$column;
3170 * Get source contact id.
3172 * @param int $activityId
3176 public static function getSourceContactID($activityId) {
3177 static $sourceID = NULL;
3179 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3180 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
3183 return self
::getActivityContact($activityId, $sourceID);
3189 * @todo Document what this is for.
3191 * @param array $params
3193 public function setApiFilter(&$params) {
3194 if (!empty($params['target_contact_id'])) {
3196 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3197 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3198 $obj = new CRM_Activity_BAO_ActivityContact();
3199 $params['return.target_contact_id'] = 1;
3200 $this->joinAdd($obj, 'LEFT');
3201 $this->selectAdd('civicrm_activity.*');
3202 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
3207 * Send activity as attachment.
3209 * @param object $activity
3210 * @param array $mailToContacts
3211 * @param array $params
3215 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
3216 if (!CRM_Utils_Array
::crmIsEmptyArray($mailToContacts)) {
3217 $clientID = CRM_Utils_Array
::value('client_id', $params);
3218 $caseID = CRM_Utils_Array
::value('case_id', $params);
3220 $ics = new CRM_Activity_BAO_ICalendar($activity);
3221 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity', $activity->id
);
3222 $ics->addAttachment($attachments, $mailToContacts);
3224 $result = CRM_Case_BAO_Case
::sendActivityCopy($clientID, $activity->id
, $mailToContacts, $attachments, $caseID);
3234 public static function getEntityRefFilters() {
3236 ['key' => 'activity_type_id', 'value' => ts('Activity Type')],
3237 ['key' => 'status_id', 'value' => ts('Activity Status')],