3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class is for activity functions
40 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
43 * Static field for all the activity information that we can potentially export
47 static $_exportableFields = NULL;
50 * Static field for all the activity information that we can potentially import
54 static $_importableFields = NULL;
57 * Check if there is absolute minimum of data to add the object
59 * @param array $params
60 * (reference ) an assoc array of name/value pairs.
64 public static function dataExists(&$params) {
65 if (!empty($params['source_contact_id']) ||
!empty($params['id'])) {
72 * Fetch object based on array of properties
74 * @param array $params
75 * (reference ) an assoc array of name/value pairs.
76 * @param array $defaults
77 * (reference ) an assoc array to hold the flattened values.
79 * @return CRM_Activity_DAO_Activity
81 public static function retrieve(&$params, &$defaults) {
82 $activity = new CRM_Activity_DAO_Activity();
83 $activity->copyValues($params);
85 if ($activity->find(TRUE)) {
86 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
87 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
88 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
89 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
91 // TODO: at some stage we'll have to deal
92 // TODO: with multiple values for assignees and targets, but
93 // TODO: for now, let's just fetch first row
94 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
95 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
96 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
97 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
98 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
99 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
100 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
101 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
103 elseif (CRM_Core_Permission
::check('access CiviMail') ||
104 (CRM_Mailing_Info
::workflowEnabled() &&
105 CRM_Core_Permission
::check('create mailings')
108 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
109 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
113 $defaults['target_contact_value'] = ts('(recipients)');
116 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
117 $defaults['source_contact_id'] = $sourceContactId;
119 if ($sourceContactId &&
120 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
125 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
132 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
134 CRM_Core_DAO
::storeValues($activity, $defaults);
142 * Delete the activity
144 * @param array $params
145 * @param bool $moveToTrash
149 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
151 if (!empty($params['id']) && !is_array($params['id'])) {
152 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
155 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
158 $transaction = new CRM_Core_Transaction();
159 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
160 $sourceRecordIds = implode(',', $params['source_record_id']);
163 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
168 if (!isset($params['id'])) {
169 if (is_array($params['activity_type_id'])) {
170 $activityTypes = implode(',', $params['activity_type_id']);
173 $activityTypes = $params['activity_type_id'];
176 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
177 $dao = CRM_Core_DAO
::executeQuery($query);
180 $activity = new CRM_Activity_DAO_Activity();
181 $activity->copyValues($params);
182 $result = $activity->delete();
185 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
187 // CRM-13994 delete activity entity_tag
188 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
189 $dao = CRM_Core_DAO
::executeQuery($query);
193 $activity = new CRM_Activity_DAO_Activity();
194 $activity->copyValues($params);
196 $activity->is_deleted
= 1;
197 $result = $activity->save();
199 // CRM-4525 log activity delete
200 $logMsg = 'Case Activity deleted for';
203 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
204 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
205 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
206 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
207 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
208 if ($sourceContactId) {
209 $msgs[] = " source={$sourceContactId}";
212 //get target contacts.
213 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
214 if (!empty($targetContactIds)) {
215 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
217 //get assignee contacts.
218 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
219 if (!empty($assigneeContactIds)) {
220 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
223 $logMsg .= implode(', ', $msgs);
225 self
::logActivityAction($activity, $logMsg);
228 // delete the recently created Activity
230 $activityRecent = array(
231 'id' => $activity->id
,
232 'type' => 'Activity',
234 CRM_Utils_Recent
::del($activityRecent);
237 $transaction->commit();
238 if (isset($activity)) {
240 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
241 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
248 * Delete activity assignment record
250 * @param int $activityId
251 * @param int $recordTypeID
253 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
254 $activityContact = new CRM_Activity_BAO_ActivityContact();
255 $activityContact->activity_id
= $activityId;
257 $activityContact->record_type_id
= $recordTypeID;
259 $activityContact->delete();
263 * Process the activities
265 * @param array $params
266 * Associated array of the submitted values.
268 * @throws CRM_Core_Exception
270 * @return CRM_Activity_BAO_Activity|null|object
272 public static function create(&$params) {
273 // check required params
274 if (!self
::dataExists($params)) {
275 throw new CRM_Core_Exception('Not enough data to create activity object');
278 $activity = new CRM_Activity_DAO_Activity();
280 if (isset($params['id']) && empty($params['id'])) {
281 unset($params['id']);
284 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
285 if (isset($params['activity_date_time']) &&
286 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
288 $params['status_id'] = 2;
291 $params['status_id'] = 1;
295 //set priority to Normal for Auto-populated activities (for Cases)
296 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
297 // if not set and not 0
298 !CRM_Utils_Array
::value('id', $params)
300 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
301 $params['priority_id'] = array_search('Normal', $priority);
304 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
305 $params['target_contact_id'] = array_unique($params['target_contact_id']);
307 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
308 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
312 if (!empty($params['id'])) {
313 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
316 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
319 $activity->copyValues($params);
320 if (isset($params['case_id'])) {
321 // CRM-8708, preserve case ID even though it's not part of the SQL model
322 $activity->case_id
= $params['case_id'];
324 elseif (is_numeric($activity->id
)) {
325 // CRM-8708, preserve case ID even though it's not part of the SQL model
326 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
330 $transaction = new CRM_Core_Transaction();
332 $result = $activity->save();
334 if (is_a($result, 'CRM_Core_Error')) {
335 $transaction->rollback();
339 $activityId = $activity->id
;
340 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
341 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
342 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
343 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
345 if (isset($params['source_contact_id'])) {
347 'activity_id' => $activityId,
348 'contact_id' => $params['source_contact_id'],
349 'record_type_id' => $sourceID,
351 self
::deleteActivityContact($activityId, $sourceID);
352 CRM_Activity_BAO_ActivityContact
::create($acParams);
355 // check and attach and files as needed
356 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
358 // attempt to save activity assignment
359 $resultAssignment = NULL;
360 if (!empty($params['assignee_contact_id'])) {
362 $assignmentParams = array('activity_id' => $activityId);
364 if (is_array($params['assignee_contact_id'])) {
365 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
366 // first delete existing assignments if any
367 self
::deleteActivityContact($activityId, $assigneeID);
371 foreach ($params['assignee_contact_id'] as $acID) {
373 $values[] = "( $activityId, $acID, $assigneeID )";
376 while (!empty($values)) {
377 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
378 $str = implode(',', $input);
379 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
380 CRM_Core_DAO
::executeQuery($sql);
384 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
385 $assignmentParams['record_type_id'] = $assigneeID;
386 if (!empty($params['id'])) {
387 $assignment = new CRM_Activity_BAO_ActivityContact();
388 $assignment->activity_id
= $activityId;
389 $assignment->record_type_id
= $assigneeID;
390 $assignment->find(TRUE);
392 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
393 $assignmentParams['id'] = $assignment->id
;
394 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
398 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
403 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
404 self
::deleteActivityContact($activityId, $assigneeID);
408 if (is_a($resultAssignment, 'CRM_Core_Error')) {
409 $transaction->rollback();
410 return $resultAssignment;
413 // attempt to save activity targets
414 $resultTarget = NULL;
415 if (!empty($params['target_contact_id'])) {
417 $targetParams = array('activity_id' => $activityId);
418 $resultTarget = array();
419 if (is_array($params['target_contact_id'])) {
420 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
421 // first delete existing targets if any
422 self
::deleteActivityContact($activityId, $targetID);
426 foreach ($params['target_contact_id'] as $tid) {
428 $values[] = "( $activityId, $tid, $targetID )";
432 while (!empty($values)) {
433 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
434 $str = implode(',', $input);
435 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
436 CRM_Core_DAO
::executeQuery($sql);
440 $targetParams['contact_id'] = $params['target_contact_id'];
441 $targetParams['record_type_id'] = $targetID;
442 if (!empty($params['id'])) {
443 $target = new CRM_Activity_BAO_ActivityContact();
444 $target->activity_id
= $activityId;
445 $target->record_type_id
= $targetID;
448 if ($target->contact_id
!= $params['target_contact_id']) {
449 $targetParams['id'] = $target->id
;
450 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
454 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
459 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
460 self
::deleteActivityContact($activityId, $targetID);
464 // write to changelog before transaction is committed/rolled
465 // back (and prepare status to display)
466 if (!empty($params['id'])) {
467 $logMsg = "Activity (id: {$result->id} ) updated with ";
470 $logMsg = "Activity created for ";
474 if (isset($params['source_contact_id'])) {
475 $msgs[] = "source={$params['source_contact_id']}";
478 if (!empty($params['target_contact_id'])) {
479 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
480 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
481 // take only first target
482 // will be used for recently viewed display
483 $t = array_slice($params['target_contact_id'], 0, 1);
484 $recentContactId = $t[0];
486 //is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
487 // as it may always be an array
488 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
489 $msgs[] = "target={$params['target_contact_id']}";
490 // will be used for recently viewed display
491 $recentContactId = $params['target_contact_id'];
495 // at worst, take source for recently viewed display
496 $recentContactId = CRM_Utils_Array
::value('source_contact_id', $params);
499 if (isset($params['assignee_contact_id'])) {
500 if (is_array($params['assignee_contact_id'])) {
501 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
504 $msgs[] = "assignee={$params['assignee_contact_id']}";
507 $logMsg .= implode(', ', $msgs);
509 self
::logActivityAction($result, $logMsg);
511 if (!empty($params['custom']) &&
512 is_array($params['custom'])
514 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
517 $transaction->commit();
518 if (empty($params['skipRecentView'])) {
519 $recentOther = array();
520 if (!empty($params['case_id'])) {
521 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
522 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
523 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
527 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home";
528 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
529 $url = CRM_Utils_System
::url('civicrm/activity', $q);
530 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
531 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
532 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
536 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
537 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
541 if (CRM_Core_Permission
::check("delete activities")) {
542 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
543 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
548 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
549 if (CRM_Core_Permission
::check('delete activities')) {
550 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
551 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
557 if (!isset($activity->parent_id
)) {
558 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
559 // add the recently created Activity
560 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
561 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
564 if (isset($activitySubject)) {
565 $title = $activitySubject . ' - ';
568 $title = $title . $recentContactDisplay;
569 if (!empty($activityTypes[$activity->activity_type_id
])) {
570 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
573 CRM_Utils_Recent
::add($title,
578 $recentContactDisplay,
584 // reset the group contact cache since smart groups might be affected due to this
585 CRM_Contact_BAO_GroupContactCache
::remove();
587 if (!empty($params['id'])) {
588 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
591 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
594 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
596 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
597 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
599 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
601 'activity_id' => $activity->id
,
602 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
604 if ($caseParams['case_id']) {
605 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
608 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
617 * @param null $logMessage
621 public static function logActivityAction($activity, $logMessage = NULL) {
622 $session = CRM_Core_Session
::singleton();
623 $id = $session->get('userID');
625 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
626 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
627 $id = self
::getActivityContact($activity->id
. $sourceID);
630 'entity_table' => 'civicrm_activity',
631 'entity_id' => $activity->id
,
632 'modified_id' => $id,
633 'modified_date' => date('YmdHis'),
634 'data' => $logMessage,
636 CRM_Core_BAO_Log
::add($logParams);
641 * Get the list Activities
643 * @param array $input
644 * Array of parameters.
646 * - contact_id int contact_id whose activities we want to retrieve
647 * - offset int which row to start from ?
648 * - rowCount int how many rows to fetch
649 * - sort object|array object or array describing sort order for sql query.
650 * - admin boolean if contact is admin
651 * - caseId int case ID
652 * - context string page on which selector is build
653 * - activity_type_id int|string the activitiy types we want to restrict by
656 * (reference) $values the relevant data object values of open activities
659 public static function &getActivities($input) {
660 //step 1: Get the basic activity data
661 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
667 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
668 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
669 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
670 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
672 $config = CRM_Core_Config
::singleton();
674 $randomNum = md5(uniqid());
675 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
677 $tableFields = array(
678 'activity_id' => 'int unsigned',
679 'activity_date_time' => 'datetime',
680 'source_record_id' => 'int unsigned',
681 'status_id' => 'int unsigned',
682 'subject' => 'varchar(255)',
683 'source_contact_name' => 'varchar(255)',
684 'activity_type_id' => 'int unsigned',
685 'activity_type' => 'varchar(128)',
686 'case_id' => 'int unsigned',
687 'case_subject' => 'varchar(255)',
688 'campaign_id' => 'int unsigned',
691 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
692 $insertValueSQL = array();
693 // The activityTempTable contains the sorted rows
694 // so in order to maintain the sort order as-is we add an auto_increment
695 // field; we can sort by this later to ensure the sort order stays correct.
696 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
697 foreach ($tableFields as $name => $desc) {
698 $sql .= "$name $desc,\n";
699 $insertValueSQL[] = $name;
702 // add unique key on activity_id just to be sure
703 // this cannot be primary key because we need that for the auto_increment
704 // fixed_sort_order field
706 UNIQUE KEY ( activity_id )
707 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
710 CRM_Core_DAO
::executeQuery($sql);
712 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
714 $order = $limit = $groupBy = '';
715 $groupBy = " GROUP BY tbl.activity_id ";
717 if (!empty($input['sort'])) {
718 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
719 $orderBy = $input['sort']->orderBy();
720 if (!empty($orderBy)) {
721 $order = " ORDER BY $orderBy";
724 elseif (trim($input['sort'])) {
725 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
726 $order = " ORDER BY $sort ";
731 // context = 'activity' in Activities tab.
732 $order = (CRM_Utils_Array
::value('context', $input) == 'activity') ?
" ORDER BY tbl.activity_date_time desc " : " ORDER BY tbl.status_id asc, tbl.activity_date_time asc ";
735 if (!empty($input['rowCount']) &&
736 $input['rowCount'] > 0
738 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
741 $input['count'] = FALSE;
742 list($sqlClause, $params) = self
::getActivitySQLClause($input);
744 $query = "{$insertSQL}
745 SELECT DISTINCT tbl.* from ( {$sqlClause} )
748 //filter case activities - CRM-5761
749 $components = self
::activityComponents();
750 if (!in_array('CiviCase', $components)) {
752 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
753 WHERE civicrm_case_activity.id IS NULL";
756 $query = $query . $groupBy . $order . $limit;
758 $dao = CRM_Core_DAO
::executeQuery($query, $params);
760 // step 2: Get target and assignee contacts for above activities
761 // create temp table for target contacts
762 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
763 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
764 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
765 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
766 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
768 CRM_Core_DAO
::executeQuery($query);
770 // note that we ignore bulk email for targets, since we don't show it in selector
772 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
773 SELECT ac.activity_id,
778 FROM {$activityTempTable}
779 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
780 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
781 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
782 WHERE ac.record_type_id != %1
784 $params = array(1 => array($targetID, 'Integer'));
785 CRM_Core_DAO
::executeQuery($query, $params);
787 // for each activity insert one target contact
788 // if we load all target contacts the performance will suffer a lot for mass-activities;
790 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
791 SELECT ac.activity_id,
797 FROM {$activityTempTable}
798 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
799 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
800 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
801 WHERE ac.record_type_id = %1
802 GROUP BY ac.activity_id
805 CRM_Core_DAO
::executeQuery($query, $params);
807 // step 3: Combine all temp tables to get final query for activity selector
808 // sort by the original sort order, stored in fixed_sort_order
810 SELECT {$activityTempTable}.*,
811 {$activityContactTempTable}.contact_id,
812 {$activityContactTempTable}.record_type_id,
813 {$activityContactTempTable}.contact_name,
814 {$activityContactTempTable}.is_deleted,
815 {$activityContactTempTable}.counter,
816 re.parent_id as is_recurring_activity
817 FROM {$activityTempTable}
818 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
819 LEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id
820 ORDER BY fixed_sort_order
823 $dao = CRM_Core_DAO
::executeQuery($query);
825 //CRM-3553, need to check user has access to target groups.
826 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
828 (CRM_Core_Permission
::check('access CiviMail')) ||
829 (CRM_Mailing_Info
::workflowEnabled() &&
830 CRM_Core_Permission
::check('create mailings'))
834 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
836 while ($dao->fetch()) {
837 $activityID = $dao->activity_id
;
838 $values[$activityID]['activity_id'] = $dao->activity_id
;
839 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
840 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
841 $values[$activityID]['activity_type'] = $dao->activity_type
;
842 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
843 $values[$activityID]['status_id'] = $dao->status_id
;
844 $values[$activityID]['subject'] = $dao->subject
;
845 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
846 $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity
;
848 if ($dao->campaign_id
) {
849 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
852 if (empty($values[$activityID]['assignee_contact_name'])) {
853 $values[$activityID]['assignee_contact_name'] = array();
856 if (empty($values[$activityID]['target_contact_name'])) {
857 $values[$activityID]['target_contact_name'] = array();
858 $values[$activityID]['target_contact_counter'] = $dao->counter
;
861 // if deleted, wrap in <del>
862 if ($dao->is_deleted
) {
863 $dao->contact_name
= "<del>{$dao->contact_name}</dao>";
866 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
867 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
868 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
871 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
872 // build array of target / assignee names
873 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
874 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
876 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
877 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
880 // case related fields
881 $values[$activityID]['case_id'] = $dao->case_id
;
882 $values[$activityID]['case_subject'] = $dao->case_subject
;
885 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter
));
886 $values[$activityID]['mailingId'] = FALSE;
889 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
891 $values[$activityID]['mailingId'] = TRUE;
900 * Get the component id and name those are enabled and logged in
901 * user has permission. To decide whether we are going to include
902 * component related activities w/ core activity retrieve process.
905 * Array of component id and name.
907 public static function activityComponents() {
908 $components = array();
909 $compInfo = CRM_Core_Component
::getEnabledComponents();
910 foreach ($compInfo as $compObj) {
911 if (!empty($compObj->info
['showActivitiesInCore'])) {
912 if ($compObj->info
['name'] == 'CiviCampaign') {
913 $componentPermission = "administer {$compObj->name}";
916 $componentPermission = "access {$compObj->name}";
918 if ($compObj->info
['name'] == 'CiviCase') {
919 if (CRM_Case_BAO_Case
::accessCiviCase()) {
920 $components[$compObj->componentID
] = $compObj->info
['name'];
923 elseif (CRM_Core_Permission
::check($componentPermission)) {
924 $components[$compObj->componentID
] = $compObj->info
['name'];
933 * Get the activity Count
935 * @param array $input
936 * Array of parameters.
938 * - contact_id int contact_id whose activities we want to retrieve
939 * - admin boolean if contact is admin
940 * - caseId int case ID
941 * - context string page on which selector is build
942 * - activity_type_id int|string the activity types we want to restrict by
945 * count of activities
948 public static function &getActivitiesCount($input) {
949 $input['count'] = TRUE;
950 list($sqlClause, $params) = self
::getActivitySQLClause($input);
952 //filter case activities - CRM-5761
953 $components = self
::activityComponents();
954 if (!in_array('CiviCase', $components)) {
956 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
957 FROM ( {$sqlClause} ) as tbl
958 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
959 WHERE civicrm_case_activity.id IS NULL";
962 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
965 return CRM_Core_DAO
::singleValueQuery($query, $params);
969 * Get the activity sql clause to pick activities
971 * @param array $input
972 * Array of parameters.
974 * - contact_id int contact_id whose activities we want to retrieve
975 * - admin boolean if contact is admin
976 * - caseId int case ID
977 * - context string page on which selector is build
978 * - count boolean are we interested in the count clause only?
979 * - activity_type_id int|string the activity types we want to restrict by
982 * count of activities
985 public static function getActivitySQLClause($input) {
987 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
989 $config = CRM_Core_Config
::singleton();
990 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
991 $sourceWhere = ' ac.contact_id = %1 ';
992 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
994 $params = array(1 => array($input['contact_id'], 'Integer'));
997 $commonClauses = array(
998 "civicrm_option_group.name = 'activity_type'",
999 "civicrm_activity.is_deleted = 0",
1000 "civicrm_activity.is_current_revision = 1",
1001 "civicrm_activity.is_test= 0",
1004 if ($input['context'] != 'activity') {
1005 $commonClauses[] = "civicrm_activity.status_id = 1";
1008 //Filter on component IDs.
1009 $components = self
::activityComponents();
1010 if (!empty($components)) {
1011 $componentsIn = implode(',', array_keys($components));
1012 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1015 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1018 // activity type ID clause
1019 if (!empty($input['activity_type_id'])) {
1020 if (is_array($input['activity_type_id'])) {
1021 foreach ($input['activity_type_id'] as $idx => $value) {
1022 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1024 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1027 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1028 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1032 // exclude by activity type clause
1033 if (!empty($input['activity_type_exclude_id'])) {
1034 if (is_array($input['activity_type_exclude_id'])) {
1035 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1036 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1038 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1041 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1042 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1046 $commonClause = implode(' AND ', $commonClauses);
1048 $includeCaseActivities = FALSE;
1049 if (in_array('CiviCase', $components)) {
1050 $includeCaseActivities = TRUE;
1053 // build main activity table select clause
1056 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1057 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1059 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1060 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1063 if (!$input['count']) {
1065 civicrm_activity.activity_date_time,
1066 civicrm_activity.source_record_id,
1067 civicrm_activity.status_id,
1068 civicrm_activity.subject,
1069 contact.sort_name as source_contact_name,
1070 civicrm_option_value.value as activity_type_id,
1071 civicrm_option_value.label as activity_type,
1072 null as case_id, null as case_subject,
1073 civicrm_activity.campaign_id as campaign_id
1077 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)
1082 SELECT civicrm_activity.id as activity_id
1084 from civicrm_activity
1085 left join civicrm_option_value on
1086 civicrm_activity.activity_type_id = civicrm_option_value.value
1087 left join civicrm_option_group on
1088 civicrm_option_group.id = civicrm_option_value.option_group_id
1095 // Build case clause
1096 // or else exclude Inbound Emails that have been filed on a case.
1099 if ($includeCaseActivities) {
1101 if (!$input['count']) {
1103 civicrm_activity.activity_date_time,
1104 civicrm_activity.source_record_id,
1105 civicrm_activity.status_id,
1106 civicrm_activity.subject,
1107 contact.sort_name as source_contact_name,
1108 civicrm_option_value.value as activity_type_id,
1109 civicrm_option_value.label as activity_type,
1110 null as case_id, null as case_subject,
1111 civicrm_activity.campaign_id as campaign_id';
1117 SELECT civicrm_activity.id as activity_id
1119 from civicrm_activity
1120 inner join civicrm_case_activity on
1121 civicrm_case_activity.activity_id = civicrm_activity.id
1122 inner join civicrm_case on
1123 civicrm_case_activity.case_id = civicrm_case.id
1124 inner join civicrm_case_contact on
1125 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1126 left join civicrm_option_value on
1127 civicrm_activity.activity_type_id = civicrm_option_value.value
1128 left join civicrm_option_group on
1129 civicrm_option_group.id = civicrm_option_value.option_group_id
1134 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1135 ( civicrm_option_value.name <> 'Inbound Email' AND
1136 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1142 $returnClause = " {$sourceClause} {$caseClause} ";
1144 return array($returnClause, $params);
1148 * Send the message to all the contacts and also insert a
1149 * contact activity in each contacts record
1151 * @param array $contactDetails
1152 * The array of contact details to send the email.
1153 * @param string $subject
1154 * The subject of the message.
1157 * @param string $emailAddress
1158 * Use this 'to' email address instead of the default Primary address.
1159 * @param int $userID
1160 * Use this userID if set.
1161 * @param string $from
1162 * @param array $attachments
1163 * The array of attachments if any.
1166 * @param string $bcc
1168 * @param array $contactIds
1170 * @param string $additionalDetails
1171 * The additional information of CC and BCC appended to the activity Details.
1174 * ( sent, activityId) if any email is sent and activityId
1176 public static function sendEmail(
1184 $attachments = NULL,
1187 $contactIds, // FIXME a param with no default shouldn't be last
1188 $additionalDetails = NULL
1190 // get the contact details of logged in contact, which we set as from email
1191 if ($userID == NULL) {
1192 $session = CRM_Core_Session
::singleton();
1193 $userID = $session->get('userID');
1196 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1198 return array(count($contactDetails), 0, count($contactDetails));
1200 if (!trim($fromDisplayName)) {
1201 $fromDisplayName = $fromEmail;
1205 // token replacement of addressee/email/postal greetings
1206 // get the tokens added in subject and message
1207 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1208 $messageToken = CRM_Utils_Token
::getTokens($text);
1209 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1210 $allTokens = array_merge($messageToken, $subjectToken);
1213 $from = "$fromDisplayName <$fromEmail>";
1216 //create the meta level record first ( email activity )
1217 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1222 // CRM-6265: save both text and HTML parts in details (if present)
1223 if ($html and $text) {
1224 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1227 $details = $html ?
$html : $text;
1228 $details .= $additionalDetails;
1231 $activityParams = array(
1232 'source_contact_id' => $userID,
1233 'activity_type_id' => $activityTypeID,
1234 'activity_date_time' => date('YmdHis'),
1235 'subject' => $subject,
1236 'details' => $details,
1237 // FIXME: check for name Completed and get ID from that lookup
1241 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1242 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1244 // add the attachments to activity params here
1246 // first process them
1247 $activityParams = array_merge($activityParams,
1252 $activity = self
::create($activityParams);
1254 // get the set of attachments from where they are stored
1255 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1258 $returnProperties = array();
1259 if (isset($messageToken['contact'])) {
1260 foreach ($messageToken['contact'] as $key => $value) {
1261 $returnProperties[$value] = 1;
1265 if (isset($subjectToken['contact'])) {
1266 foreach ($subjectToken['contact'] as $key => $value) {
1267 if (!isset($returnProperties[$value])) {
1268 $returnProperties[$value] = 1;
1273 // get token details for contacts, call only if tokens are used
1275 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1276 list($details) = CRM_Utils_Token
::getTokenDetails(
1281 'CRM_Activity_BAO_Activity'
1287 CRM_Utils_Hook
::tokens($tokens);
1288 $categories = array_keys($tokens);
1290 $escapeSmarty = FALSE;
1291 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1292 $smarty = CRM_Core_Smarty
::singleton();
1293 $escapeSmarty = TRUE;
1296 $sent = $notSent = array();
1297 foreach ($contactDetails as $values) {
1298 $contactId = $values['contact_id'];
1299 $emailAddress = $values['email'];
1301 if (!empty($details) && is_array($details["{$contactId}"])) {
1302 // unset email from details since it always returns primary email address
1303 unset($details["{$contactId}"]['email']);
1304 unset($details["{$contactId}"]['email_id']);
1305 $values = array_merge($values, $details["{$contactId}"]);
1308 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1309 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1312 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1313 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1314 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1320 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1321 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1322 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1328 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1329 // also add the contact tokens to the template
1330 $smarty->assign_by_ref('contact', $values);
1332 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1333 $tokenText = $smarty->fetch("string:$tokenText");
1334 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1338 if (self
::sendMessage(
1356 return array($sent, $activity->id
);
1360 * @param array $contactDetails
1361 * @param array $activityParams
1362 * @param array $smsParams
1363 * @param $contactIds
1364 * @param int $userID
1367 * @throws CRM_Core_Exception
1369 public static function sendSMS(
1372 &$smsParams = array(),
1376 if ($userID == NULL) {
1377 $session = CRM_Core_Session
::singleton();
1378 $userID = $session->get('userID');
1381 $text = &$activityParams['sms_text_message'];
1384 // token replacement of addressee/email/postal greetings
1385 // get the tokens added in subject and message
1386 $messageToken = CRM_Utils_Token
::getTokens($text);
1388 //create the meta level record first ( sms activity )
1389 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1396 $activitySubject = $activityParams['activity_subject'];
1397 $activityParams = array(
1398 'source_contact_id' => $userID,
1399 'activity_type_id' => $activityTypeID,
1400 'activity_date_time' => date('YmdHis'),
1401 'subject' => $activitySubject,
1402 'details' => $details,
1403 // FIXME: check for name Completed and get ID from that lookup
1407 $activity = self
::create($activityParams);
1408 $activityID = $activity->id
;
1410 $returnProperties = array();
1412 if (isset($messageToken['contact'])) {
1413 foreach ($messageToken['contact'] as $key => $value) {
1414 $returnProperties[$value] = 1;
1420 CRM_Utils_Hook
::tokens($tokens);
1421 $categories = array_keys($tokens);
1423 // get token details for contacts, call only if tokens are used
1425 if (!empty($returnProperties) ||
!empty($tokens)) {
1426 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1430 'CRM_Activity_BAO_Activity'
1435 $escapeSmarty = FALSE;
1437 foreach ($contactDetails as $values) {
1438 $contactId = $values['contact_id'];
1440 if (!empty($details) && is_array($details["{$contactId}"])) {
1441 // unset email from details since it always returns primary email address
1442 unset($details["{$contactId}"]['email']);
1443 unset($details["{$contactId}"]['email_id']);
1444 $values = array_merge($values, $details["{$contactId}"]);
1447 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1448 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1450 // Only send if the phone is of type mobile
1451 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1452 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1453 $smsParams['To'] = $values['phone'];
1456 $smsParams['To'] = '';
1459 $sendResult = self
::sendSMSMessage(
1467 if (PEAR
::isError($sendResult)) {
1468 // Collect all of the PEAR_Error objects
1469 $errMsgs[] = $sendResult;
1476 // If at least one message was sent and no errors
1477 // were generated then return a boolean value of TRUE.
1478 // Otherwise, return FALSE (no messages sent) or
1479 // and array of 1 or more PEAR_Error objects.
1481 if ($success > 0 && count($errMsgs) == 0) {
1484 elseif (count($errMsgs) > 0) {
1488 return array($sent, $activity->id
, $success);
1492 * Send the sms message to a specific contact
1495 * The contact id of the recipient.
1498 * @param array $smsParams
1499 * The params used for sending sms.
1500 * @param int $activityID
1501 * The activity ID that tracks the message.
1502 * @param int $userID
1504 * @return bool|PEAR_Error
1505 * true on success or PEAR_Error object
1507 public static function sendSMSMessage(
1510 $smsParams = array(),
1515 $toPhoneNumber = "";
1517 if ($smsParams['To']) {
1518 $toPhoneNumber = trim($smsParams['To']);
1521 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1522 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1523 //to get primary mobile ph,if not get a first mobile ph
1524 if (!empty($toPhoneNumbers)) {
1525 $toPhoneNumerDetails = reset($toPhoneNumbers);
1526 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1527 //contact allows to send sms
1532 // make sure both phone are valid
1533 // and that the recipient wants to receive sms
1534 if (empty($toPhoneNumber) or $toDoNotSms) {
1535 return PEAR
::raiseError(
1536 'Recipient phone number is invalid or recipient does not want to receive SMS',
1542 $recipient = $smsParams['To'];
1543 $smsParams['contact_id'] = $toID;
1544 $smsParams['parent_activity_id'] = $activityID;
1546 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1547 $sendResult = $providerObj->send($recipient, $smsParams, $tokenText, NULL, $userID);
1548 if (PEAR
::isError($sendResult)) {
1552 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1553 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1555 // add activity target record for every sms that is send
1556 $activityTargetParams = array(
1557 'activity_id' => $activityID,
1558 'contact_id' => $toID,
1559 'record_type_id' => $targetID,
1561 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1567 * Send the message to a specific contact
1569 * @param string $from
1570 * The name and email of the sender.
1571 * @param int $fromID
1573 * The contact id of the recipient.
1574 * @param string $subject
1575 * The subject of the message.
1576 * @param $text_message
1577 * @param $html_message
1578 * @param string $emailAddress
1579 * Use this 'to' email address instead of the default Primary address.
1580 * @param int $activityID
1581 * The activity ID that tracks the message.
1582 * @param null $attachments
1587 * TRUE if successful else FALSE.
1589 public static function sendMessage(
1598 $attachments = NULL,
1602 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1603 if ($emailAddress) {
1604 $toEmail = trim($emailAddress);
1607 // make sure both email addresses are valid
1608 // and that the recipient wants to receive email
1609 if (empty($toEmail) or $toDoNotEmail) {
1612 if (!trim($toDisplayName)) {
1613 $toDisplayName = $toEmail;
1616 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1617 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1618 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1619 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1621 // create the params array
1622 $mailParams = array(
1623 'groupName' => 'Activity Email Sender',
1625 'toName' => $toDisplayName,
1626 'toEmail' => $toEmail,
1627 'subject' => $subject,
1630 'text' => $text_message,
1631 'html' => $html_message,
1632 'attachments' => $attachments,
1635 if (!CRM_Utils_Mail
::send($mailParams)) {
1639 // add activity target record for every mail that is send
1640 $activityTargetParams = array(
1641 'activity_id' => $activityID,
1642 'contact_id' => $toID,
1643 'record_type_id' => $targetID,
1645 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1650 * Combine all the importable fields from the lower levels object
1652 * The ordering is important, since currently we do not have a weight
1653 * scheme. Adding weight is super important and should be done in the
1654 * next week or so, before this can be called complete.
1656 * @param bool $status
1659 * array of importable Fields
1661 public static function &importableFields($status = FALSE) {
1662 if (!self
::$_importableFields) {
1663 if (!self
::$_importableFields) {
1664 self
::$_importableFields = array();
1667 $fields = array('' => array('title' => ts('- do not import -')));
1670 $fields = array('' => array('title' => ts('- Activity Fields -')));
1673 $tmpFields = CRM_Activity_DAO_Activity
::import();
1674 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1676 // Using new Dedupe rule.
1677 $ruleParams = array(
1678 'contact_type' => 'Individual',
1679 'used' => 'Unsupervised',
1681 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1683 $tmpConatctField = array();
1684 if (is_array($fieldsArray)) {
1685 foreach ($fieldsArray as $value) {
1686 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1691 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1692 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1693 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1696 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1697 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1698 $fields = array_merge($fields, $tmpConatctField);
1699 $fields = array_merge($fields, $tmpFields);
1700 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1701 self
::$_importableFields = $fields;
1703 return self
::$_importableFields;
1707 * get the Activities of a target contact
1709 * @param int $contactId
1710 * Id of the contact whose activities need to find.
1713 * array of activity fields
1715 public static function getContactActivity($contactId) {
1716 $activities = array();
1717 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1718 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1719 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1720 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1722 // First look for activities where contactId is one of the targets
1724 SELECT activity_id, record_type_id
1725 FROM civicrm_activity_contact
1726 WHERE contact_id = $contactId
1728 $dao = CRM_Core_DAO
::executeQuery($query);
1729 while ($dao->fetch()) {
1730 if ($dao->record_type_id
== $targetID) {
1731 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1733 elseif ($dao->record_type_id
== $assigneeID) {
1734 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1737 // do source stuff here
1738 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1742 $activityIds = array_keys($activities);
1743 if (count($activityIds) < 1) {
1747 $activityIds = implode(',', $activityIds);
1749 SELECT activity.id as activity_id,
1751 subject, location, activity_date_time, details, status_id
1752 FROM civicrm_activity activity
1753 WHERE activity.id IN ($activityIds)";
1755 $dao = CRM_Core_DAO
::executeQuery($query);
1757 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1758 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1760 while ($dao->fetch()) {
1761 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1762 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1763 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1764 $activities[$dao->activity_id
]['location'] = $dao->location
;
1765 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1766 $activities[$dao->activity_id
]['details'] = $dao->details
;
1767 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1768 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1769 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1771 // set to null if not set
1772 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1773 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1780 * Add activity for Membership/Event/Contribution
1782 * @param object $activity
1783 * (reference) particular component object.
1784 * @param string $activityType
1785 * For Membership Signup or Renewal.
1786 * @param int $targetContactID
1790 public static function addActivity(
1792 $activityType = 'Membership Signup',
1793 $targetContactID = NULL
1795 if ($activity->__table
== 'civicrm_membership') {
1796 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1798 if (!$membershipType) {
1799 $membershipType = ts('Membership');
1802 $subject = "{$membershipType}";
1804 if (!empty($activity->source
) && $activity->source
!= 'null') {
1805 $subject .= " - {$activity->source}";
1808 if ($activity->owner_membership_id
) {
1811 FROM civicrm_contact, civicrm_membership
1812 WHERE civicrm_contact.id = civicrm_membership.contact_id
1813 AND civicrm_membership.id = $activity->owner_membership_id
1815 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1816 $subject .= " (by {$displayName})";
1819 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
, 'label');
1820 // CRM-72097 changed from start date to today
1821 $date = date('YmdHis');
1822 $component = 'Membership';
1824 elseif ($activity->__table
== 'civicrm_participant') {
1825 $event = CRM_Event_BAO_Event
::getEvents(1, $activity->event_id
, TRUE, FALSE);
1827 $roles = CRM_Event_PseudoConstant
::participantRole();
1828 $status = CRM_Event_PseudoConstant
::participantStatus();
1830 $subject = $event[$activity->event_id
];
1831 if (!empty($roles[$activity->role_id
])) {
1832 $subject .= ' - ' . $roles[$activity->role_id
];
1834 if (!empty($status[$activity->status_id
])) {
1835 $subject .= ' - ' . $status[$activity->status_id
];
1837 $date = date('YmdHis');
1838 if ($activityType != 'Email') {
1839 $activityType = 'Event Registration';
1841 $component = 'Event';
1843 elseif ($activity->__table
== 'civicrm_contribution') {
1844 //create activity record only for Completed Contributions
1845 if ($activity->contribution_status_id
!= 1) {
1851 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1852 if (!empty($activity->source
) && $activity->source
!= 'null') {
1853 $subject .= " - {$activity->source}";
1855 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1856 $activityType = $component = 'Contribution';
1858 $activityParams = array(
1859 'source_contact_id' => $activity->contact_id
,
1860 'source_record_id' => $activity->id
,
1861 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1865 'subject' => $subject,
1866 'activity_date_time' => $date,
1867 'is_test' => $activity->is_test
,
1868 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1872 'skipRecentView' => TRUE,
1873 'campaign_id' => $activity->campaign_id
,
1876 // create activity with target contacts
1877 $session = CRM_Core_Session
::singleton();
1878 $id = $session->get('userID');
1880 $activityParams['source_contact_id'] = $id;
1881 $activityParams['target_contact_id'][] = $activity->contact_id
;
1885 if (property_exists($activity, 'details')) {
1886 $activityParams['details'] = $activity->details
;
1889 if ($targetContactID) {
1890 $activityParams['target_contact_id'][] = $targetContactID;
1892 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1893 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1899 * Get Parent activity for currently viewed activity
1901 * @param int $activityId
1902 * Current activity id.
1905 * $parentId Id of parent activity otherwise false.
1907 public static function getParentActivity($activityId) {
1908 static $parentActivities = array();
1910 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1912 if (!array_key_exists($activityId, $parentActivities)) {
1913 $parentActivities[$activityId] = array();
1915 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1920 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1923 return $parentActivities[$activityId];
1927 * Get total count of prior revision of currently viewd activity
1929 * @param $activityID
1930 * Current activity id.
1933 * $params count of prior activities otherwise false.
1935 public static function getPriorCount($activityID) {
1936 static $priorCounts = array();
1938 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1940 if (!array_key_exists($activityID, $priorCounts)) {
1941 $priorCounts[$activityID] = array();
1942 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1949 SELECT count( id ) AS cnt
1950 FROM civicrm_activity
1951 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1952 AND is_current_revision = 0
1953 AND id < {$activityID}
1955 $params = array(1 => array($originalID, 'Integer'));
1956 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1958 $priorCounts[$activityID] = $count ?
$count : 0;
1961 return $priorCounts[$activityID];
1965 * Get all prior activities of currently viewed activity
1967 * @param $activityID
1968 * Current activity id.
1969 * @param bool $onlyPriorRevisions
1972 * prior activities info.
1974 public static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1975 static $priorActivities = array();
1977 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1978 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1980 if (!array_key_exists($index, $priorActivities)) {
1981 $priorActivities[$index] = array();
1983 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1989 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1990 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1991 WHERE (ca.id = %1 OR ca.original_id = %1)
1992 AND cl.entity_table = 'civicrm_activity'
1993 AND cl.entity_id = ca.id
1994 AND cl.modified_id = c.id
1996 if ($onlyPriorRevisions) {
1997 $query .= " AND ca.id < {$activityID}";
1999 $query .= " ORDER BY ca.id DESC";
2001 $params = array(1 => array($originalID, 'Integer'));
2002 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2004 while ($dao->fetch()) {
2005 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
2006 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
2007 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
2012 return $priorActivities[$index];
2016 * Find the latest revision of a given activity
2018 * @param int $activityID
2019 * Prior activity id.
2022 * current activity id.
2024 public static function getLatestActivityId($activityID) {
2025 static $latestActivityIds = array();
2027 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2029 if (!array_key_exists($activityID, $latestActivityIds)) {
2030 $latestActivityIds[$activityID] = array();
2032 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2037 $activityID = $originalID;
2039 $params = array(1 => array($activityID, 'Integer'));
2040 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2042 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2045 return $latestActivityIds[$activityID];
2049 * Create a follow up a given activity
2051 * @param int $activityId
2052 * activity id of parent activity.
2053 * @param array $params
2055 * @return CRM_Activity_BAO_Activity|null|object
2057 public static function createFollowupActivity($activityId, $params) {
2062 $session = CRM_Core_Session
::singleton();
2064 $followupParams = array();
2065 $followupParams['parent_id'] = $activityId;
2066 $followupParams['source_contact_id'] = $session->get('userID');
2067 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2069 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2070 // Get Subject of Follow-up Activiity, CRM-4491
2071 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2072 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2074 //create target contact for followup
2075 if (!empty($params['target_contact_id'])) {
2076 $followupParams['target_contact_id'] = $params['target_contact_id'];
2079 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2080 $params['followup_date_time']
2082 $followupActivity = self
::create($followupParams);
2084 return $followupActivity;
2088 * Get Activity specific File according activity type Id.
2090 * @param int $activityTypeId
2092 * @param string $crmDir
2094 * @return string|bool
2095 * if file exists returns $activityTypeFile activity filename otherwise false.
2098 public static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2099 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2101 if ($activityTypes[$activityTypeId]['name']) {
2102 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2108 global $civicrm_root;
2109 $config = CRM_Core_Config
::singleton();
2110 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2111 if (empty($config->customPHPPathDir
)) {
2114 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2119 return $activityTypeFile;
2123 * Restore the activity
2125 * @param array $params
2129 public static function restoreActivity(&$params) {
2130 $activity = new CRM_Activity_DAO_Activity();
2131 $activity->copyValues($params);
2133 $activity->is_deleted
= 0;
2134 $result = $activity->save();
2140 * Get the exportable fields for Activities
2142 * @param string $name
2143 * If it is called by case $name = Case else $name = Activity.
2146 * array of exportable Fields
2148 public static function &exportableFields($name = 'Activity') {
2149 if (!isset(self
::$_exportableFields[$name])) {
2150 self
::$_exportableFields[$name] = array();
2152 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2153 // my case hence we have defined fields as case_*
2154 if ($name == 'Activity') {
2155 $exportableFields = CRM_Activity_DAO_Activity
::export();
2156 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2157 $exportableFields['source_contact'] = array(
2158 'title' => ts('Source Contact'),
2159 'type' => CRM_Utils_Type
::T_STRING
,
2162 $Activityfields = array(
2163 'activity_type' => array('title' => ts('Activity Type'), 'name' => 'activity_type', 'type' => CRM_Utils_Type
::T_STRING
),
2164 'activity_status' => array('title' => ts('Activity Status'), 'name' => 'activity_status', 'type' => CRM_Utils_Type
::T_STRING
),
2166 $fields = array_merge($Activityfields, $exportableFields);
2169 //set title to activity fields
2171 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2172 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2173 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2174 'case_scheduled_activity_date' => array(
2175 'title' => ts('Activity Scheduled Date'),
2176 'type' => CRM_Utils_Type
::T_DATE
,
2178 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2179 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2180 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2181 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2182 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2183 'case_activity_is_auto' => array(
2184 'title' => ts('Activity Auto-generated?'),
2185 'type' => CRM_Utils_Type
::T_BOOLEAN
,
2189 // add custom data for cases
2190 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2193 // add custom data for case activities
2194 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2196 self
::$_exportableFields[$name] = $fields;
2198 return self
::$_exportableFields[$name];
2202 * Get the allowed profile fields for Activities
2205 * array of activity profile Fields
2207 public static function getProfileFields() {
2208 $exportableFields = self
::exportableFields('Activity');
2209 $skipFields = array(
2212 'source_contact_id',
2214 'activity_campaign',
2216 'is_current_revision',
2217 'activity_is_deleted',
2219 $config = CRM_Core_Config
::singleton();
2220 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2221 $skipFields[] = 'activity_engagement_level';
2224 foreach ($skipFields as $field) {
2225 if (isset($exportableFields[$field])) {
2226 unset($exportableFields[$field]);
2230 // hack to use 'activity_type_id' instead of 'activity_type'
2231 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2232 unset($exportableFields['activity_status']);
2234 return $exportableFields;
2238 * This function deletes the activity record related to contact record,
2239 * when there are no target and assignee record w/ other contact.
2241 * @param int $contactId
2246 public static function cleanupActivity($contactId) {
2251 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2252 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2254 $transaction = new CRM_Core_Transaction();
2256 // delete activity if there is no record in civicrm_activity_contact
2257 // pointing to any other contact record
2258 $activityContact = new CRM_Activity_DAO_ActivityContact();
2259 $activityContact->contact_id
= $contactId;
2260 $activityContact->record_type_id
= $sourceID;
2261 $activityContact->find();
2263 while ($activityContact->fetch()) {
2264 // delete activity_contact record for the deleted contact
2265 $activityContact->delete();
2267 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2268 $activityContactOther->activity_id
= $activityContact->activity_id
;
2270 // delete activity only if no other contacts connected
2271 if (!$activityContactOther->find(TRUE)) {
2272 $activityParams = array('id' => $activityContact->activity_id
);
2273 $result = self
::deleteActivity($activityParams);
2276 $activityContactOther->free();
2279 $activityContact->free();
2280 $transaction->commit();
2286 * Does user has sufficient permission for view/edit activity record?
2288 * @param int $activityId
2289 * Activity record id.
2290 * @param int $action
2295 public static function checkPermission($activityId, $action) {
2298 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2303 $activity = new CRM_Activity_DAO_Activity();
2304 $activity->id
= $activityId;
2305 if (!$activity->find(TRUE)) {
2309 //component related permissions.
2310 $compPermissions = array(
2311 'CiviCase' => array(
2312 'administer CiviCase',
2313 'access my cases and activities',
2314 'access all cases and activities',
2316 'CiviMail' => array('access CiviMail'),
2317 'CiviEvent' => array('access CiviEvent'),
2318 'CiviGrant' => array('access CiviGrant'),
2319 'CiviPledge' => array('access CiviPledge'),
2320 'CiviMember' => array('access CiviMember'),
2321 'CiviReport' => array('access CiviReport'),
2322 'CiviContribute' => array('access CiviContribute'),
2323 'CiviCampaign' => array('administer CiviCampaign'),
2326 //return early when it is case activity.
2327 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2328 //check for civicase related permission.
2329 if ($isCaseActivity) {
2331 foreach ($compPermissions['CiviCase'] as $per) {
2332 if (CRM_Core_Permission
::check($per)) {
2338 //check for case specific permissions.
2341 if ($action == CRM_Core_Action
::UPDATE
) {
2344 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2346 $activity->activity_type_id
2353 //first check the component permission.
2356 FROM civicrm_option_value val
2357 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2358 WHERE val.value = %2";
2360 1 => array('activity_type', 'String'),
2361 2 => array($activity->activity_type_id
, 'Integer'),
2363 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2366 $componentName = CRM_Core_Component
::getComponentName($componentId);
2367 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2369 //here we are interesting in any single permission.
2370 if (is_array($compPermission)) {
2371 foreach ($compPermission as $per) {
2372 if (CRM_Core_Permission
::check($per)) {
2380 //check for this permission related to contact.
2381 $permission = CRM_Core_Permission
::VIEW
;
2382 if ($action == CRM_Core_Action
::UPDATE
) {
2383 $permission = CRM_Core_Permission
::EDIT
;
2386 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2387 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2388 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2389 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2391 //check for source contact.
2392 if (!$componentId ||
$allow) {
2393 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2394 //account for possibility of activity not having a source contact (as it may have been deleted)
2395 if ($sourceContactId) {
2396 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2400 //check for target and assignee contacts.
2402 //first check for supper permission.
2403 $supPermission = 'view all contacts';
2404 if ($action == CRM_Core_Action
::UPDATE
) {
2405 $supPermission = 'edit all contacts';
2407 $allow = CRM_Core_Permission
::check($supPermission);
2409 //user might have sufficient permission, through acls.
2412 //get the target contacts.
2413 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2414 foreach ($targetContacts as $cnt => $contactId) {
2415 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2421 //get the assignee contacts.
2423 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2424 foreach ($assigneeContacts as $cnt => $contactId) {
2425 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2438 * wrapper for ajax activity selector
2440 * @param array $params
2441 * Associated array for params record id.
2444 * associated array of contact activities
2446 public static function getContactActivitySelector(&$params) {
2447 // format the params
2448 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2449 $params['rowCount'] = $params['rp'];
2450 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2451 $params['caseId'] = NULL;
2452 $context = CRM_Utils_Array
::value('context', $params);
2454 // get contact activities
2455 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2458 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2460 // format params and add links
2461 $contactActivities = array();
2463 if (!empty($activities)) {
2464 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2466 // check logged in user for permission
2467 $page = new CRM_Core_Page();
2468 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2469 $permissions = array($page->_permission
);
2470 if (CRM_Core_Permission
::check('delete activities')) {
2471 $permissions[] = CRM_Core_Permission
::DELETE
;
2474 $mask = CRM_Core_Action
::mask($permissions);
2476 foreach ($activities as $activityId => $values) {
2477 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2478 $contactActivities[$activityId]['subject'] = $values['subject'];
2479 if ($params['contact_id'] == $values['source_contact_id']) {
2480 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2482 elseif ($values['source_contact_id']) {
2483 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'],
2484 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2487 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2490 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2491 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2492 'civicrm/mailing/report/event',
2493 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2495 elseif (!empty($values['recipients'])) {
2496 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2498 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2499 $contactActivities[$activityId]['target_contact'] = '';
2500 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2501 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName,
2502 'civicrm/contact/view', "reset=1&cid={$tcID}");
2505 if ($extraCount = $values['target_contact_counter'] - 1) {
2506 $contactActivities[$activityId]['target_contact'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2509 elseif (!$values['target_contact_name']) {
2510 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2513 if (empty($values['assignee_contact_name'])) {
2514 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2516 elseif (!empty($values['assignee_contact_name'])) {
2518 $contactActivities[$activityId]['assignee_contact'] = '';
2519 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2520 if ($acID && $count < 5) {
2521 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2524 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2528 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2535 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2536 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2538 // add class to this row if overdue
2539 $contactActivities[$activityId]['class'] = '';
2540 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2541 && CRM_Utils_Array
::value('status_id', $values) == 1
2543 $contactActivities[$activityId]['class'] = 'status-overdue';
2546 $contactActivities[$activityId]['class'] = 'status-ontime';
2550 $contactActivities[$activityId]['links'] = '';
2551 $accessMailingReport = FALSE;
2552 if (!empty($values['mailingId'])) {
2553 $accessMailingReport = TRUE;
2556 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2557 CRM_Utils_Array
::value('activity_type_id', $values),
2558 CRM_Utils_Array
::value('source_record_id', $values),
2559 $accessMailingReport,
2560 CRM_Utils_Array
::value('activity_id', $values)
2563 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2565 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2568 'id' => $values['activity_id'],
2569 'cid' => $params['contact_id'],
2571 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2577 $values['activity_id']
2580 $contactActivities[$activityId]['is_recurring_activity'] = $values['is_recurring_activity'];
2584 return $contactActivities;
2588 * copy custom fields and attachments from an existing activity to another.
2589 * @see CRM_Case_Page_AJAX::_convertToCaseActivity()
2591 * @param array $params
2593 public static function copyExtendedActivityData($params) {
2594 // attach custom data to the new activity
2595 $customParams = $htmlType = array();
2596 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2598 if (!empty($customValues)) {
2599 $fieldIds = implode(', ', array_keys($customValues));
2600 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2601 $result = CRM_Core_DAO
::executeQuery($sql);
2603 while ($result->fetch()) {
2604 $htmlType[] = $result->id
;
2607 foreach ($customValues as $key => $value) {
2608 if ($value !== NULL) {
2610 if (in_array($key, $htmlType)) {
2611 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2612 $customParams["custom_{$key}_-1"] = array(
2613 'name' => $fileValues[0],
2614 'path' => $fileValues[1],
2618 $customParams["custom_{$key}_-1"] = $value;
2622 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2623 $params['mainActivityId'], 'Activity'
2627 // copy activity attachments ( if any )
2628 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2632 * @param int $activityId
2633 * @param int $recordTypeID
2634 * @param string $column
2638 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2639 $activityContact = new CRM_Activity_BAO_ActivityContact();
2640 $activityContact->activity_id
= $activityId;
2641 if ($recordTypeID) {
2642 $activityContact->record_type_id
= $recordTypeID;
2644 if ($activityContact->find(TRUE)) {
2645 return $activityContact->$column;
2651 * @param int $activityId
2655 public static function getSourceContactID($activityId) {
2656 static $sourceID = NULL;
2658 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2659 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2662 return self
::getActivityContact($activityId, $sourceID);
2666 * @param array $params
2668 public function setApiFilter(&$params) {
2669 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2671 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2672 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2673 $obj = new CRM_Activity_BAO_ActivityContact();
2674 $params['return.target_contact_id'] = 1;
2675 $this->joinAdd($obj, 'LEFT');
2676 $this->selectAdd('civicrm_activity.*');
2677 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");