3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * This class is for activity functions.
37 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
40 * Static field for all the activity information that we can potentially export.
44 static $_exportableFields = NULL;
47 * Static field for all the activity information that we can potentially import.
51 static $_importableFields = NULL;
54 * Check if there is absolute minimum of data to add the object.
56 * @param array $params
57 * (reference ) an assoc array of name/value pairs.
61 public static function dataExists(&$params) {
62 if (!empty($params['source_contact_id']) ||
!empty($params['id'])) {
69 * Fetch object based on array of properties.
71 * @param array $params
72 * (reference ) an assoc array of name/value pairs.
73 * @param array $defaults
74 * (reference ) an assoc array to hold the flattened values.
76 * @return CRM_Activity_DAO_Activity
78 public static function retrieve(&$params, &$defaults) {
79 $activity = new CRM_Activity_DAO_Activity();
80 $activity->copyValues($params);
82 if ($activity->find(TRUE)) {
83 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
84 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
85 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
86 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
88 // TODO: at some stage we'll have to deal
89 // with multiple values for assignees and targets, but
90 // for now, let's just fetch first row.
91 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
92 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
93 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
94 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
95 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
96 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
97 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
98 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
100 elseif (CRM_Core_Permission
::check('access CiviMail') ||
101 (CRM_Mailing_Info
::workflowEnabled() &&
102 CRM_Core_Permission
::check('create mailings')
105 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
106 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
110 $defaults['target_contact_value'] = ts('(recipients)');
113 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
114 $defaults['source_contact_id'] = $sourceContactId;
116 if ($sourceContactId &&
117 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
122 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
129 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
131 CRM_Core_DAO
::storeValues($activity, $defaults);
139 * Delete the activity.
141 * @param array $params
142 * @param bool $moveToTrash
146 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
148 if (!empty($params['id']) && !is_array($params['id'])) {
149 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
152 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
155 $transaction = new CRM_Core_Transaction();
156 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
157 $sourceRecordIds = implode(',', $params['source_record_id']);
160 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
165 if (!isset($params['id'])) {
166 if (is_array($params['activity_type_id'])) {
167 $activityTypes = implode(',', $params['activity_type_id']);
170 $activityTypes = $params['activity_type_id'];
173 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
174 $dao = CRM_Core_DAO
::executeQuery($query);
177 $activity = new CRM_Activity_DAO_Activity();
178 $activity->copyValues($params);
179 $result = $activity->delete();
182 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
184 // CRM-13994 delete activity entity_tag
185 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
186 $dao = CRM_Core_DAO
::executeQuery($query);
190 $activity = new CRM_Activity_DAO_Activity();
191 $activity->copyValues($params);
193 $activity->is_deleted
= 1;
194 $result = $activity->save();
196 // CRM-4525 log activity delete
197 $logMsg = 'Case Activity deleted for';
200 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
201 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
202 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
203 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
204 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
205 if ($sourceContactId) {
206 $msgs[] = " source={$sourceContactId}";
209 // get target contacts.
210 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
211 if (!empty($targetContactIds)) {
212 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
214 // get assignee contacts.
215 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
216 if (!empty($assigneeContactIds)) {
217 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
220 $logMsg .= implode(', ', $msgs);
222 self
::logActivityAction($activity, $logMsg);
225 // delete the recently created Activity
227 $activityRecent = array(
228 'id' => $activity->id
,
229 'type' => 'Activity',
231 CRM_Utils_Recent
::del($activityRecent);
234 $transaction->commit();
235 if (isset($activity)) {
237 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
238 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
245 * Delete activity assignment record.
247 * @param int $activityId
248 * @param int $recordTypeID
250 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
251 $activityContact = new CRM_Activity_BAO_ActivityContact();
252 $activityContact->activity_id
= $activityId;
254 $activityContact->record_type_id
= $recordTypeID;
257 // Let's check if activity contact record exits and then delete.
258 // Looks like delete leads to deadlock when multiple simultaneous
259 // requests are done. CRM-15470
260 if ($activityContact->find()) {
261 $activityContact->delete();
266 * Process the activities.
268 * @param array $params
269 * Associated array of the submitted values.
271 * @throws CRM_Core_Exception
273 * @return CRM_Activity_BAO_Activity|null|object
275 public static function create(&$params) {
276 // check required params
277 if (!self
::dataExists($params)) {
278 throw new CRM_Core_Exception('Not enough data to create activity object');
281 $activity = new CRM_Activity_DAO_Activity();
283 if (isset($params['id']) && empty($params['id'])) {
284 unset($params['id']);
287 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
288 if (isset($params['activity_date_time']) &&
289 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
291 $params['status_id'] = 2;
294 $params['status_id'] = 1;
298 // Set priority to Normal for Auto-populated activities (for Cases)
299 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
300 // if not set and not 0
301 !CRM_Utils_Array
::value('id', $params)
303 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
304 $params['priority_id'] = array_search('Normal', $priority);
307 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
308 $params['target_contact_id'] = array_unique($params['target_contact_id']);
310 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
311 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
315 if (!empty($params['id'])) {
316 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
319 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
322 $activity->copyValues($params);
323 if (isset($params['case_id'])) {
324 // CRM-8708, preserve case ID even though it's not part of the SQL model
325 $activity->case_id
= $params['case_id'];
327 elseif (is_numeric($activity->id
)) {
328 // CRM-8708, preserve case ID even though it's not part of the SQL model
329 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
333 $transaction = new CRM_Core_Transaction();
335 $result = $activity->save();
337 if (is_a($result, 'CRM_Core_Error')) {
338 $transaction->rollback();
342 $activityId = $activity->id
;
343 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
344 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
345 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
346 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
348 if (isset($params['source_contact_id'])) {
350 'activity_id' => $activityId,
351 'contact_id' => $params['source_contact_id'],
352 'record_type_id' => $sourceID,
354 self
::deleteActivityContact($activityId, $sourceID);
355 CRM_Activity_BAO_ActivityContact
::create($acParams);
358 // check and attach and files as needed
359 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
361 // attempt to save activity assignment
362 $resultAssignment = NULL;
363 if (!empty($params['assignee_contact_id'])) {
365 $assignmentParams = array('activity_id' => $activityId);
367 if (is_array($params['assignee_contact_id'])) {
368 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
369 // first delete existing assignments if any
370 self
::deleteActivityContact($activityId, $assigneeID);
374 foreach ($params['assignee_contact_id'] as $acID) {
376 $values[] = "( $activityId, $acID, $assigneeID )";
379 while (!empty($values)) {
380 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
381 $str = implode(',', $input);
382 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
383 CRM_Core_DAO
::executeQuery($sql);
387 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
388 $assignmentParams['record_type_id'] = $assigneeID;
389 if (!empty($params['id'])) {
390 $assignment = new CRM_Activity_BAO_ActivityContact();
391 $assignment->activity_id
= $activityId;
392 $assignment->record_type_id
= $assigneeID;
393 $assignment->find(TRUE);
395 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
396 $assignmentParams['id'] = $assignment->id
;
397 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
401 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
406 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
407 self
::deleteActivityContact($activityId, $assigneeID);
411 if (is_a($resultAssignment, 'CRM_Core_Error')) {
412 $transaction->rollback();
413 return $resultAssignment;
416 // attempt to save activity targets
417 $resultTarget = NULL;
418 if (!empty($params['target_contact_id'])) {
420 $targetParams = array('activity_id' => $activityId);
421 $resultTarget = array();
422 if (is_array($params['target_contact_id'])) {
423 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
424 // first delete existing targets if any
425 self
::deleteActivityContact($activityId, $targetID);
429 foreach ($params['target_contact_id'] as $tid) {
431 $values[] = "( $activityId, $tid, $targetID )";
435 while (!empty($values)) {
436 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
437 $str = implode(',', $input);
438 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
439 CRM_Core_DAO
::executeQuery($sql);
443 $targetParams['contact_id'] = $params['target_contact_id'];
444 $targetParams['record_type_id'] = $targetID;
445 if (!empty($params['id'])) {
446 $target = new CRM_Activity_BAO_ActivityContact();
447 $target->activity_id
= $activityId;
448 $target->record_type_id
= $targetID;
451 if ($target->contact_id
!= $params['target_contact_id']) {
452 $targetParams['id'] = $target->id
;
453 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
457 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
462 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
463 self
::deleteActivityContact($activityId, $targetID);
467 // write to changelog before transaction is committed/rolled
468 // back (and prepare status to display)
469 if (!empty($params['id'])) {
470 $logMsg = "Activity (id: {$result->id} ) updated with ";
473 $logMsg = "Activity created for ";
477 if (isset($params['source_contact_id'])) {
478 $msgs[] = "source={$params['source_contact_id']}";
481 if (!empty($params['target_contact_id'])) {
482 if (is_array($params['target_contact_id']) && !CRM_Utils_Array
::crmIsEmptyArray($params['target_contact_id'])) {
483 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
484 // take only first target
485 // will be used for recently viewed display
486 $t = array_slice($params['target_contact_id'], 0, 1);
487 $recentContactId = $t[0];
489 // Is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
490 // as it may always be an array
491 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
492 $msgs[] = "target={$params['target_contact_id']}";
493 // will be used for recently viewed display
494 $recentContactId = $params['target_contact_id'];
498 // at worst, take source for recently viewed display
499 $recentContactId = CRM_Utils_Array
::value('source_contact_id', $params);
502 if (isset($params['assignee_contact_id'])) {
503 if (is_array($params['assignee_contact_id'])) {
504 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
507 $msgs[] = "assignee={$params['assignee_contact_id']}";
510 $logMsg .= implode(', ', $msgs);
512 self
::logActivityAction($result, $logMsg);
514 if (!empty($params['custom']) &&
515 is_array($params['custom'])
517 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
520 $transaction->commit();
521 if (empty($params['skipRecentView'])) {
522 $recentOther = array();
523 if (!empty($params['case_id'])) {
524 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
525 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
526 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
530 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home";
531 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
532 $url = CRM_Utils_System
::url('civicrm/activity', $q);
533 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
534 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
535 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
539 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
540 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
544 if (CRM_Core_Permission
::check("delete activities")) {
545 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
546 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
551 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
552 if (CRM_Core_Permission
::check('delete activities')) {
553 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
554 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
560 if (!isset($activity->parent_id
)) {
561 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
562 // add the recently created Activity
563 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
564 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
567 if (isset($activitySubject)) {
568 $title = $activitySubject . ' - ';
571 $title = $title . $recentContactDisplay;
572 if (!empty($activityTypes[$activity->activity_type_id
])) {
573 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
576 CRM_Utils_Recent
::add($title,
581 $recentContactDisplay,
587 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
589 if (!empty($params['id'])) {
590 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
593 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
596 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
598 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
599 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
601 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
603 'activity_id' => $activity->id
,
604 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
606 if ($caseParams['case_id']) {
607 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
610 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
618 * Create an activity.
620 * @todo elaborate on what this does.
622 * @param CRM_Core_DAO_Activity $activity
623 * @param string $logMessage
627 public static function logActivityAction($activity, $logMessage = NULL) {
628 $id = CRM_Core_Session
::getLoggedInContactID();
630 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
631 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
632 $id = self
::getActivityContact($activity->id
, $sourceID);
635 'entity_table' => 'civicrm_activity',
636 'entity_id' => $activity->id
,
637 'modified_id' => $id,
638 'modified_date' => date('YmdHis'),
639 'data' => $logMessage,
641 CRM_Core_BAO_Log
::add($logParams);
646 * Get the list Activities.
648 * @param array $params
649 * Array of parameters.
651 * - contact_id int contact_id whose activities we want to retrieve
652 * - offset int which row to start from ?
653 * - rowCount int how many rows to fetch
654 * - sort object|array object or array describing sort order for sql query.
655 * - admin boolean if contact is admin
656 * - caseId int case ID
657 * - context string page on which selector is build
658 * - activity_type_id int|string the activitiy types we want to restrict by
659 * @param bool $getCount
660 * Get count of the activities
663 * Relevant data object values of open activities
665 public static function getActivities($params, $getCount = FALSE) {
666 $activities = array();
668 // fetch all activity IDs whose target/assignee/source contact id is $params['contact_id']
669 // currently cannot be done via Activity.Get API so we are using SQL query instead
670 if (!empty($params['contact_id'])) {
671 $activityIDs = CRM_Core_DAO
::singleValueQuery("SELECT GROUP_CONCAT(DISTINCT activity_id SEPARATOR ',')
672 FROM civicrm_activity_contact
673 WHERE contact_id = %1", array(1 => array($params['contact_id'], 'Integer')));
675 // if no activities found for given $params['contact_id'] then return empty array
676 if (empty($activityIDs)) {
677 return $getCount ?
count($activities) : $activities;
679 $activityIDs = explode(',', $activityIDs);
682 // fetch all active activity types
683 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
685 // Activity.Get API params
686 $activityParams = array(
687 'id' => (!empty($activityIDs)) ?
array('IN' => $activityIDs) : NULL,
689 'is_current_revision' => 1,
692 'activity_date_time',
695 'source_contact_name',
696 'assignee_contact_id',
698 'target_contact_name',
699 'assignee_contact_name',
707 'check_permissions' => 1,
709 'offset' => CRM_Utils_Array
::value('offset', $params, 0),
713 if ($params['context'] != 'activity') {
714 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey(__CLASS__
, 'status_id', 'Scheduled');
717 // activity type ID clause
718 if (!empty($params['activity_type_id'])) {
719 if (is_array($params['activity_type_id'])) {
720 foreach ($params['activity_type_id'] as $idx => $value) {
721 $params['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
723 $activityParams['activity_type_id'] = array('IN' => $params['activity_type_id']);
726 $activityParams['activity_type_id'] = CRM_Utils_Type
::escape($params['activity_type_id'], 'Positive');
729 elseif (!empty($activityTypes) && count($activityTypes)) {
730 $activityParams['activity_type_id'] = array('IN' => array_keys($activityTypes));
733 $excludeActivityIDs = array();
734 if (!empty($params['activity_type_exclude_id'])) {
735 if (is_array($params['activity_type_exclude_id'])) {
736 foreach ($params['activity_type_exclude_id'] as $idx => $value) {
737 $excludeActivityIDs[$idx] = CRM_Utils_Type
::escape($value, 'Positive');
741 $excludeActivityIDs[] = CRM_Utils_Type
::escape($params['activity_type_exclude_id'], 'Positive');
745 if (!empty($params['rowCount']) &&
746 $params['rowCount'] > 0
748 $activityParams['options']['limit'] = $params['rowCount'];
750 // set limit = 0 if we need to fetch the activity count
752 $activityParams['options']['limit'] = 0;
755 if (!empty($params['sort'])) {
756 if (is_a($params['sort'], 'CRM_Utils_Sort')) {
757 $order = $params['sort']->orderBy();
759 elseif (trim($params['sort'])) {
760 $order = CRM_Utils_Type
::escape($params['sort'], 'String');
765 // context = 'activity' in Activities tab.
766 $activityParams['options']['sort'] = (CRM_Utils_Array
::value('context', $params) == 'activity') ?
"activity_date_time DESC" : "status_id ASC, activity_date_time ASC";
769 $activityParams['options']['sort'] = str_replace('activity_type ', 'activity_type_id.label ', $order);
773 // 1. we should use Activity.Getcount for fetching count only, but in order to check that
774 // current logged in user has permission to view Case activities we are performing filtering out those activities from list (see below).
775 // This logic need to be incorporated in Activity.get definition
776 $result = civicrm_api3('Activity', 'Get', $activityParams);
778 $enabledComponents = self
::activityComponents();
779 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
780 $bulkActivityTypeID = CRM_Core_PseudoConstant
::getKey(__CLASS__
, 'activity_type_id', 'Bulk Email');
782 // CRM-3553, need to check user has access to target groups.
783 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
784 $accessCiviMail = ((CRM_Core_Permission
::check('access CiviMail')) ||
785 (CRM_Mailing_Info
::workflowEnabled() && CRM_Core_Permission
::check('create mailings'))
788 $mappingParams = array(
789 'id' => 'activity_id',
790 'source_record_id' => 'source_record_id',
791 'activity_type_id' => 'activity_type_id',
792 'activity_date_time' => 'activity_date_time',
793 'status_id' => 'status_id',
794 'subject' => 'subject',
795 'campaign_id' => 'campaign_id',
796 'assignee_contact_name' => 'assignee_contact_name',
797 'target_contact_name' => 'target_contact_name',
798 'source_contact_id' => 'source_contact_id',
799 'source_contact_name' => 'source_contact_name',
800 'case_id' => 'case_id',
803 foreach ($result['values'] as $id => $activity) {
804 // skip case activities if CiviCase is not enabled OR those actvities which are
805 if ((!empty($activity['case_id']) && !in_array('CiviCase', $enabledComponents)) ||
806 (count($excludeActivityIDs) && in_array($activity['activity_type_id'], $excludeActivityIDs))
811 $activities[$id] = array();
813 // if count is needed, no need to populate the array list with attributes
818 $isBulkActivity = (!$bulkActivityTypeID ||
($bulkActivityTypeID != $activity['activity_type_id']));
819 foreach ($mappingParams as $apiKey => $expectedName) {
820 if (in_array($apiKey, array('assignee_contact_name', 'target_contact_name'))) {
821 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity, array());
822 if ($apiKey == 'target_contact_name' && count($activity['target_contact_name'])) {
823 $activities[$id]['target_contact_counter'] = count($activity['target_contact_name']);
826 if ($isBulkActivity) {
827 $activities[$id]['recipients'] = ts('(%1 recipients)', array(1 => count($activity['target_contact_name'])));
828 $activities[$id]['mailingId'] = FALSE;
829 if ($accessCiviMail &&
830 ($mailingIDs === TRUE ||
in_array($activity['source_record_id'], $mailingIDs))
832 $activities[$id]['mailingId'] = TRUE;
836 // case related fields
837 elseif ($apiKey == 'case_id' && !$isBulkActivity) {
838 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
840 // fetch case subject for case ID found
841 if (!empty($activity['case_id'])) {
842 $activities[$id]['case_subject'] = CRM_Core_DAO
::executeQuery('CRM_Case_DAO_Case', $activity['case_id'], 'subject');
846 $activities[$id][$expectedName] = CRM_Utils_Array
::value($apiKey, $activity);
847 if ($apiKey == 'activity_type_id') {
848 $activities[$id]['activity_type'] = CRM_Utils_Array
::value($activities[$id][$expectedName], $activityTypes);
850 elseif ($apiKey == 'campaign_id') {
851 $activities[$id]['campaign'] = CRM_Utils_Array
::value($activities[$id][$expectedName], $allCampaigns);
855 // if deleted, wrap in <del>
856 if (!empty($activity['source_contact_id']) &&
857 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $activity['source_contact_id'], 'is_deleted')
859 $activities[$id]['source_contact_name'] = sprintf("<del>%s<del>", $activity['source_contact_name']);
861 $activities[$id]['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getParentFor($id, 'civicrm_activity');
864 return $getCount ?
count($activities) : $activities;
868 * Get the component id and name if those are enabled and allowed.
870 * Checks whether logged in user has permission.
871 * To decide whether we are going to include
872 * component related activities with core activity retrieve process.
873 * (what did that just mean?)
876 * Array of component id and name.
878 public static function activityComponents() {
879 $components = array();
880 $compInfo = CRM_Core_Component
::getEnabledComponents();
881 foreach ($compInfo as $compObj) {
882 if (!empty($compObj->info
['showActivitiesInCore'])) {
883 if ($compObj->info
['name'] == 'CiviCampaign') {
884 $componentPermission = "administer {$compObj->name}";
887 $componentPermission = "access {$compObj->name}";
889 if ($compObj->info
['name'] == 'CiviCase') {
890 if (CRM_Case_BAO_Case
::accessCiviCase()) {
891 $components[$compObj->componentID
] = $compObj->info
['name'];
894 elseif (CRM_Core_Permission
::check($componentPermission)) {
895 $components[$compObj->componentID
] = $compObj->info
['name'];
904 * Send the message to all the contacts.
906 * Also insert a contact activity in each contacts record.
908 * @param array $contactDetails
909 * The array of contact details to send the email.
910 * @param string $subject
911 * The subject of the message.
914 * @param string $emailAddress
915 * Use this 'to' email address instead of the default Primary address.
917 * Use this userID if set.
918 * @param string $from
919 * @param array $attachments
920 * The array of attachments if any.
925 * @param array $contactIds
927 * @param string $additionalDetails
928 * The additional information of CC and BCC appended to the activity Details.
931 * ( sent, activityId) if any email is sent and activityId
933 public static function sendEmail(
945 $additionalDetails = NULL
947 // get the contact details of logged in contact, which we set as from email
948 if ($userID == NULL) {
949 $userID = CRM_Core_Session
::getLoggedInContactID();
952 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
954 return array(count($contactDetails), 0, count($contactDetails));
956 if (!trim($fromDisplayName)) {
957 $fromDisplayName = $fromEmail;
961 // token replacement of addressee/email/postal greetings
962 // get the tokens added in subject and message
963 $subjectToken = CRM_Utils_Token
::getTokens($subject);
964 $messageToken = CRM_Utils_Token
::getTokens($text);
965 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
966 $allTokens = array_merge($messageToken, $subjectToken);
969 $from = "$fromDisplayName <$fromEmail>";
972 //create the meta level record first ( email activity )
973 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
978 // CRM-6265: save both text and HTML parts in details (if present)
979 if ($html and $text) {
980 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
983 $details = $html ?
$html : $text;
984 $details .= $additionalDetails;
987 $activityParams = array(
988 'source_contact_id' => $userID,
989 'activity_type_id' => $activityTypeID,
990 'activity_date_time' => date('YmdHis'),
991 'subject' => $subject,
992 'details' => $details,
993 // FIXME: check for name Completed and get ID from that lookup
997 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
998 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1000 // add the attachments to activity params here
1002 // first process them
1003 $activityParams = array_merge($activityParams,
1008 $activity = self
::create($activityParams);
1010 // get the set of attachments from where they are stored
1011 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1014 $returnProperties = array();
1015 if (isset($messageToken['contact'])) {
1016 foreach ($messageToken['contact'] as $key => $value) {
1017 $returnProperties[$value] = 1;
1021 if (isset($subjectToken['contact'])) {
1022 foreach ($subjectToken['contact'] as $key => $value) {
1023 if (!isset($returnProperties[$value])) {
1024 $returnProperties[$value] = 1;
1029 // get token details for contacts, call only if tokens are used
1031 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1032 list($details) = CRM_Utils_Token
::getTokenDetails(
1037 'CRM_Activity_BAO_Activity'
1043 CRM_Utils_Hook
::tokens($tokens);
1044 $categories = array_keys($tokens);
1046 $escapeSmarty = FALSE;
1047 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1048 $smarty = CRM_Core_Smarty
::singleton();
1049 $escapeSmarty = TRUE;
1052 $sent = $notSent = array();
1053 foreach ($contactDetails as $values) {
1054 $contactId = $values['contact_id'];
1055 $emailAddress = $values['email'];
1057 if (!empty($details) && is_array($details["{$contactId}"])) {
1058 // unset email from details since it always returns primary email address
1059 unset($details["{$contactId}"]['email']);
1060 unset($details["{$contactId}"]['email_id']);
1061 $values = array_merge($values, $details["{$contactId}"]);
1064 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1065 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1068 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1069 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1070 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1076 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1077 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1078 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1084 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1085 // also add the contact tokens to the template
1086 $smarty->assign_by_ref('contact', $values);
1088 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1089 $tokenText = $smarty->fetch("string:$tokenText");
1090 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1094 if (self
::sendMessage(
1112 return array($sent, $activity->id
);
1118 * @param array $contactDetails
1119 * @param array $activityParams
1120 * @param array $smsParams
1121 * @param $contactIds
1122 * @param int $userID
1125 * @throws CRM_Core_Exception
1127 public static function sendSMS(
1130 &$smsParams = array(),
1134 if ($userID == NULL) {
1135 $userID = CRM_Core_Session
::getLoggedInContactID();
1138 $text = &$activityParams['sms_text_message'];
1141 // token replacement of addressee/email/postal greetings
1142 // get the tokens added in subject and message
1143 $messageToken = CRM_Utils_Token
::getTokens($text);
1145 // Create the meta level record first ( sms activity )
1146 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1153 $activitySubject = $activityParams['activity_subject'];
1154 $activityParams = array(
1155 'source_contact_id' => $userID,
1156 'activity_type_id' => $activityTypeID,
1157 'activity_date_time' => date('YmdHis'),
1158 'subject' => $activitySubject,
1159 'details' => $details,
1160 // FIXME: check for name Completed and get ID from that lookup
1164 $activity = self
::create($activityParams);
1165 $activityID = $activity->id
;
1167 $returnProperties = array();
1169 if (isset($messageToken['contact'])) {
1170 foreach ($messageToken['contact'] as $key => $value) {
1171 $returnProperties[$value] = 1;
1177 CRM_Utils_Hook
::tokens($tokens);
1178 $categories = array_keys($tokens);
1180 // get token details for contacts, call only if tokens are used
1182 if (!empty($returnProperties) ||
!empty($tokens)) {
1183 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1187 'CRM_Activity_BAO_Activity'
1192 $escapeSmarty = FALSE;
1194 foreach ($contactDetails as $values) {
1195 $contactId = $values['contact_id'];
1197 if (!empty($details) && is_array($details["{$contactId}"])) {
1198 // unset phone from details since it always returns primary number
1199 unset($details["{$contactId}"]['phone']);
1200 unset($details["{$contactId}"]['phone_type_id']);
1201 $values = array_merge($values, $details["{$contactId}"]);
1204 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1205 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1207 // Only send if the phone is of type mobile
1208 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1209 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1210 $smsParams['To'] = $values['phone'];
1213 $smsParams['To'] = '';
1216 $sendResult = self
::sendSMSMessage(
1224 if (PEAR
::isError($sendResult)) {
1225 // Collect all of the PEAR_Error objects
1226 $errMsgs[] = $sendResult;
1233 // If at least one message was sent and no errors
1234 // were generated then return a boolean value of TRUE.
1235 // Otherwise, return FALSE (no messages sent) or
1236 // and array of 1 or more PEAR_Error objects.
1238 if ($success > 0 && count($errMsgs) == 0) {
1241 elseif (count($errMsgs) > 0) {
1245 return array($sent, $activity->id
, $success);
1249 * Send the sms message to a specific contact.
1252 * The contact id of the recipient.
1254 * @param array $smsParams
1255 * The params used for sending sms.
1256 * @param int $activityID
1257 * The activity ID that tracks the message.
1258 * @param int $userID
1260 * @return bool|PEAR_Error
1261 * true on success or PEAR_Error object
1263 public static function sendSMSMessage(
1266 $smsParams = array(),
1271 $toPhoneNumber = "";
1273 if ($smsParams['To']) {
1274 $toPhoneNumber = trim($smsParams['To']);
1277 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1278 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1279 // To get primary mobile phonenumber,if not get the first mobile phonenumber
1280 if (!empty($toPhoneNumbers)) {
1281 $toPhoneNumerDetails = reset($toPhoneNumbers);
1282 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1283 // Contact allows to send sms
1288 // make sure both phone are valid
1289 // and that the recipient wants to receive sms
1290 if (empty($toPhoneNumber) or $toDoNotSms) {
1291 return PEAR
::raiseError(
1292 'Recipient phone number is invalid or recipient does not want to receive SMS',
1298 $recipient = $smsParams['To'];
1299 $smsParams['contact_id'] = $toID;
1300 $smsParams['parent_activity_id'] = $activityID;
1302 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1303 $sendResult = $providerObj->send($recipient, $smsParams, $tokenText, NULL, $userID);
1304 if (PEAR
::isError($sendResult)) {
1308 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1309 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1311 // add activity target record for every sms that is send
1312 $activityTargetParams = array(
1313 'activity_id' => $activityID,
1314 'contact_id' => $toID,
1315 'record_type_id' => $targetID,
1317 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1323 * Send the message to a specific contact.
1325 * @param string $from
1326 * The name and email of the sender.
1327 * @param int $fromID
1329 * The contact id of the recipient.
1330 * @param string $subject
1331 * The subject of the message.
1332 * @param $text_message
1333 * @param $html_message
1334 * @param string $emailAddress
1335 * Use this 'to' email address instead of the default Primary address.
1336 * @param int $activityID
1337 * The activity ID that tracks the message.
1338 * @param null $attachments
1343 * TRUE if successful else FALSE.
1345 public static function sendMessage(
1354 $attachments = NULL,
1358 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1359 if ($emailAddress) {
1360 $toEmail = trim($emailAddress);
1363 // make sure both email addresses are valid
1364 // and that the recipient wants to receive email
1365 if (empty($toEmail) or $toDoNotEmail) {
1368 if (!trim($toDisplayName)) {
1369 $toDisplayName = $toEmail;
1372 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1373 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1375 // create the params array
1376 $mailParams = array(
1377 'groupName' => 'Activity Email Sender',
1379 'toName' => $toDisplayName,
1380 'toEmail' => $toEmail,
1381 'subject' => $subject,
1384 'text' => $text_message,
1385 'html' => $html_message,
1386 'attachments' => $attachments,
1389 if (!CRM_Utils_Mail
::send($mailParams)) {
1393 // add activity target record for every mail that is send
1394 $activityTargetParams = array(
1395 'activity_id' => $activityID,
1396 'contact_id' => $toID,
1397 'record_type_id' => $targetID,
1399 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1404 * Combine all the importable fields from the lower levels object.
1406 * The ordering is important, since currently we do not have a weight
1407 * scheme. Adding weight is super important and should be done in the
1408 * next week or so, before this can be called complete.
1410 * @param bool $status
1413 * array of importable Fields
1415 public static function &importableFields($status = FALSE) {
1416 if (!self
::$_importableFields) {
1417 if (!self
::$_importableFields) {
1418 self
::$_importableFields = array();
1421 $fields = array('' => array('title' => ts('- do not import -')));
1424 $fields = array('' => array('title' => ts('- Activity Fields -')));
1427 $tmpFields = CRM_Activity_DAO_Activity
::import();
1428 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1430 // Using new Dedupe rule.
1431 $ruleParams = array(
1432 'contact_type' => 'Individual',
1433 'used' => 'Unsupervised',
1435 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1437 $tmpConatctField = array();
1438 if (is_array($fieldsArray)) {
1439 foreach ($fieldsArray as $value) {
1440 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1445 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1446 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1447 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1450 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1451 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1452 $fields = array_merge($fields, $tmpConatctField);
1453 $fields = array_merge($fields, $tmpFields);
1454 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1455 self
::$_importableFields = $fields;
1457 return self
::$_importableFields;
1461 * Get the Activities of a target contact.
1463 * @param int $contactId
1464 * Id of the contact whose activities need to find.
1467 * array of activity fields
1469 public static function getContactActivity($contactId) {
1470 $activities = array();
1471 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1472 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1473 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1474 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1476 // First look for activities where contactId is one of the targets
1478 SELECT activity_id, record_type_id
1479 FROM civicrm_activity_contact
1480 WHERE contact_id = $contactId
1482 $dao = CRM_Core_DAO
::executeQuery($query);
1483 while ($dao->fetch()) {
1484 if ($dao->record_type_id
== $targetID) {
1485 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1487 elseif ($dao->record_type_id
== $assigneeID) {
1488 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1491 // do source stuff here
1492 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1496 $activityIds = array_keys($activities);
1497 if (count($activityIds) < 1) {
1501 $activityIds = implode(',', $activityIds);
1503 SELECT activity.id as activity_id,
1505 subject, location, activity_date_time, details, status_id
1506 FROM civicrm_activity activity
1507 WHERE activity.id IN ($activityIds)";
1509 $dao = CRM_Core_DAO
::executeQuery($query);
1511 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1512 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1514 while ($dao->fetch()) {
1515 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1516 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1517 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1518 $activities[$dao->activity_id
]['location'] = $dao->location
;
1519 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1520 $activities[$dao->activity_id
]['details'] = $dao->details
;
1521 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1522 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1523 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1525 // set to null if not set
1526 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1527 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1534 * Add activity for Membership/Event/Contribution.
1536 * @param object $activity
1537 * (reference) particular component object.
1538 * @param string $activityType
1539 * For Membership Signup or Renewal.
1540 * @param int $targetContactID
1544 public static function addActivity(
1546 $activityType = 'Membership Signup',
1547 $targetContactID = NULL
1549 if ($activity->__table
== 'civicrm_membership') {
1550 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1552 if (!$membershipType) {
1553 $membershipType = ts('Membership');
1556 $subject = "{$membershipType}";
1558 if (!empty($activity->source
) && $activity->source
!= 'null') {
1559 $subject .= " - {$activity->source}";
1562 if ($activity->owner_membership_id
) {
1565 FROM civicrm_contact, civicrm_membership
1566 WHERE civicrm_contact.id = civicrm_membership.contact_id
1567 AND civicrm_membership.id = $activity->owner_membership_id
1569 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1570 $subject .= " (by {$displayName})";
1573 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
, 'label');
1574 // CRM-72097 changed from start date to today
1575 $date = date('YmdHis');
1576 $component = 'Membership';
1578 elseif ($activity->__table
== 'civicrm_participant') {
1579 $event = CRM_Event_BAO_Event
::getEvents(1, $activity->event_id
, TRUE, FALSE);
1581 $roles = CRM_Event_PseudoConstant
::participantRole();
1582 $status = CRM_Event_PseudoConstant
::participantStatus();
1584 $subject = $event[$activity->event_id
];
1585 if (!empty($roles[$activity->role_id
])) {
1586 $subject .= ' - ' . $roles[$activity->role_id
];
1588 if (!empty($status[$activity->status_id
])) {
1589 $subject .= ' - ' . $status[$activity->status_id
];
1591 $date = date('YmdHis');
1592 if ($activityType != 'Email') {
1593 $activityType = 'Event Registration';
1595 $component = 'Event';
1597 elseif ($activity->__table
== 'civicrm_contribution') {
1598 // create activity record only for Completed Contributions
1599 if ($activity->contribution_status_id
!= 1) {
1605 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1606 if (!empty($activity->source
) && $activity->source
!= 'null') {
1607 $subject .= " - {$activity->source}";
1609 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1610 $activityType = $component = 'Contribution';
1612 $activityParams = array(
1613 'source_contact_id' => $activity->contact_id
,
1614 'source_record_id' => $activity->id
,
1615 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1619 'subject' => $subject,
1620 'activity_date_time' => $date,
1621 'is_test' => $activity->is_test
,
1622 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1626 'skipRecentView' => TRUE,
1627 'campaign_id' => $activity->campaign_id
,
1630 if (!empty($activity->activity_id
)) {
1631 $activityParams['id'] = $activity->activity_id
;
1633 // create activity with target contacts
1634 $id = CRM_Core_Session
::getLoggedInContactID();
1636 $activityParams['source_contact_id'] = $id;
1637 $activityParams['target_contact_id'][] = $activity->contact_id
;
1641 if (property_exists($activity, 'details')) {
1642 $activityParams['details'] = $activity->details
;
1645 if ($targetContactID) {
1646 $activityParams['target_contact_id'][] = $targetContactID;
1648 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1649 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1655 * Get Parent activity for currently viewed activity.
1657 * @param int $activityId
1658 * Current activity id.
1661 * Id of parent activity otherwise false.
1663 public static function getParentActivity($activityId) {
1664 static $parentActivities = array();
1666 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1668 if (!array_key_exists($activityId, $parentActivities)) {
1669 $parentActivities[$activityId] = array();
1671 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1676 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1679 return $parentActivities[$activityId];
1683 * Get total count of prior revision of currently viewed activity.
1685 * @param $activityID
1686 * Current activity id.
1689 * $params count of prior activities otherwise false.
1691 public static function getPriorCount($activityID) {
1692 static $priorCounts = array();
1694 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1696 if (!array_key_exists($activityID, $priorCounts)) {
1697 $priorCounts[$activityID] = array();
1698 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1705 SELECT count( id ) AS cnt
1706 FROM civicrm_activity
1707 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1708 AND is_current_revision = 0
1709 AND id < {$activityID}
1711 $params = array(1 => array($originalID, 'Integer'));
1712 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1714 $priorCounts[$activityID] = $count ?
$count : 0;
1717 return $priorCounts[$activityID];
1721 * Get all prior activities of currently viewed activity.
1723 * @param $activityID
1724 * Current activity id.
1725 * @param bool $onlyPriorRevisions
1728 * prior activities info.
1730 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1731 static $priorActivities = array();
1733 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1734 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1736 if (!array_key_exists($index, $priorActivities)) {
1737 $priorActivities[$index] = array();
1739 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1744 $originalID = $activityID;
1748 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1749 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1750 WHERE (ca.id = %1 OR ca.original_id = %1)
1751 AND cl.entity_table = 'civicrm_activity'
1752 AND cl.entity_id = ca.id
1753 AND cl.modified_id = c.id
1755 if ($onlyPriorRevisions) {
1756 $query .= " AND ca.id < {$activityID}";
1758 $query .= " ORDER BY ca.id DESC";
1760 $params = array(1 => array($originalID, 'Integer'));
1761 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1763 while ($dao->fetch()) {
1764 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1765 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1766 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1771 return $priorActivities[$index];
1775 * Find the latest revision of a given activity.
1777 * @param int $activityID
1778 * Prior activity id.
1781 * current activity id.
1783 public static function getLatestActivityId($activityID) {
1784 static $latestActivityIds = array();
1786 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1788 if (!array_key_exists($activityID, $latestActivityIds)) {
1789 $latestActivityIds[$activityID] = array();
1791 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1796 $activityID = $originalID;
1798 $params = array(1 => array($activityID, 'Integer'));
1799 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1801 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
1804 return $latestActivityIds[$activityID];
1808 * Create a follow up a given activity.
1810 * @param int $activityId
1811 * activity id of parent activity.
1812 * @param array $params
1814 * @return CRM_Activity_BAO_Activity|null|object
1816 public static function createFollowupActivity($activityId, $params) {
1821 $followupParams = array();
1822 $followupParams['parent_id'] = $activityId;
1823 $followupParams['source_contact_id'] = CRM_Core_Session
::getLoggedInContactID();
1824 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
1826 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1827 // Get Subject of Follow-up Activiity, CRM-4491
1828 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
1829 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
1831 // Create target contact for followup.
1832 if (!empty($params['target_contact_id'])) {
1833 $followupParams['target_contact_id'] = $params['target_contact_id'];
1836 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
1837 $params['followup_date_time']
1839 $followupActivity = self
::create($followupParams);
1841 return $followupActivity;
1845 * Get Activity specific File according activity type Id.
1847 * @param int $activityTypeId
1849 * @param string $crmDir
1851 * @return string|bool
1852 * if file exists returns $activityTypeFile activity filename otherwise false.
1854 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
1855 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1857 if ($activityTypes[$activityTypeId]['name']) {
1858 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
1864 global $civicrm_root;
1865 $config = CRM_Core_Config
::singleton();
1866 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
1867 if (empty($config->customPHPPathDir
)) {
1870 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
1875 return $activityTypeFile;
1879 * Restore the activity.
1881 * @param array $params
1883 * @return CRM_Activity_DAO_Activity
1885 public static function restoreActivity(&$params) {
1886 $activity = new CRM_Activity_DAO_Activity();
1887 $activity->copyValues($params);
1889 $activity->is_deleted
= 0;
1890 $result = $activity->save();
1896 * Get the exportable fields for Activities.
1898 * @param string $name
1899 * If it is called by case $name = Case else $name = Activity.
1902 * array of exportable Fields
1904 public static function &exportableFields($name = 'Activity') {
1905 if (!isset(self
::$_exportableFields[$name])) {
1906 self
::$_exportableFields[$name] = array();
1908 // TODO: ideally we should retrieve all fields from xml, in this case since activity processing is done
1909 // my case hence we have defined fields as case_*
1910 if ($name == 'Activity') {
1911 $exportableFields = CRM_Activity_DAO_Activity
::export();
1912 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
1913 $exportableFields['source_contact'] = array(
1914 'title' => ts('Source Contact'),
1915 'type' => CRM_Utils_Type
::T_STRING
,
1918 $Activityfields = array(
1919 'activity_type' => array(
1920 'title' => ts('Activity Type'),
1921 'name' => 'activity_type',
1922 'type' => CRM_Utils_Type
::T_STRING
,
1923 'searchByLabel' => TRUE,
1925 'activity_status' => array(
1926 'title' => ts('Activity Status'),
1927 'name' => 'activity_status',
1928 'type' => CRM_Utils_Type
::T_STRING
,
1929 'searchByLabel' => TRUE,
1931 'activity_priority' => array(
1932 'title' => ts('Activity Priority'),
1933 'name' => 'activity_priority',
1934 'type' => CRM_Utils_Type
::T_STRING
,
1935 'searchByLabel' => TRUE,
1938 $fields = array_merge($Activityfields, $exportableFields);
1941 // Set title to activity fields.
1943 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
1944 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
1945 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
1946 'case_scheduled_activity_date' => array(
1947 'title' => ts('Activity Scheduled Date'),
1948 'type' => CRM_Utils_Type
::T_DATE
,
1950 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
1951 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
1952 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
1953 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
1954 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
1955 'case_activity_is_auto' => array(
1956 'title' => ts('Activity Auto-generated?'),
1957 'type' => CRM_Utils_Type
::T_BOOLEAN
,
1962 // add custom data for case activities
1963 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1965 self
::$_exportableFields[$name] = $fields;
1967 return self
::$_exportableFields[$name];
1971 * Get the allowed profile fields for Activities.
1974 * array of activity profile Fields
1976 public static function getProfileFields() {
1977 $exportableFields = self
::exportableFields('Activity');
1978 $skipFields = array(
1981 'source_contact_id',
1983 'activity_campaign',
1985 'is_current_revision',
1986 'activity_is_deleted',
1988 $config = CRM_Core_Config
::singleton();
1989 if (!in_array('CiviCampaign', $config->enableComponents
)) {
1990 $skipFields[] = 'activity_engagement_level';
1993 foreach ($skipFields as $field) {
1994 if (isset($exportableFields[$field])) {
1995 unset($exportableFields[$field]);
1999 // hack to use 'activity_type_id' instead of 'activity_type'
2000 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2001 unset($exportableFields['activity_status']);
2003 return $exportableFields;
2007 * This function deletes the activity record related to contact record.
2009 * This is conditional on there being no target and assignee record
2010 * with other contacts.
2012 * @param int $contactId
2017 public static function cleanupActivity($contactId) {
2022 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2023 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2025 $transaction = new CRM_Core_Transaction();
2027 // delete activity if there is no record in civicrm_activity_contact
2028 // pointing to any other contact record
2029 $activityContact = new CRM_Activity_DAO_ActivityContact();
2030 $activityContact->contact_id
= $contactId;
2031 $activityContact->record_type_id
= $sourceID;
2032 $activityContact->find();
2034 while ($activityContact->fetch()) {
2035 // delete activity_contact record for the deleted contact
2036 $activityContact->delete();
2038 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2039 $activityContactOther->activity_id
= $activityContact->activity_id
;
2041 // delete activity only if no other contacts connected
2042 if (!$activityContactOther->find(TRUE)) {
2043 $activityParams = array('id' => $activityContact->activity_id
);
2044 $result = self
::deleteActivity($activityParams);
2047 $activityContactOther->free();
2050 $activityContact->free();
2051 $transaction->commit();
2057 * Does user has sufficient permission for view/edit activity record.
2059 * @param int $activityId
2060 * Activity record id.
2061 * @param int $action
2066 public static function checkPermission($activityId, $action) {
2069 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2074 $activity = new CRM_Activity_DAO_Activity();
2075 $activity->id
= $activityId;
2076 if (!$activity->find(TRUE)) {
2080 // Component related permissions.
2081 $compPermissions = array(
2082 'CiviCase' => array(
2083 'administer CiviCase',
2084 'access my cases and activities',
2085 'access all cases and activities',
2087 'CiviMail' => array('access CiviMail'),
2088 'CiviEvent' => array('access CiviEvent'),
2089 'CiviGrant' => array('access CiviGrant'),
2090 'CiviPledge' => array('access CiviPledge'),
2091 'CiviMember' => array('access CiviMember'),
2092 'CiviReport' => array('access CiviReport'),
2093 'CiviContribute' => array('access CiviContribute'),
2094 'CiviCampaign' => array('administer CiviCampaign'),
2097 // Return early when it is case activity.
2098 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2099 // Check for civicase related permission.
2100 if ($isCaseActivity) {
2102 foreach ($compPermissions['CiviCase'] as $per) {
2103 if (CRM_Core_Permission
::check($per)) {
2109 // Check for case specific permissions.
2112 if ($action == CRM_Core_Action
::UPDATE
) {
2115 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2117 $activity->activity_type_id
2124 // First check the component permission.
2127 FROM civicrm_option_value val
2128 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2129 WHERE val.value = %2";
2131 1 => array('activity_type', 'String'),
2132 2 => array($activity->activity_type_id
, 'Integer'),
2134 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2137 $componentName = CRM_Core_Component
::getComponentName($componentId);
2138 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2140 // Here we are interesting in any single permission.
2141 if (is_array($compPermission)) {
2142 foreach ($compPermission as $per) {
2143 if (CRM_Core_Permission
::check($per)) {
2151 // Check for this permission related to contact.
2152 $permission = CRM_Core_Permission
::VIEW
;
2153 if ($action == CRM_Core_Action
::UPDATE
) {
2154 $permission = CRM_Core_Permission
::EDIT
;
2157 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2158 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2159 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2160 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2162 // Check for source contact.
2163 if (!$componentId ||
$allow) {
2164 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2165 // Account for possibility of activity not having a source contact (as it may have been deleted).
2166 $allow = $sourceContactId ? CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission) : TRUE;
2169 // Check for target and assignee contacts.
2171 // First check for supper permission.
2172 $supPermission = 'view all contacts';
2173 if ($action == CRM_Core_Action
::UPDATE
) {
2174 $supPermission = 'edit all contacts';
2176 $allow = CRM_Core_Permission
::check($supPermission);
2178 // User might have sufficient permission, through acls.
2181 // Get the target contacts.
2182 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2183 foreach ($targetContacts as $cnt => $contactId) {
2184 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2190 // Get the assignee contacts.
2192 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2193 foreach ($assigneeContacts as $cnt => $contactId) {
2194 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2207 * Wrapper for ajax activity selector.
2209 * @param array $params
2210 * Associated array for params record id.
2213 * Associated array of contact activities
2215 public static function getContactActivitySelector(&$params) {
2216 // Format the params.
2217 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2218 $params['rowCount'] = $params['rp'];
2219 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2220 $params['caseId'] = NULL;
2221 $context = CRM_Utils_Array
::value('context', $params);
2222 $showContactOverlay = !CRM_Utils_String
::startsWith($context, "dashlet");
2223 $activityTypeInfo = civicrm_api3('OptionValue', 'get', array(
2224 'option_group_id' => "activity_type",
2225 'options' => array('limit' => 0),
2227 $activityIcons = array();
2228 foreach ($activityTypeInfo['values'] as $type) {
2229 if (!empty($type['icon'])) {
2230 $activityIcons[$type['value']] = $type['icon'];
2234 // Get contact activities.
2235 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2238 $params['total'] = count($activities);
2240 // Format params and add links.
2241 $contactActivities = array();
2243 if (!empty($activities)) {
2244 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2246 // Check logged in user for permission.
2247 $page = new CRM_Core_Page();
2248 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2249 $permissions = array($page->_permission
);
2250 if (CRM_Core_Permission
::check('delete activities')) {
2251 $permissions[] = CRM_Core_Permission
::DELETE
;
2254 $mask = CRM_Core_Action
::mask($permissions);
2256 foreach ($activities as $activityId => $values) {
2257 $activity = array();
2258 $activity['DT_RowId'] = $activityId;
2259 // Add class to this row if overdue.
2260 $activity['DT_RowClass'] = "crm-entity status-id-{$values['status_id']}";
2261 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2262 && CRM_Utils_Array
::value('status_id', $values) == 1
2264 $activity['DT_RowClass'] .= ' status-overdue';
2267 $activity['DT_RowClass'] .= ' status-ontime';
2270 $activity['DT_RowAttr'] = array();
2271 $activity['DT_RowAttr']['data-entity'] = 'activity';
2272 $activity['DT_RowAttr']['data-id'] = $activityId;
2274 $activity['activity_type'] = (!empty($activityIcons[$values['activity_type_id']]) ?
'<span class="crm-i ' . $activityIcons[$values['activity_type_id']] . '"></span> ' : '') . $values['activity_type'];
2275 $activity['subject'] = $values['subject'];
2277 $activity['source_contact_name'] = '';
2278 if ($params['contact_id'] == $values['source_contact_id']) {
2279 $activity['source_contact_name'] = $values['source_contact_name'];
2281 elseif ($values['source_contact_id']) {
2283 if ($showContactOverlay) {
2284 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2285 CRM_Contact_BAO_Contact
::getContactType($values['source_contact_id']),
2287 $values['source_contact_id']);
2289 $activity['source_contact_name'] = $srcTypeImage . CRM_Utils_System
::href($values['source_contact_name'],
2290 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2293 $activity['source_contact_name'] = '<em>n/a</em>';
2296 $activity['target_contact_name'] = '';
2297 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2298 $activity['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2299 'civicrm/mailing/report/event',
2300 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2302 elseif (!empty($values['recipients'])) {
2303 $activity['target_contact_name'] = $values['recipients'];
2305 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2306 $activity['target_contact_name'] = '';
2307 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2308 $targetTypeImage = "";
2309 $targetLink = CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2310 if ($showContactOverlay) {
2311 $targetTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2312 CRM_Contact_BAO_Contact
::getContactType($tcID),
2315 $activity['target_contact_name'] .= "<div>$targetTypeImage $targetLink";
2318 $activity['target_contact_name'] .= $targetLink;
2322 if ($extraCount = $values['target_contact_counter'] - 1) {
2323 $activity['target_contact_name'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2325 if ($showContactOverlay) {
2326 $activity['target_contact_name'] .= "</div> ";
2329 elseif (!$values['target_contact_name']) {
2330 $activity['target_contact_name'] = '<em>n/a</em>';
2333 $activity['assignee_contact_name'] = '';
2334 if (empty($values['assignee_contact_name'])) {
2335 $activity['assignee_contact_name'] = '<em>n/a</em>';
2337 elseif (!empty($values['assignee_contact_name'])) {
2339 $activity['assignee_contact_name'] = '';
2340 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2341 if ($acID && $count < 5) {
2342 $assigneeTypeImage = "";
2343 $assigneeLink = CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2344 if ($showContactOverlay) {
2345 $assigneeTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage(
2346 CRM_Contact_BAO_Contact
::getContactType($acID),
2349 $activity['assignee_contact_name'] .= "<div>$assigneeTypeImage $assigneeLink";
2352 $activity['assignee_contact_name'] .= $assigneeLink;
2357 $activity['assignee_contact_name'] .= "; ";
2359 if ($showContactOverlay) {
2360 $activity['assignee_contact_name'] .= "</div> ";
2364 $activity['assignee_contact_name'] .= "(" . ts('more') . ")";
2371 $activity['activity_date_time'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2372 $activity['status_id'] = $activityStatus[$values['status_id']];
2375 $activity['links'] = '';
2376 $accessMailingReport = FALSE;
2377 if (!empty($values['mailingId'])) {
2378 $accessMailingReport = TRUE;
2381 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2382 CRM_Utils_Array
::value('activity_type_id', $values),
2383 CRM_Utils_Array
::value('source_record_id', $values),
2384 $accessMailingReport,
2385 CRM_Utils_Array
::value('activity_id', $values)
2388 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2390 $activity['links'] = CRM_Core_Action
::formLink($actionLinks,
2393 'id' => $values['activity_id'],
2394 'cid' => $params['contact_id'],
2396 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2402 $values['activity_id']
2405 if ($values['is_recurring_activity']) {
2406 $activity['is_recurring_activity'] = CRM_Core_BAO_RecurringEntity
::getPositionAndCount($values['activity_id'], 'civicrm_activity');
2409 array_push($contactActivities, $activity);
2413 $activitiesDT = array();
2414 $activitiesDT['data'] = $contactActivities;
2415 $activitiesDT['recordsTotal'] = $params['total'];
2416 $activitiesDT['recordsFiltered'] = $params['total'];
2418 return $activitiesDT;
2422 * Copy custom fields and attachments from an existing activity to another.
2424 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2426 * @param array $params
2428 public static function copyExtendedActivityData($params) {
2429 // attach custom data to the new activity
2430 $customParams = $htmlType = array();
2431 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2433 if (!empty($customValues)) {
2434 $fieldIds = implode(', ', array_keys($customValues));
2435 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2436 $result = CRM_Core_DAO
::executeQuery($sql);
2438 while ($result->fetch()) {
2439 $htmlType[] = $result->id
;
2442 foreach ($customValues as $key => $value) {
2443 if ($value !== NULL) {
2445 if (in_array($key, $htmlType)) {
2446 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2447 $customParams["custom_{$key}_-1"] = array(
2448 'name' => $fileValues[0],
2449 'path' => $fileValues[1],
2453 $customParams["custom_{$key}_-1"] = $value;
2457 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, 'civicrm_activity',
2458 $params['mainActivityId'], 'Activity'
2462 // copy activity attachments ( if any )
2463 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2467 * Get activity contact.
2469 * @param int $activityId
2470 * @param int $recordTypeID
2471 * @param string $column
2475 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2476 $activityContact = new CRM_Activity_BAO_ActivityContact();
2477 $activityContact->activity_id
= $activityId;
2478 if ($recordTypeID) {
2479 $activityContact->record_type_id
= $recordTypeID;
2481 if ($activityContact->find(TRUE)) {
2482 return $activityContact->$column;
2488 * Get source contact id.
2490 * @param int $activityId
2494 public static function getSourceContactID($activityId) {
2495 static $sourceID = NULL;
2497 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2498 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2501 return self
::getActivityContact($activityId, $sourceID);
2507 * @todo Document what this is for.
2509 * @param array $params
2511 public function setApiFilter(&$params) {
2512 if (!empty($params['target_contact_id'])) {
2514 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2515 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2516 $obj = new CRM_Activity_BAO_ActivityContact();
2517 $params['return.target_contact_id'] = 1;
2518 $this->joinAdd($obj, 'LEFT');
2519 $this->selectAdd('civicrm_activity.*');
2520 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");
2525 * Send activity as attachment.
2527 * @param object $activity
2528 * @param array $mailToContacts
2529 * @param array $params
2533 public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
2534 if (!CRM_Utils_Array
::crmIsEmptyArray($mailToContacts)) {
2535 $clientID = CRM_Utils_Array
::value('client_id', $params);
2536 $caseID = CRM_Utils_Array
::value('case_id', $params);
2538 $ics = new CRM_Activity_BAO_ICalendar($activity);
2539 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity', $activity->id
);
2540 $ics->addAttachment($attachments, $mailToContacts);
2542 $result = CRM_Case_BAO_Case
::sendActivityCopy($clientID, $activity->id
, $mailToContacts, $attachments, $caseID);