3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
48 static $_exportableFields = NULL;
51 * static field for all the activity information that we can potentially import
56 static $_importableFields = NULL;
59 * Check if there is absolute minimum of data to add the object
61 * @param array $params (reference ) an assoc array of name/value pairs
66 public static function dataExists(&$params) {
67 if (CRM_Utils_Array
::value('source_contact_id', $params) ||
68 CRM_Utils_Array
::value('id', $params)
76 * Takes a bunch of params that are needed to match certain criteria and
77 * retrieves the relevant objects. Typically the valid params are only
78 * contact_id. We'll tweak this function to be more full featured over a period
79 * of time. This is the inverse function of create. It also stores all the retrieved
80 * values in the default array
82 * @param array $params (reference ) an assoc array of name/value pairs
83 * @param array $defaults (reference ) an assoc array to hold the flattened values
84 * @param string $activityType activity type
86 * @return object CRM_Core_BAO_Meeting object
89 public static function retrieve(&$params, &$defaults) {
90 $activity = new CRM_Activity_DAO_Activity();
91 $activity->copyValues($params);
93 if ($activity->find(TRUE)) {
94 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
95 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
96 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
97 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
99 // TODO: at some stage we'll have to deal
100 // TODO: with multiple values for assignees and targets, but
101 // TODO: for now, let's just fetch first row
102 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
103 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
104 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
105 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
106 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
107 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
108 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
109 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
111 elseif (CRM_Core_Permission
::check('access CiviMail') ||
112 (CRM_Mailing_Info
::workflowEnabled() &&
113 CRM_Core_Permission
::check('create mailings')
116 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
117 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
121 $defaults['target_contact_value'] = ts('(recipients)');
124 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
125 $defaults['source_contact_id'] = $sourceContactId;
127 if ($sourceContactId &&
128 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
133 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
140 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
142 CRM_Core_DAO
::storeValues($activity, $defaults);
150 * Function to delete the activity
152 * @param array $params associated array
158 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
160 if (CRM_Utils_Array
::value('id', $params) && !is_array($params['id'])) {
161 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
164 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
167 $transaction = new CRM_Core_Transaction();
168 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
169 $sourceRecordIds = implode(',', $params['source_record_id']);
172 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
177 if (!isset($params['id'])) {
178 if (is_array($params['activity_type_id'])) {
179 $activityTypes = implode(',', $params['activity_type_id']);
182 $activityTypes = $params['activity_type_id'];
185 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
186 $dao = CRM_Core_DAO
::executeQuery($query);
189 $activity = new CRM_Activity_DAO_Activity();
190 $activity->copyValues($params);
191 $result = $activity->delete();
194 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
198 $activity = new CRM_Activity_DAO_Activity();
199 $activity->copyValues($params);
201 $activity->is_deleted
= 1;
202 $result = $activity->save();
204 //log activty delete.CRM-4525.
205 $logMsg = 'Case Activity deleted for';
208 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
209 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
210 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
211 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
212 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
213 if ($sourceContactId) {
214 $msgs[] = " source={$sourceContactId}";
217 //get target contacts.
218 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
219 if (!empty($targetContactIds)) {
220 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
222 //get assignee contacts.
223 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
224 if (!empty($assigneeContactIds)) {
225 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
228 $logMsg .= implode(', ', $msgs);
230 self
::logActivityAction($activity, $logMsg);
233 // delete the recently created Activity
235 $activityRecent = array(
236 'id' => $activity->id
,
237 'type' => 'Activity',
239 CRM_Utils_Recent
::del($activityRecent);
242 $transaction->commit();
243 if (isset($activity)) {
245 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
246 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
253 * Delete activity assignment record
255 * @param int $id activity id
260 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
261 $activityContact = new CRM_Activity_BAO_ActivityContact();
262 $activityContact->activity_id
= $activityId;
264 $activityContact->record_type_id
= $recordTypeID;
266 $activityContact->delete();
270 * Function to process the activities
272 * @param object $form form object
273 * @param array $params associated array of the submitted values
274 * @param array $ids array of ids
275 * @param string $activityType activity Type
276 * @param boolean $record true if it is Record Activity
281 public static function create(&$params) {
282 // check required params
283 if (!self
::dataExists($params)) {
284 CRM_Core_Error
::fatal('Not enough data to create activity object,');
287 $activity = new CRM_Activity_DAO_Activity();
289 if (isset($params['id']) && empty($params['id'])) {
290 unset($params['id']);
293 if (!CRM_Utils_Array
::value('status_id', $params) &&
294 !CRM_Utils_Array
::value('activity_status_id', $params) &&
295 !CRM_Utils_Array
::value('id', $params)
297 if (isset($params['activity_date_time']) &&
298 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
300 $params['status_id'] = 2;
303 $params['status_id'] = 1;
307 //set priority to Normal for Auto-populated activities (for Cases)
308 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
309 // if not set and not 0
310 !CRM_Utils_Array
::value('id', $params)
312 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
313 $params['priority_id'] = array_search('Normal', $priority);
316 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
317 $params['target_contact_id'] = array_unique($params['target_contact_id']);
319 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
320 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
324 if (CRM_Utils_Array
::value('id', $params)) {
325 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
328 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
331 $activity->copyValues($params);
332 if (isset($params['case_id'])) {
333 // CRM-8708, preserve case ID even though it's not part of the SQL model
334 $activity->case_id
= $params['case_id'];
336 elseif (is_numeric($activity->id
)) {
337 // CRM-8708, preserve case ID even though it's not part of the SQL model
338 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
342 $transaction = new CRM_Core_Transaction();
344 $result = $activity->save();
346 if (is_a($result, 'CRM_Core_Error')) {
347 $transaction->rollback();
351 $activityId = $activity->id
;
352 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
353 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
354 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
355 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
357 if (isset($params['source_contact_id'])) {
359 'activity_id' => $activityId,
360 'contact_id' => $params['source_contact_id'],
361 'record_type_id' => $sourceID
363 self
::deleteActivityContact($activityId, $sourceID);
364 CRM_Activity_BAO_ActivityContact
::create($acParams);
367 // check and attach and files as needed
368 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
370 // attempt to save activity assignment
371 $resultAssignment = NULL;
372 if (CRM_Utils_Array
::value('assignee_contact_id', $params)) {
374 $assignmentParams = array('activity_id' => $activityId);
376 if (is_array($params['assignee_contact_id'])) {
377 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
378 // first delete existing assignments if any
379 self
::deleteActivityContact($activityId, $assigneeID);
383 foreach ($params['assignee_contact_id'] as $acID) {
385 $values[] = "( $activityId, $acID, $assigneeID )";
388 while (!empty($values)) {
389 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
390 $str = implode(',', $input);
391 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
392 CRM_Core_DAO
::executeQuery($sql);
396 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
397 $assignmentParams['record_type_id'] = $assigneeID;
398 if (CRM_Utils_Array
::value('id', $params)) {
399 $assignment = new CRM_Activity_BAO_ActivityContact();
400 $assignment->activity_id
= $activityId;
401 $assignment->record_type_id
= $assigneeID;
402 $assignment->find(TRUE);
404 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
405 $assignmentParams['id'] = $assignment->id
;
406 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
410 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
415 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
416 self
::deleteActivityContact($activityId, $assigneeID);
420 if (is_a($resultAssignment, 'CRM_Core_Error')) {
421 $transaction->rollback();
422 return $resultAssignment;
425 // attempt to save activity targets
426 $resultTarget = NULL;
427 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
429 $targetParams = array('activity_id' => $activityId);
430 $resultTarget = array();
431 if (is_array($params['target_contact_id'])) {
432 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
433 // first delete existing targets if any
434 self
::deleteActivityContact($activityId, $targetID );
438 foreach ($params['target_contact_id'] as $tid) {
440 $values[] = "( $activityId, $tid, $targetID )";
444 while (!empty($values)) {
445 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
446 $str = implode(',', $input);
447 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
448 CRM_Core_DAO
::executeQuery($sql);
452 $targetParams['contact_id'] = $params['target_contact_id'];
453 $targetParams['record_type_id'] = $targetID;
454 if (CRM_Utils_Array
::value('id', $params)) {
455 $target = new CRM_Activity_BAO_ActivityContact();
456 $target->activity_id
= $activityId;
457 $target->record_type_id
= $targetID;
460 if ($target->contact_id
!= $params['target_contact_id']) {
461 $targetParams['id'] = $target->id
;
462 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
466 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
471 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
472 self
::deleteActivityContact($activityId, $targetID );
476 // write to changelog before transaction is committed/rolled
477 // back (and prepare status to display)
478 if (CRM_Utils_Array
::value('id', $params)) {
479 $logMsg = "Activity (id: {$result->id} ) updated with ";
482 $logMsg = "Activity created for ";
486 if (isset($params['source_contact_id'])) {
487 $msgs[] = "source={$params['source_contact_id']}";
490 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
491 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
492 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
493 // take only first target
494 // will be used for recently viewed display
495 $t = array_slice($params['target_contact_id'], 0, 1);
496 $recentContactId = $t[0];
498 elseif (isset($params['target_contact_id'])) {
499 $msgs[] = "target={$params['target_contact_id']}";
500 // will be used for recently viewed display
501 $recentContactId = $params['target_contact_id'];
505 // at worst, take source for recently viewed display
506 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
509 if (isset($params['assignee_contact_id'])) {
510 if (is_array($params['assignee_contact_id'])) {
511 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
514 $msgs[] = "assignee={$params['assignee_contact_id']}";
517 $logMsg .= implode(', ', $msgs);
519 self
::logActivityAction($result, $logMsg);
521 if (CRM_Utils_Array
::value('custom', $params) &&
522 is_array($params['custom'])
524 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
527 $transaction->commit();
528 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
529 $recentOther = array();
530 if (CRM_Utils_Array
::value('case_id', $params)) {
531 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
532 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
533 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
537 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home";
538 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
539 $url = CRM_Utils_System
::url('civicrm/activity', $q);
540 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
541 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
542 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
546 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
547 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
551 if (CRM_Core_Permission
::check("delete activities")) {
552 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
553 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
558 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
559 if (CRM_Core_Permission
::check('delete activities')) {
560 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
561 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
567 if (!isset($activity->parent_id
)) {
568 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
569 // add the recently created Activity
570 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
571 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
574 if (isset($activitySubject)) {
575 $title = $activitySubject . ' - ';
578 $title = $title . $recentContactDisplay;
579 if (CRM_Utils_Array
::value($activity->activity_type_id
, $activityTypes)) {
580 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
583 CRM_Utils_Recent
::add($title,
588 $recentContactDisplay,
594 // reset the group contact cache since smart groups might be affected due to this
595 CRM_Contact_BAO_GroupContactCache
::remove();
597 if (CRM_Utils_Array
::value('id', $params)) {
598 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
601 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
604 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
606 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
607 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
609 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
611 'activity_id' => $activity->id
,
612 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
614 if ($caseParams['case_id']) {
615 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
618 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
625 public static function logActivityAction($activity, $logMessage = NULL) {
626 $session = CRM_Core_Session
::singleton();
627 $id = $session->get('userID');
629 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
630 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
631 $id = self
::getActivityContact($activity->id
. $sourceID);
634 'entity_table' => 'civicrm_activity',
635 'entity_id' => $activity->id
,
636 'modified_id' => $id,
637 'modified_date' => date('YmdHis'),
638 'data' => $logMessage,
640 CRM_Core_BAO_Log
::add($logParams);
645 * function to get the list Activities
647 * @param array $input array of parameters
649 * - contact_id int contact_id whose activities we want to retrieve
650 * - offset int which row to start from ?
651 * - rowCount int how many rows to fetch
652 * - sort object|array object or array describing sort order for sql query.
653 * - admin boolean if contact is admin
654 * - caseId int case ID
655 * - context string page on which selector is build
656 * - activity_type_id int|string the activitiy types we want to restrict by
658 * @return array (reference) $values the relevant data object values of open activities
663 static function &getActivities($input) {
664 //step 1: Get the basic activity data
665 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
671 $config = CRM_Core_Config
::singleton();
673 $randomNum = md5(uniqid());
674 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
676 $tableFields = array(
677 'activity_id' => 'int unsigned',
678 'activity_date_time' => 'datetime',
679 'source_record_id' => 'int unsigned',
680 'status_id' => 'int unsigned',
681 'subject' => 'varchar(255)',
682 'source_contact_name' => 'varchar(255)',
683 'activity_type_id' => 'int unsigned',
684 'activity_type' => 'varchar(128)',
685 'case_id' => 'int unsigned',
686 'case_subject' => 'varchar(255)',
687 'campaign_id' => 'int unsigned',
690 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
691 $insertValueSQL = array();
692 // The activityTempTable contains the sorted rows
693 // so in order to maintain the sort order as-is we add an auto_increment
694 // field; we can sort by this later to ensure the sort order stays correct.
695 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
696 foreach ($tableFields as $name => $desc) {
697 $sql .= "$name $desc,\n";
698 $insertValueSQL[] = $name;
701 // add unique key on activity_id just to be sure
702 // this cannot be primary key because we need that for the auto_increment
703 // fixed_sort_order field
705 UNIQUE KEY ( activity_id )
706 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
709 CRM_Core_DAO
::executeQuery($sql);
711 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
713 $order = $limit = $groupBy = '';
714 $groupBy = " GROUP BY tbl.activity_id ";
716 if (!empty($input['sort'])) {
717 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
718 $orderBy = $input['sort']->orderBy();
719 if (!empty($orderBy)) {
720 $order = " ORDER BY $orderBy";
723 elseif (trim($input['sort'])) {
724 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
725 $order = " ORDER BY $sort ";
730 // context = 'activity' in Activities tab.
731 $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 ";
734 if (!empty($input['rowCount']) &&
735 $input['rowCount'] > 0
737 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
740 $input['count'] = FALSE;
742 // skip bulk activities in activity tab
743 $input['activity_type_exclude_id'][$bulkActivityTypeID] = $bulkActivityTypeID;
744 list($sqlClause, $params) = self
::getActivitySQLClause($input);
746 $query = "{$insertSQL}
747 SELECT DISTINCT tbl.* from ( {$sqlClause} )
750 //filter case activities - CRM-5761
751 $components = self
::activityComponents();
752 if (!in_array('CiviCase', $components)) {
754 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
755 WHERE civicrm_case_activity.id IS NULL";
758 $query = $query . $groupBy . $order . $limit;
760 $dao = CRM_Core_DAO
::executeQuery($query, $params);
762 // step 2: Get target and assignee contacts for above activities
763 // create temp table for target contacts
764 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
765 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
766 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
767 contact_name varchar(255), is_deleted int unsigned, INDEX index_activity_id( activity_id ) )
768 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
770 CRM_Core_DAO
::executeQuery($query);
772 // note that we ignore bulk email for targets, since we don't show it in selector
774 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
775 SELECT ac.activity_id,
780 FROM {$activityTempTable}
781 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
782 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
783 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
785 CRM_Core_DAO
::executeQuery($query);
787 // step 3: Combine all temp tables to get final query for activity selector
788 // sort by the original sort order, stored in fixed_sort_order
790 SELECT {$activityTempTable}.*,
791 {$activityContactTempTable}.contact_id,
792 {$activityContactTempTable}.record_type_id,
793 {$activityContactTempTable}.contact_name,
794 {$activityContactTempTable}.is_deleted
795 FROM {$activityTempTable}
796 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
797 ORDER BY fixed_sort_order
801 $dao = CRM_Core_DAO
::executeQuery($query);
803 //CRM-3553, need to check user has access to target groups.
804 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
806 (CRM_Core_Permission
::check('access CiviMail')) ||
807 (CRM_Mailing_Info
::workflowEnabled() &&
808 CRM_Core_Permission
::check('create mailings'))
812 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
815 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
816 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
817 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
818 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
821 while ($dao->fetch()) {
822 $activityID = $dao->activity_id
;
823 $values[$activityID]['activity_id'] = $dao->activity_id
;
824 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
825 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
826 $values[$activityID]['activity_type'] = $dao->activity_type
;
827 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
828 $values[$activityID]['status_id'] = $dao->status_id
;
829 $values[$activityID]['subject'] = $dao->subject
;
830 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
832 if ($dao->campaign_id
) {
833 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
836 if (!CRM_Utils_Array
::value('assignee_contact_name', $values[$activityID])) {
837 $values[$activityID]['assignee_contact_name'] = array();
840 if (!CRM_Utils_Array
::value('target_contact_name', $values[$activityID])) {
841 $values[$activityID]['target_contact_name'] = array();
844 // if deleted, wrap in <del>
845 if ( $dao->is_deleted
) {
846 $dao->contact_name
= "<del>{$dao->contact_name}</dao>";
849 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
850 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
851 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
854 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
855 // build array of target / assignee names
856 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
857 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
859 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
860 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
863 // case related fields
864 $values[$activityID]['case_id'] = $dao->case_id
;
865 $values[$activityID]['case_subject'] = $dao->case_subject
;
868 $values[$activityID]['recipients'] = ts('(recipients)');
869 $values[$activityID]['mailingId'] = false;
872 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
874 $values[$activityID]['mailingId'] = true;
883 * Get the component id and name those are enabled and logged in
884 * user has permission. To decide whether we are going to include
885 * component related activities w/ core activity retrieve process.
887 * return an array of component id and name.
890 static function activityComponents() {
891 $components = array();
892 $compInfo = CRM_Core_Component
::getEnabledComponents();
893 foreach ($compInfo as $compObj) {
894 if (CRM_Utils_Array
::value('showActivitiesInCore', $compObj->info
)) {
895 if ($compObj->info
['name'] == 'CiviCampaign') {
896 $componentPermission = "administer {$compObj->name}";
899 $componentPermission = "access {$compObj->name}";
901 if ($compObj->info
['name'] == 'CiviCase') {
902 if (CRM_Case_BAO_Case
::accessCiviCase()) {
903 $components[$compObj->componentID
] = $compObj->info
['name'];
906 elseif (CRM_Core_Permission
::check($componentPermission)) {
907 $components[$compObj->componentID
] = $compObj->info
['name'];
916 * function to get the activity Count
918 * @param array $input array of parameters
920 * - contact_id int contact_id whose activities we want to retrieve
921 * - admin boolean if contact is admin
922 * - caseId int case ID
923 * - context string page on which selector is build
924 * - activity_type_id int|string the activity types we want to restrict by
926 * @return int count of activities
931 static function &getActivitiesCount($input) {
932 // skip bulk activities in activity tab
933 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
938 $input['activity_type_exclude_id'][$bulkActivityTypeID] = $bulkActivityTypeID;
940 $input['count'] = TRUE;
941 list($sqlClause, $params) = self
::getActivitySQLClause($input);
943 //filter case activities - CRM-5761
944 $components = self
::activityComponents();
945 if (!in_array('CiviCase', $components)) {
947 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
948 FROM ( {$sqlClause} ) as tbl
949 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
950 WHERE civicrm_case_activity.id IS NULL";
953 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
956 return CRM_Core_DAO
::singleValueQuery($query, $params);
960 * function to get the activity sql clause to pick activities
962 * @param array $input array of parameters
964 * - contact_id int contact_id whose activities we want to retrieve
965 * - admin boolean if contact is admin
966 * - caseId int case ID
967 * - context string page on which selector is build
968 * - count boolean are we interested in the count clause only?
969 * - activity_type_id int|string the activity types we want to restrict by
971 * @return int count of activities
976 static function getActivitySQLClause($input) {
978 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
980 $config = CRM_Core_Config
::singleton();
981 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
982 $sourceWhere = ' ac.contact_id = %1 ';
983 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
985 $params = array(1 => array($input['contact_id'], 'Integer'));
988 $commonClauses = array(
989 "civicrm_option_group.name = 'activity_type'",
990 "civicrm_activity.is_deleted = 0",
991 "civicrm_activity.is_current_revision = 1",
992 "civicrm_activity.is_test= 0",
995 if ($input['context'] != 'activity') {
996 $commonClauses[] = "civicrm_activity.status_id = 1";
999 //Filter on component IDs.
1000 $components = self
::activityComponents();
1001 if (!empty($components)) {
1002 $componentsIn = implode(',', array_keys($components));
1003 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1006 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1009 // activity type ID clause
1010 if (!empty($input['activity_type_id'])) {
1011 if (is_array($input['activity_type_id'])) {
1012 foreach ($input['activity_type_id'] as $idx => $value) {
1013 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1015 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1018 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1019 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1023 // exclude by activity type clause
1024 if (!empty($input['activity_type_exclude_id'])) {
1025 if (is_array($input['activity_type_exclude_id'])) {
1026 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1027 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1029 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1032 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1033 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1037 $commonClause = implode(' AND ', $commonClauses);
1039 $includeCaseActivities = FALSE;
1040 if (in_array('CiviCase', $components)) {
1041 $includeCaseActivities = TRUE;
1045 // build main activity table select clause
1048 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1049 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1051 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1052 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1055 if (!$input['count']) {
1057 civicrm_activity.activity_date_time,
1058 civicrm_activity.source_record_id,
1059 civicrm_activity.status_id,
1060 civicrm_activity.subject,
1061 contact.sort_name as source_contact_name,
1062 civicrm_option_value.value as activity_type_id,
1063 civicrm_option_value.label as activity_type,
1064 null as case_id, null as case_subject,
1065 civicrm_activity.campaign_id as campaign_id
1069 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)
1074 SELECT civicrm_activity.id as activity_id
1076 from civicrm_activity
1077 left join civicrm_option_value on
1078 civicrm_activity.activity_type_id = civicrm_option_value.value
1079 left join civicrm_option_group on
1080 civicrm_option_group.id = civicrm_option_value.option_group_id
1087 // Build case clause
1088 // or else exclude Inbound Emails that have been filed on a case.
1091 if ($includeCaseActivities) {
1093 if (!$input['count']) {
1095 civicrm_activity.activity_date_time,
1096 civicrm_activity.source_record_id,
1097 civicrm_activity.status_id,
1098 civicrm_activity.subject,
1099 contact.sort_name as source_contact_name,
1100 civicrm_option_value.value as activity_type_id,
1101 civicrm_option_value.label as activity_type,
1102 null as case_id, null as case_subject,
1103 civicrm_activity.campaign_id as campaign_id';
1109 SELECT civicrm_activity.id as activity_id
1111 from civicrm_activity
1112 inner join civicrm_case_activity on
1113 civicrm_case_activity.activity_id = civicrm_activity.id
1114 inner join civicrm_case on
1115 civicrm_case_activity.case_id = civicrm_case.id
1116 inner join civicrm_case_contact on
1117 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1118 left join civicrm_option_value on
1119 civicrm_activity.activity_type_id = civicrm_option_value.value
1120 left join civicrm_option_group on
1121 civicrm_option_group.id = civicrm_option_value.option_group_id
1126 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1127 ( civicrm_option_value.name <> 'Inbound Email' AND
1128 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1134 $returnClause = " {$sourceClause} {$caseClause} ";
1136 return array($returnClause, $params);
1140 * send the message to all the contacts and also insert a
1141 * contact activity in each contacts record
1143 * @param array $contactDetails the array of contact details to send the email
1144 * @param string $subject the subject of the message
1145 * @param string $message the message contents
1146 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1147 * @param int $userID use this userID if set
1148 * @param string $from
1149 * @param array $attachments the array of attachments if any
1150 * @param string $cc cc recipient
1151 * @param string $bcc bcc recipient
1152 * @param array $contactIds contact ids
1153 * @param string $additionalDetails the additional information of CC and BCC appended to the activity Details
1155 * @return array ( sent, activityId) if any email is sent and activityId
1159 static function sendEmail(
1167 $attachments = NULL,
1170 $contactIds, // FIXME a param with no default shouldn't be last
1171 $additionalDetails = NULL
1173 // get the contact details of logged in contact, which we set as from email
1174 if ($userID == NULL) {
1175 $session = CRM_Core_Session
::singleton();
1176 $userID = $session->get('userID');
1179 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1181 return array(count($contactDetails), 0, count($contactDetails));
1183 if (!trim($fromDisplayName)) {
1184 $fromDisplayName = $fromEmail;
1188 // token replacement of addressee/email/postal greetings
1189 // get the tokens added in subject and message
1190 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1191 $messageToken = CRM_Utils_Token
::getTokens($text);
1192 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1193 $allTokens = array_merge($messageToken, $subjectToken);
1196 $from = "$fromDisplayName <$fromEmail>";
1199 //create the meta level record first ( email activity )
1200 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1205 // CRM-6265: save both text and HTML parts in details (if present)
1206 if ($html and $text) {
1207 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1210 $details = $html ?
$html : $text;
1211 $details .= $additionalDetails;
1214 $activityParams = array(
1215 'source_contact_id' => $userID,
1216 'activity_type_id' => $activityTypeID,
1217 'activity_date_time' => date('YmdHis'),
1218 'subject' => $subject,
1219 'details' => $details,
1220 // FIXME: check for name Completed and get ID from that lookup
1224 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1225 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1227 // add the attachments to activity params here
1229 // first process them
1230 $activityParams = array_merge($activityParams,
1235 $activity = self
::create($activityParams);
1237 // get the set of attachments from where they are stored
1238 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1241 $returnProperties = array();
1242 if (isset($messageToken['contact'])) {
1243 foreach ($messageToken['contact'] as $key => $value) {
1244 $returnProperties[$value] = 1;
1248 if (isset($subjectToken['contact'])) {
1249 foreach ($subjectToken['contact'] as $key => $value) {
1250 if (!isset($returnProperties[$value])) {
1251 $returnProperties[$value] = 1;
1257 // get token details for contacts, call only if tokens are used
1259 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1260 list($details) = CRM_Utils_Token
::getTokenDetails(
1265 'CRM_Activity_BAO_Activity'
1271 CRM_Utils_Hook
::tokens($tokens);
1272 $categories = array_keys($tokens);
1274 $escapeSmarty = FALSE;
1275 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1276 $smarty = CRM_Core_Smarty
::singleton();
1277 $escapeSmarty = TRUE;
1280 $sent = $notSent = array();
1281 foreach ($contactDetails as $values) {
1282 $contactId = $values['contact_id'];
1283 $emailAddress = $values['email'];
1285 if (!empty($details) && is_array($details["{$contactId}"])) {
1286 // unset email from details since it always returns primary email address
1287 unset($details["{$contactId}"]['email']);
1288 unset($details["{$contactId}"]['email_id']);
1289 $values = array_merge($values, $details["{$contactId}"]);
1292 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1293 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1296 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1297 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1298 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1304 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1305 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1306 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1312 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1313 // also add the contact tokens to the template
1314 $smarty->assign_by_ref('contact', $values);
1316 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1317 $tokenText = $smarty->fetch("string:$tokenText");
1318 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1322 if (self
::sendMessage(
1339 return array($sent, $activity->id
);
1342 static function sendSMS(&$contactDetails,
1344 &$smsParams = array(),
1348 if ($userID == NULL) {
1349 $session = CRM_Core_Session
::singleton();
1350 $userID = $session->get('userID');
1353 $text = &$activityParams['text_message'];
1354 $html = &$activityParams['html_message'];
1357 // token replacement of addressee/email/postal greetings
1358 // get the tokens added in subject and message
1359 $messageToken = CRM_Utils_Token
::getTokens($text);
1360 $messageToken = array_merge($messageToken,
1361 CRM_Utils_Token
::getTokens($html)
1364 //create the meta level record first ( sms activity )
1365 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1370 // CRM-6265: save both text and HTML parts in details (if present)
1371 if ($html and $text) {
1372 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1375 $details = $html ?
$html : $text;
1378 $activitySubject = $activityParams['activity_subject'];
1379 $activityParams = array(
1380 'source_contact_id' => $userID,
1381 'activity_type_id' => $activityTypeID,
1382 'activity_date_time' => date('YmdHis'),
1383 'subject' => $activitySubject,
1384 'details' => $details,
1385 // FIXME: check for name Completed and get ID from that lookup
1389 $activity = self
::create($activityParams);
1390 $activityID = $activity->id
;
1392 $returnProperties = array();
1394 if (isset($messageToken['contact'])) {
1395 foreach ($messageToken['contact'] as $key => $value) {
1396 $returnProperties[$value] = 1;
1402 CRM_Utils_Hook
::tokens($tokens);
1403 $categories = array_keys($tokens);
1405 // get token details for contacts, call only if tokens are used
1407 if (!empty($returnProperties) ||
!empty($tokens)) {
1408 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1412 'CRM_Activity_BAO_Activity'
1417 $escapeSmarty = FALSE;
1419 foreach ($contactDetails as $values) {
1420 $contactId = $values['contact_id'];
1422 if (!empty($details) && is_array($details["{$contactId}"])) {
1423 // unset email from details since it always returns primary email address
1424 unset($details["{$contactId}"]['email']);
1425 unset($details["{$contactId}"]['email_id']);
1426 $values = array_merge($values, $details["{$contactId}"]);
1429 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1430 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1432 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1433 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1435 // Only send if the phone is of type mobile
1436 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1437 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1438 $smsParams['To'] = $values['phone'];
1441 $smsParams['To'] = '';
1444 $sendResult = self
::sendSMSMessage(
1453 if (PEAR
::isError($sendResult)) {
1454 // Collect all of the PEAR_Error objects
1455 $errMsgs[] = $sendResult;
1461 // If at least one message was sent and no errors
1462 // were generated then return a boolean value of TRUE.
1463 // Otherwise, return FALSE (no messages sent) or
1464 // and array of 1 or more PEAR_Error objects.
1466 if ($success > 0 && count($errMsgs) == 0) {
1468 } elseif (count($errMsgs) > 0) {
1472 return array($sent, $activity->id
, $success);
1476 * send the sms message to a specific contact
1478 * @param int $toID the contact id of the recipient
1479 * @param int $activityID the activity ID that tracks the message
1480 * @param array $smsParams the params used for sending sms
1482 * @return mixed true on success or PEAR_Error object
1486 static function sendSMSMessage($toID,
1489 $smsParams = array(),
1494 $toPhoneNumber = "";
1496 if ($smsParams['To']) {
1497 $toPhoneNumber = trim($smsParams['To']);
1500 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1501 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1502 //to get primary mobile ph,if not get a first mobile ph
1503 if (!empty($toPhoneNumbers)) {
1504 $toPhoneNumerDetails = reset($toPhoneNumbers);
1505 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1506 //contact allows to send sms
1511 // make sure both phone are valid
1512 // and that the recipient wants to receive sms
1513 if (empty($toPhoneNumber) or $toDoNotSms) {
1514 return PEAR
::raiseError(
1515 'Recipient phone number is invalid or recipient does not want to receive SMS',
1521 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1522 $recipient = $smsParams['To'];
1523 $smsParams['contact_id'] = $toID;
1524 $smsParams['parent_activity_id'] = $activityID;
1526 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1527 $sendResult = $providerObj->send($recipient, $smsParams, $message, NULL, $userID);
1528 if (PEAR
::isError($sendResult)) {
1532 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1533 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1536 // add activity target record for every sms that is send
1537 $activityTargetParams = array(
1538 'activity_id' => $activityID,
1539 'contact_id' => $toID,
1540 'record_type_id' => $targetID
1542 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1548 * send the message to a specific contact
1550 * @param string $from the name and email of the sender
1551 * @param int $toID the contact id of the recipient
1552 * @param string $subject the subject of the message
1553 * @param string $message the message contents
1554 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1555 * @param int $activityID the activity ID that tracks the message
1557 * @return boolean true if successfull else false.
1561 static function sendMessage($from,
1569 $attachments = NULL,
1573 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1574 if ($emailAddress) {
1575 $toEmail = trim($emailAddress);
1578 // make sure both email addresses are valid
1579 // and that the recipient wants to receive email
1580 if (empty($toEmail) or $toDoNotEmail) {
1583 if (!trim($toDisplayName)) {
1584 $toDisplayName = $toEmail;
1587 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1588 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1589 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1590 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1592 // create the params array
1593 $mailParams = array(
1594 'groupName' => 'Activity Email Sender',
1596 'toName' => $toDisplayName,
1597 'toEmail' => $toEmail,
1598 'subject' => $subject,
1601 'text' => $text_message,
1602 'html' => $html_message,
1603 'attachments' => $attachments,
1606 if (!CRM_Utils_Mail
::send($mailParams)) {
1610 // add activity target record for every mail that is send
1611 $activityTargetParams = array(
1612 'activity_id' => $activityID,
1613 'contact_id' => $toID,
1614 'record_type_id' => $targetID
1616 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1621 * combine all the importable fields from the lower levels object
1623 * The ordering is important, since currently we do not have a weight
1624 * scheme. Adding weight is super important and should be done in the
1625 * next week or so, before this can be called complete.
1629 * @return array array of importable Fields
1633 static function &importableFields($status = FALSE) {
1634 if (!self
::$_importableFields) {
1635 if (!self
::$_importableFields) {
1636 self
::$_importableFields = array();
1639 $fields = array('' => array('title' => ts('- do not import -')));
1642 $fields = array('' => array('title' => ts('- Activity Fields -')));
1645 $tmpFields = CRM_Activity_DAO_Activity
::import();
1646 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1648 // Using new Dedupe rule.
1649 $ruleParams = array(
1650 'contact_type' => 'Individual',
1651 'used' => 'Unsupervised',
1653 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1655 $tmpConatctField = array();
1656 if (is_array($fieldsArray)) {
1657 foreach ($fieldsArray as $value) {
1658 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1663 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1664 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1665 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1668 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1669 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1670 $fields = array_merge($fields, $tmpConatctField);
1671 $fields = array_merge($fields, $tmpFields);
1672 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1673 self
::$_importableFields = $fields;
1675 return self
::$_importableFields;
1679 * To get the Activities of a target contact
1681 * @param $contactId Integer ContactId of the contact whose activities
1684 * @return array array of activity fields
1687 static function getContactActivity($contactId) {
1688 $activities = array();
1689 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1690 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1691 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1692 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1695 // First look for activities where contactId is one of the targets
1697 SELECT activity_id, record_type_id
1698 FROM civicrm_activity_contact
1699 WHERE contact_id = $contactId
1701 $dao = CRM_Core_DAO
::executeQuery($query);
1702 while ($dao->fetch()) {
1703 if ($dao->record_type_id
== $targetID ) {
1704 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1706 else if ($dao->record_type_id
== $assigneeID) {
1707 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1710 // do source stuff here
1711 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1715 $activityIds = array_keys($activities);
1716 if (count($activityIds) < 1) {
1720 $activityIds = implode(',', $activityIds);
1722 SELECT activity.id as activity_id,
1724 subject, location, activity_date_time, details, status_id
1725 FROM civicrm_activity activity
1726 WHERE activity.id IN ($activityIds)";
1728 $dao = CRM_Core_DAO
::executeQuery($query);
1730 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1731 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1733 while ($dao->fetch()) {
1734 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1735 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1736 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1737 $activities[$dao->activity_id
]['location'] = $dao->location
;
1738 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1739 $activities[$dao->activity_id
]['details'] = $dao->details
;
1740 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1741 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1742 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1744 // set to null if not set
1745 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1746 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1753 * Function to add activity for Membership/Event/Contribution
1755 * @param object $activity (reference) particular component object
1756 * @param string $activityType for Membership Signup or Renewal
1762 static function addActivity(&$activity,
1763 $activityType = 'Membership Signup',
1764 $targetContactID = NULL
1766 if ($activity->__table
== 'civicrm_membership') {
1767 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1769 if (!$membershipType) {
1770 $membershipType = ts('Membership');
1773 $subject = "{$membershipType}";
1775 if (!empty($activity->source
) && $activity->source
!= 'null') {
1776 $subject .= " - {$activity->source}";
1779 if ($activity->owner_membership_id
) {
1782 FROM civicrm_contact, civicrm_membership
1783 WHERE civicrm_contact.id = civicrm_membership.contact_id
1784 AND civicrm_membership.id = $activity->owner_membership_id
1786 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1787 $subject .= " (by {$displayName})";
1790 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1791 // CRM-72097 changed from start date to today
1792 $date = date('YmdHis');
1793 $component = 'Membership';
1795 elseif ($activity->__table
== 'civicrm_participant') {
1796 $event = CRM_Event_BAO_Event
::getEvents(1, $activity->event_id
, TRUE, FALSE);
1798 $roles = CRM_Event_PseudoConstant
::participantRole();
1799 $status = CRM_Event_PseudoConstant
::participantStatus();
1801 $subject = $event[$activity->event_id
];
1802 if (CRM_Utils_Array
::value($activity->role_id
, $roles)) {
1803 $subject .= ' - ' . $roles[$activity->role_id
];
1805 if (CRM_Utils_Array
::value($activity->status_id
, $status)) {
1806 $subject .= ' - ' . $status[$activity->status_id
];
1808 $date = date('YmdHis');
1809 if ($activityType != 'Email') {
1810 $activityType = 'Event Registration';
1812 $component = 'Event';
1814 elseif ($activity->__table
== 'civicrm_contribution') {
1815 //create activity record only for Completed Contributions
1816 if ($activity->contribution_status_id
!= 1) {
1822 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1823 if (!empty($activity->source
) && $activity->source
!= 'null') {
1824 $subject .= " - {$activity->source}";
1826 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1827 $activityType = $component = 'Contribution';
1829 $activityParams = array(
1830 'source_contact_id' => $activity->contact_id
,
1831 'source_record_id' => $activity->id
,
1832 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1836 'subject' => $subject,
1837 'activity_date_time' => $date,
1838 'is_test' => $activity->is_test
,
1839 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1843 'skipRecentView' => TRUE,
1844 'campaign_id' => $activity->campaign_id
,
1847 // create activity with target contacts
1848 $session = CRM_Core_Session
::singleton();
1849 $id = $session->get('userID');
1851 $activityParams['source_contact_id'] = $id;
1852 $activityParams['target_contact_id'][] = $activity->contact_id
;
1856 if ($targetContactID) {
1857 $activityParams['target_contact_id'][] = $targetContactID;
1859 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1860 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1866 * Function to get Parent activity for currently viewed activity
1868 * @param int $activityId current activity id
1870 * @return int $parentId Id of parent activity otherwise false.
1873 static function getParentActivity($activityId) {
1874 static $parentActivities = array();
1876 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1878 if (!array_key_exists($activityId, $parentActivities)) {
1879 $parentActivities[$activityId] = array();
1881 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1886 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1889 return $parentActivities[$activityId];
1893 * Function to get total count of prior revision of currently viewd activity
1895 * @param int $activityId current activity id
1897 * @return int $params count of prior activities otherwise false.
1900 static function getPriorCount($activityID) {
1901 static $priorCounts = array();
1903 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1905 if (!array_key_exists($activityID, $priorCounts)) {
1906 $priorCounts[$activityID] = array();
1907 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1914 SELECT count( id ) AS cnt
1915 FROM civicrm_activity
1916 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1917 AND is_current_revision = 0
1918 AND id < {$activityID}
1920 $params = array(1 => array($originalID, 'Integer'));
1921 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1923 $priorCounts[$activityID] = $count ?
$count : 0;
1926 return $priorCounts[$activityID];
1930 * Function to get all prior activities of currently viewe
1933 * @param int $activityId current activity id
1935 * @return array $result prior activities info.
1938 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1939 static $priorActivities = array();
1941 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1942 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1944 if (!array_key_exists($index, $priorActivities)) {
1945 $priorActivities[$index] = array();
1947 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1953 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1954 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1955 WHERE (ca.id = %1 OR ca.original_id = %1)
1956 AND cl.entity_table = 'civicrm_activity'
1957 AND cl.entity_id = ca.id
1958 AND cl.modified_id = c.id
1960 if ($onlyPriorRevisions) {
1961 $query .= " AND ca.id < {$activityID}";
1963 $query .= " ORDER BY ca.id DESC";
1965 $params = array(1 => array($originalID, 'Integer'));
1966 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1968 while ($dao->fetch()) {
1969 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1970 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1971 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1972 $priorActivities[$index][$dao->activityID
]['link'] = 'javascript:viewActivity( $dao->activityID );';
1977 return $priorActivities[$index];
1981 * Function to find the latest revision of a given activity
1983 * @param int $activityId prior activity id
1985 * @return int $params current activity id.
1988 static function getLatestActivityId($activityID) {
1989 static $latestActivityIds = array();
1991 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1993 if (!array_key_exists($activityID, $latestActivityIds)) {
1994 $latestActivityIds[$activityID] = array();
1996 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2001 $activityID = $originalID;
2003 $params = array(1 => array($activityID, 'Integer'));
2004 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2006 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2009 return $latestActivityIds[$activityID];
2013 * Function to create a follow up a given activity
2015 * @activityId int activity id of parent activity
2017 * @param array $activity details
2021 static function createFollowupActivity($activityId, $params) {
2026 $session = CRM_Core_Session
::singleton();
2028 $followupParams = array();
2029 $followupParams['parent_id'] = $activityId;
2030 $followupParams['source_contact_id'] = $session->get('userID');
2031 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2033 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2034 // Get Subject of Follow-up Activiity, CRM-4491
2035 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2037 //create target contact for followup
2038 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2039 $followupParams['target_contact_id'] = $params['target_contact_id'];
2042 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2043 $params['followup_date_time']
2045 $followupActivity = self
::create($followupParams);
2047 return $followupActivity;
2051 * Function to get Activity specific File according activity type Id.
2053 * @param int $activityTypeId activity id
2055 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2059 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2060 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2062 if ($activityTypes[$activityTypeId]['name']) {
2063 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2069 global $civicrm_root;
2070 $config = CRM_Core_Config
::singleton();
2071 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2072 if (empty($config->customPHPPathDir
)) {
2075 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2080 return $activityTypeFile;
2084 * Function to restore the activity
2086 * @param array $params associated array
2092 public static function restoreActivity(&$params) {
2093 $activity = new CRM_Activity_DAO_Activity();
2094 $activity->copyValues($params);
2096 $activity->is_deleted
= 0;
2097 $result = $activity->save();
2103 * Get the exportable fields for Activities
2105 * @param string $name if it is called by case $name = Case else $name = Activity
2107 * @return array array of exportable Fields
2111 static function &exportableFields($name = 'Activity') {
2112 if (!isset(self
::$_exportableFields[$name])) {
2113 self
::$_exportableFields[$name] = array();
2115 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2116 // my case hence we have defined fields as case_*
2117 if ($name == 'Activity') {
2118 $exportableFields = CRM_Activity_DAO_Activity
::export();
2119 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2120 $exportableFields['source_contact'] = array(
2121 'title' => ts('Source Contact'),
2122 'type' => CRM_Utils_Type
::T_STRING
,
2126 $Activityfields = array(
2127 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2128 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2130 $fields = array_merge($Activityfields, $exportableFields);
2133 //set title to activity fields
2135 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2136 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2137 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2138 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2139 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2140 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2141 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2142 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2143 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2144 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2147 // add custom data for cases
2148 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2151 // add custom data for case activities
2152 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2154 self
::$_exportableFields[$name] = $fields;
2156 return self
::$_exportableFields[$name];
2160 * Get the allowed profile fields for Activities
2162 * @return array array of activity profile Fields
2165 static function getProfileFields() {
2166 $exportableFields = self
::exportableFields('Activity');
2167 $skipFields = array(
2170 'source_contact_id',
2172 'activity_campaign',
2174 'is_current_revision',
2175 'activity_is_deleted',
2177 $config = CRM_Core_Config
::singleton();
2178 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2179 $skipFields[] = 'activity_engagement_level';
2182 foreach ($skipFields as $field) {
2183 if (isset($exportableFields[$field])) {
2184 unset($exportableFields[$field]);
2188 // hack to use 'activity_type_id' instead of 'activity_type'
2189 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2190 unset($exportableFields['activity_status']);
2192 return $exportableFields;
2196 * This function deletes the activity record related to contact record,
2197 * when there are no target and assignee record w/ other contact.
2199 * @param int $contactId contactId
2204 public static function cleanupActivity($contactId) {
2209 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2210 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2212 $transaction = new CRM_Core_Transaction();
2214 // delete activity if there is no record in civicrm_activity_contact
2215 // pointing to any other contact record
2216 $activityContact = new CRM_Activity_DAO_ActivityContact();
2217 $activityContact->contact_id
= $contactId;
2218 $activityContact->record_type_id
= $sourceID;
2219 $activityContact->find();
2221 while ($activityContact->fetch()) {
2222 // delete activity_contact record for the deleted contact
2223 $activityContact->delete();
2225 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2226 $activityContactOther->activity_id
= $activityContact->activity_id
;
2228 // delete activity only if no other contacts connected
2229 if ( ! $activityContactOther->find(TRUE) ) {
2230 $activityParams = array('id' => $activityContact->activity_id
);
2231 $result = self
::deleteActivity($activityParams);
2234 $activityContactOther->free();
2237 $activityContact->free();
2238 $transaction->commit();
2244 * Does user has sufficient permission for view/edit activity record.
2246 * @param int $activityId activity record id.
2247 * @param int $action edit/view
2249 * @return boolean $allow true/false
2252 public static function checkPermission($activityId, $action) {
2255 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2260 $activity = new CRM_Activity_DAO_Activity();
2261 $activity->id
= $activityId;
2262 if (!$activity->find(TRUE)) {
2266 //component related permissions.
2267 $compPermissions = array(
2268 'CiviCase' => array('administer CiviCase',
2269 'access my cases and activities',
2270 'access all cases and activities',
2272 'CiviMail' => array('access CiviMail'),
2273 'CiviEvent' => array('access CiviEvent'),
2274 'CiviGrant' => array('access CiviGrant'),
2275 'CiviPledge' => array('access CiviPledge'),
2276 'CiviMember' => array('access CiviMember'),
2277 'CiviReport' => array('access CiviReport'),
2278 'CiviContribute' => array('access CiviContribute'),
2279 'CiviCampaign' => array('administer CiviCampaign'),
2282 //return early when it is case activity.
2283 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2284 //check for civicase related permission.
2285 if ($isCaseActivity) {
2287 foreach ($compPermissions['CiviCase'] as $per) {
2288 if (CRM_Core_Permission
::check($per)) {
2294 //check for case specific permissions.
2297 if ($action == CRM_Core_Action
::UPDATE
) {
2300 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2302 $activity->activity_type_id
2309 //first check the component permission.
2312 FROM civicrm_option_value val
2313 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2314 WHERE val.value = %2";
2315 $params = array(1 => array('activity_type', 'String'),
2316 2 => array($activity->activity_type_id
, 'Integer'),
2318 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2321 $componentName = CRM_Core_Component
::getComponentName($componentId);
2322 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2324 //here we are interesting in any single permission.
2325 if (is_array($compPermission)) {
2326 foreach ($compPermission as $per) {
2327 if (CRM_Core_Permission
::check($per)) {
2335 //check for this permission related to contact.
2336 $permission = CRM_Core_Permission
::VIEW
;
2337 if ($action == CRM_Core_Action
::UPDATE
) {
2338 $permission = CRM_Core_Permission
::EDIT
;
2341 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2342 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2343 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2344 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2346 //check for source contact.
2347 if (!$componentId ||
$allow) {
2348 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2349 //account for possibility of activity not having a source contact (as it may have been deleted)
2350 if ( $sourceContactId ) {
2351 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2355 //check for target and assignee contacts.
2357 //first check for supper permission.
2358 $supPermission = 'view all contacts';
2359 if ($action == CRM_Core_Action
::UPDATE
) {
2360 $supPermission = 'edit all contacts';
2362 $allow = CRM_Core_Permission
::check($supPermission);
2364 //user might have sufficient permission, through acls.
2367 //get the target contacts.
2368 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2369 foreach ($targetContacts as $cnt => $contactId) {
2370 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2376 //get the assignee contacts.
2378 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2379 foreach ($assigneeContacts as $cnt => $contactId) {
2380 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2393 * This function is a wrapper for ajax activity selector
2395 * @param array $params associated array for params record id.
2397 * @return array $contactActivities associated array of contact activities
2400 public static function getContactActivitySelector(&$params) {
2401 // format the params
2402 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2403 $params['rowCount'] = $params['rp'];
2404 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2405 $params['caseId'] = NULL;
2406 $context = CRM_Utils_Array
::value('context', $params);
2408 // get contact activities
2409 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2412 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2414 // format params and add links
2415 $contactActivities = array();
2417 if (!empty($activities)) {
2418 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2420 // check logged in user for permission
2421 $page = new CRM_Core_Page();
2422 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2423 $permissions = array($page->_permission
);
2424 if (CRM_Core_Permission
::check('delete activities')) {
2425 $permissions[] = CRM_Core_Permission
::DELETE
;
2428 $mask = CRM_Core_Action
::mask($permissions);
2430 foreach ($activities as $activityId => $values) {
2431 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2432 $contactActivities[$activityId]['subject'] = $values['subject'];
2433 if ($params['contact_id'] == $values['source_contact_id']) {
2434 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2436 elseif ($values['source_contact_id']) {
2437 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'],
2438 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2441 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2444 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2445 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2446 'civicrm/mailing/report/event',
2447 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2449 elseif (CRM_Utils_Array
::value('recipients', $values)) {
2450 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2452 elseif (!$values['target_contact_name']) {
2453 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2455 elseif (!empty($values['target_contact_name'])) {
2457 $contactActivities[$activityId]['target_contact'] = '';
2458 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2459 if ($tcID && $count < 5) {
2460 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName,
2461 'civicrm/contact/view', "reset=1&cid={$tcID}");
2464 $contactActivities[$activityId]['target_contact'] .= "; ";
2468 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2475 if (empty($values['assignee_contact_name'])) {
2476 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2478 elseif (!empty($values['assignee_contact_name'])) {
2480 $contactActivities[$activityId]['assignee_contact'] = '';
2481 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2482 if ($acID && $count < 5) {
2483 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2486 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2490 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2497 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2498 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2500 // add class to this row if overdue
2501 $contactActivities[$activityId]['class'] = '';
2502 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2503 && CRM_Utils_Array
::value('status_id', $values) == 1
2505 $contactActivities[$activityId]['class'] = 'status-overdue';
2508 $contactActivities[$activityId]['class'] = 'status-ontime';
2512 $contactActivities[$activityId]['links'] = '';
2513 $accessMailingReport = FALSE;
2514 if (CRM_Utils_Array
::value('mailingId', $values)) {
2515 $accessMailingReport = TRUE;
2518 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2519 CRM_Utils_Array
::value('activity_type_id', $values),
2520 CRM_Utils_Array
::value('source_record_id', $values),
2521 $accessMailingReport,
2522 CRM_Utils_Array
::value('activity_id', $values)
2525 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2527 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2530 'id' => $values['activity_id'],
2531 'cid' => $params['contact_id'],
2533 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2539 return $contactActivities;
2543 * Used to copy custom fields and attachments from an existing activity to another.
2544 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2546 static function copyExtendedActivityData($params) {
2547 // attach custom data to the new activity
2548 $customParams = $htmlType = array();
2549 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2551 if (!empty($customValues)) {
2552 $fieldIds = implode(', ', array_keys($customValues));
2553 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2554 $result = CRM_Core_DAO
::executeQuery($sql);
2556 while ($result->fetch()) {
2557 $htmlType[] = $result->id
;
2560 foreach ($customValues as $key => $value) {
2561 if ($value !== NULL) { // CRM-10542
2562 if (in_array($key, $htmlType)) {
2563 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2564 $customParams["custom_{$key}_-1"] = array(
2565 'name' => $fileValues[0],
2566 'path' => $fileValues[1],
2570 $customParams["custom_{$key}_-1"] = $value;
2574 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2575 $params['mainActivityId'], 'Activity'
2579 // copy activity attachments ( if any )
2580 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2583 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2584 $activityContact = new CRM_Activity_BAO_ActivityContact();
2585 $activityContact->activity_id
= $activityId;
2586 if ($recordTypeID) {
2587 $activityContact->record_type_id
= $recordTypeID;
2589 if ($activityContact->find(TRUE)) {
2590 return $activityContact->$column;
2595 public static function getSourceContactID($activityId) {
2596 static $sourceID = NULL;
2598 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2599 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2602 return self
::getActivityContact($activityId, $sourceID);
2605 function setApiFilter(&$params) {
2606 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2608 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2609 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2610 $obj = new CRM_Activity_BAO_ActivityContact();
2611 $params['return.target_contact_id'] = 1;
2612 $this->joinAdd($obj, 'LEFT');
2613 $this->selectAdd('civicrm_activity.*');
2614 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");