3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 // TODO: at some stage we'll have to deal
95 // TODO: with multiple values for assignees and targets, but
96 // TODO: for now, let's just fetch first row
97 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityAssignment
::retrieveAssigneeIdsByActivityId($activity->id
);
98 $assignee_contact_names = CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames($activity->id
);
100 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
102 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
103 $defaults['target_contact'] = CRM_Activity_BAO_ActivityTarget
::retrieveTargetIdsByActivityId($activity->id
);
104 $target_contact_names = CRM_Activity_BAO_ActivityTarget
::getTargetNames($activity->id
);
106 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
108 elseif (CRM_Core_Permission
::check('access CiviMail') ||
109 (CRM_Mailing_Info
::workflowEnabled() &&
110 CRM_Core_Permission
::check('create mailings')
113 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
114 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$activity->source_contact_id}&context=activity"
118 $defaults['target_contact_value'] = ts('(recipients)');
121 if ($activity->source_contact_id
&&
122 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
123 $activity->source_contact_id
,
127 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
128 $activity->source_contact_id
,
134 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
136 CRM_Core_DAO
::storeValues($activity, $defaults);
144 * Function to delete the activity
146 * @param array $params associated array
152 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
154 if (CRM_Utils_Array
::value('id', $params) && !is_array($params['id'])) {
155 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
158 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
161 $transaction = new CRM_Core_Transaction();
162 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
163 $sourceRecordIds = implode(',', $params['source_record_id']);
166 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
171 if (!isset($params['id'])) {
172 if (is_array($params['activity_type_id'])) {
173 $activityTypes = implode(',', $params['activity_type_id']);
176 $activityTypes = $params['activity_type_id'];
179 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
180 $dao = CRM_Core_DAO
::executeQuery($query);
183 $activity = new CRM_Activity_DAO_Activity();
184 $activity->copyValues($params);
185 $result = $activity->delete();
188 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
192 $activity = new CRM_Activity_DAO_Activity();
193 $activity->copyValues($params);
195 $activity->is_deleted
= 1;
196 $result = $activity->save();
198 //log activty delete.CRM-4525.
199 $logMsg = 'Case Activity deleted for';
201 $sourceContactId = CRM_Core_DAO
::getfieldValue('CRM_Activity_DAO_Activity',
202 $activity->id
, 'source_contact_id'
204 if ($sourceContactId) {
205 $msgs[] = " source={$sourceContactId}";
207 //get target contacts.
208 $targetContactIds = CRM_Activity_BAO_ActivityTarget
::getTargetNames($activity->id
);
209 if (!empty($targetContactIds)) {
210 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
212 //get assignee contacts.
213 $assigneeContactIds = CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames($activity->id
);
214 if (!empty($assigneeContactIds)) {
215 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
218 $logMsg .= implode(', ', $msgs);
220 self
::logActivityAction($activity, $logMsg);
223 // delete the recently created Activity
225 $activityRecent = array(
226 'id' => $activity->id
,
227 'type' => 'Activity',
229 CRM_Utils_Recent
::del($activityRecent);
232 $transaction->commit();
233 if (isset($activity)) {
235 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
236 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
243 * Delete activity assignment record
245 * @param int $id activity id
250 public static function deleteActivityAssignment($activityId) {
251 $assignment = new CRM_Activity_BAO_ActivityAssignment();
252 $assignment->activity_id
= $activityId;
253 $assignment->record_type
= 'Assignee';
254 $assignment->delete();
258 * Delete activity target record
260 * @param int $id activity id
265 public static function deleteActivityTarget($activityId) {
266 $target = new CRM_Activity_BAO_ActivityTarget();
267 $target->activity_id
= $activityId;
268 $target->record_type
= 'Target';
273 * Create activity target record
275 * @param array activity_id, target_contact_id
280 static function createActivityTarget($params) {
281 if (!$params['target_contact_id']) {
285 $target = new CRM_Activity_BAO_ActivityTarget();
286 $target->activity_id
= $params['activity_id'];
287 $target->target_contact_id
= $params['target_contact_id'];
288 // avoid duplicate entries, CRM-7484
289 // happens if sending email to the same contact with different email addresses
290 if (!$target->find(TRUE)) {
296 * Create activity assignment record
298 * @param array activity_id, assignee_contact_id
303 static function createActivityAssignment($params) {
304 if (!$params['assignee_contact_id']) {
307 $assignee = new CRM_Activity_BAO_ActivityAssignment();
308 $assignee->activity_id
= $params['activity_id'];
309 $assignee->assignee_contact_id
= $params['assignee_contact_id'];
314 * Function to process the activities
316 * @param object $form form object
317 * @param array $params associated array of the submitted values
318 * @param array $ids array of ids
319 * @param string $activityType activity Type
320 * @param boolean $record true if it is Record Activity
325 public static function create(&$params) {
326 // check required params
327 if (!self
::dataExists($params)) {
328 CRM_Core_Error
::fatal('Not enough data to create activity object,');
331 $activity = new CRM_Activity_DAO_Activity();
333 if (isset($params['id']) && empty($params['id'])) {
334 unset($params['id']);
337 if (!CRM_Utils_Array
::value('status_id', $params) &&
338 !CRM_Utils_Array
::value('activity_status_id', $params) &&
339 !CRM_Utils_Array
::value('id', $params)
341 if (isset($params['activity_date_time']) &&
342 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
344 $params['status_id'] = 2;
347 $params['status_id'] = 1;
351 //set priority to Normal for Auto-populated activities (for Cases)
352 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
353 // if not set and not 0
354 !CRM_Utils_Array
::value('id', $params)
356 $priority = CRM_Core_PseudoConstant
::priority();
357 $params['priority_id'] = array_search('Normal', $priority);
360 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
361 $params['target_contact_id'] = array_unique($params['target_contact_id']);
363 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
364 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
368 if (CRM_Utils_Array
::value('id', $params)) {
369 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
372 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
375 $activity->copyValues($params);
376 if (isset($params['case_id'])) {
377 // CRM-8708, preserve case ID even though it's not part of the SQL model
378 $activity->case_id
= $params['case_id'];
380 elseif (is_numeric($activity->id
)) {
381 // CRM-8708, preserve case ID even though it's not part of the SQL model
382 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
386 $transaction = new CRM_Core_Transaction();
388 $result = $activity->save();
390 if (is_a($result, 'CRM_Core_Error')) {
391 $transaction->rollback();
395 $activityId = $activity->id
;
397 // check and attach and files as needed
398 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
400 // attempt to save activity assignment
401 $resultAssignment = NULL;
402 if (CRM_Utils_Array
::value('assignee_contact_id', $params)) {
404 $assignmentParams = array('activity_id' => $activityId);
406 if (is_array($params['assignee_contact_id'])) {
407 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
408 // first delete existing assignments if any
409 self
::deleteActivityAssignment($activityId);
413 foreach ($params['assignee_contact_id'] as $acID) {
415 $values[] = "( $activityId, $acID, 'Assignee' )";
418 while (!empty($values)) {
419 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
420 $str = implode(',', $input);
421 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type ) VALUES $str;";
422 CRM_Core_DAO
::executeQuery($sql);
426 $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
428 if (CRM_Utils_Array
::value('id', $params)) {
429 $assignment = new CRM_Activity_BAO_ActivityAssignment();
430 $assignment->activity_id
= $activityId;
431 $assignment->find(TRUE);
433 if ($assignment->assignee_contact_id
!= $params['assignee_contact_id']) {
434 $assignmentParams['id'] = $assignment->id
;
435 $resultAssignment = CRM_Activity_BAO_ActivityAssignment
::create($assignmentParams);
439 $resultAssignment = CRM_Activity_BAO_ActivityAssignment
::create($assignmentParams);
444 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
445 self
::deleteActivityAssignment($activityId);
449 if (is_a($resultAssignment, 'CRM_Core_Error')) {
450 $transaction->rollback();
451 return $resultAssignment;
454 // attempt to save activity targets
455 $resultTarget = NULL;
456 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
458 $targetParams = array('activity_id' => $activityId);
459 $resultTarget = array();
460 if (is_array($params['target_contact_id'])) {
461 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
462 // first delete existing targets if any
463 self
::deleteActivityTarget($activityId);
467 foreach ($params['target_contact_id'] as $tid) {
469 $values[] = "( $activityId, $tid, 'Target' )";
473 while (!empty($values)) {
474 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
475 $str = implode(',', $input);
476 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type ) VALUES $str;";
477 CRM_Core_DAO
::executeQuery($sql);
481 $targetParams['target_contact_id'] = $params['target_contact_id'];
483 if (CRM_Utils_Array
::value('id', $params)) {
484 $target = new CRM_Activity_BAO_ActivityTarget();
485 $target->activity_id
= $activityId;
488 if ($target->target_contact_id
!= $params['target_contact_id']) {
489 $targetParams['id'] = $target->id
;
490 $resultTarget = CRM_Activity_BAO_ActivityTarget
::create($targetParams);
494 $resultTarget = CRM_Activity_BAO_ActivityTarget
::create($targetParams);
499 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
500 self
::deleteActivityTarget($activityId);
504 // write to changelog before transation is committed/rolled
505 // back (and prepare status to display)
506 if (CRM_Utils_Array
::value('id', $params)) {
507 $logMsg = "Activity (id: {$result->id} ) updated with ";
510 $logMsg = "Activity created for ";
514 if (isset($params['source_contact_id'])) {
515 $msgs[] = "source={$params['source_contact_id']}";
518 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
519 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
520 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
521 // take only first target
522 // will be used for recently viewed display
523 $t = array_slice($params['target_contact_id'], 0, 1);
524 $recentContactId = $t[0];
526 elseif (isset($params['target_contact_id'])) {
527 $msgs[] = "target={$params['target_contact_id']}";
528 // will be used for recently viewed display
529 $recentContactId = $params['target_contact_id'];
533 // at worst, take source for recently viewed display
534 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
537 if (isset($params['assignee_contact_id'])) {
538 if (is_array($params['assignee_contact_id'])) {
539 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
542 $msgs[] = "assignee={$params['assignee_contact_id']}";
545 $logMsg .= implode(', ', $msgs);
547 self
::logActivityAction($result, $logMsg);
549 if (CRM_Utils_Array
::value('custom', $params) &&
550 is_array($params['custom'])
552 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
555 $transaction->commit();
556 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
557 $recentOther = array();
558 if (CRM_Utils_Array
::value('case_id', $params)) {
559 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
560 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
561 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
565 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
566 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
567 $url = CRM_Utils_System
::url('civicrm/activity', $q);
568 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
569 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
570 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
574 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
575 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
579 if (CRM_Core_Permission
::check("delete activities")) {
580 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
581 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
586 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
587 if (CRM_Core_Permission
::check('delete activities')) {
588 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
589 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
595 if (!isset($activity->parent_id
)) {
596 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
597 // add the recently created Activity
598 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
599 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
602 if (isset($activitySubject)) {
603 $title = $activitySubject . ' - ';
606 $title = $title . $recentContactDisplay;
607 if (CRM_Utils_Array
::value($activity->activity_type_id
, $activityTypes)) {
608 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
611 CRM_Utils_Recent
::add($title,
616 $recentContactDisplay,
622 // reset the group contact cache since smart groups might be affected due to this
623 CRM_Contact_BAO_GroupContactCache
::remove();
625 if (CRM_Utils_Array
::value('id', $params)) {
626 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
629 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
632 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
634 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
635 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
637 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
639 'activity_id' => $activity->id
,
640 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
642 if ($caseParams['case_id']) {
643 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
646 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
653 public static function logActivityAction($activity, $logMessage = NULL) {
654 $session = CRM_Core_Session
::singleton();
655 $id = $session->get('userID');
657 $id = $activity->source_contact_id
;
660 'entity_table' => 'civicrm_activity',
661 'entity_id' => $activity->id
,
662 'modified_id' => $id,
663 'modified_date' => date('YmdHis'),
664 'data' => $logMessage,
666 CRM_Core_BAO_Log
::add($logParams);
671 * function to get the list Actvities
673 * @param array $input array of parameters
675 * - contact_id int contact_id whose activties we want to retrieve
676 * - offset int which row to start from ?
677 * - rowCount int how many rows to fetch
678 * - sort object|array object or array describing sort order for sql query.
679 * - admin boolean if contact is admin
680 * - caseId int case ID
681 * - context string page on which selector is build
682 * - activity_type_id int|string the activitiy types we want to restrict by
684 * @return array (reference) $values the relevant data object values of open activitie
689 static function &getActivities($input) {
690 //step 1: Get the basic activity data
691 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
696 $config = CRM_Core_Config
::singleton();
698 $randomNum = md5(uniqid());
699 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
701 $tableFields = array(
702 'activity_id' => 'int unsigned',
703 'activity_date_time' => 'datetime',
704 'status_id' => 'int unsigned',
705 'subject' => 'varchar(255)',
706 'source_record_id' => 'int unsigned',
707 'activity_type_id' => 'int unsigned',
708 'activity_type' => 'varchar(128)',
709 'case_id' => 'int unsigned',
710 'case_subject' => 'varchar(255)',
711 'campaign_id' => 'int unsigned',
714 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
715 $insertValueSQL = array();
716 foreach ($tableFields as $name => $desc) {
717 $sql .= "$name $desc,\n";
718 $insertValueSQL[] = $name;
722 PRIMARY KEY ( activity_id )
723 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
726 CRM_Core_DAO
::executeQuery($sql);
728 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
730 $order = $limit = $groupBy = '';
732 if (!empty($input['sort'])) {
733 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
734 $orderBy = $input['sort']->orderBy();
735 if (!empty($orderBy)) {
736 $order = " ORDER BY $orderBy";
739 elseif (trim($input['sort'])) {
740 $order = " ORDER BY {$input['sort']}";
745 $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 ";
748 if (!empty($input['rowCount']) &&
749 $input['rowCount'] > 0
751 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
754 $input['count'] = FALSE;
755 list($sqlClause, $params) = self
::getActivitySQLClause($input);
757 $query = "{$insertSQL}
758 SELECT DISTINCT tbl.* from ( {$sqlClause} )
761 //filter case activities - CRM-5761
762 $components = self
::activityComponents();
763 if (!in_array('CiviCase', $components)) {
765 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
766 WHERE civicrm_case_activity.id IS NULL";
769 $query = $query . $groupBy . $order . $limit;
771 $dao = CRM_Core_DAO
::executeQuery($query, $params);
773 $notbulkActivityClause = '';
774 if ($bulkActivityTypeID) {
775 $notbulkActivityClause = " AND {$activityTempTable}.activity_type_id <> {$bulkActivityTypeID} ";
778 // step 2: Get target and assignee contacts for above activities
779 // create temp table for target contacts
780 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
781 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
782 activity_id int unsigned, contact_id int unsigned, record_type varchar(16), contact_name varchar(255) )
783 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
785 CRM_Core_DAO
::executeQuery($query);
787 // note that we ignore bulk email for targets, since we don't show it in selector
789 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type, contact_name )
790 SELECT ac.activity_id,
794 FROM civicrm_activity_contact ac
795 INNER JOIN {$activityTempTable} ON ( ac.activity_id = {$activityTempTable}.activity_id
796 INNER JOIN civicrm_contact c ON c.id = at.contact_id
797 WHERE c.is_deleted = 0
798 {$notbulkActivityClause} )
800 CRM_Core_DAO
::executeQuery($query);
802 CRM_Core_DAO
::executeQuery($query);
804 // step 3: Combine all temp tables to get final query for activity selector
806 SELECT {$activityTempTable}.*,
807 {$activityContactTempTable}.contact_id,
808 {$activityContactTempTable}.record_type,
809 {$activityContactTempTable}.contact_name,
810 FROM {$activityTempTable}
811 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
815 $dao = CRM_Core_DAO
::executeQuery($query);
817 //CRM-3553, need to check user has access to target groups.
818 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
820 (CRM_Core_Permission
::check('access CiviMail')) ||
821 (CRM_Mailing_Info
::workflowEnabled() &&
822 CRM_Core_Permission
::check('create mailings'))
826 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
829 while ($dao->fetch()) {
830 $activityID = $dao->activity_id
;
831 $values[$activityID]['activity_id'] = $dao->activity_id
;
832 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
833 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
834 $values[$activityID]['activity_type'] = $dao->activity_type
;
835 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
836 $values[$activityID]['status_id'] = $dao->status_id
;
837 $values[$activityID]['subject'] = $dao->subject
;
838 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
840 if ($dao->campaign_id
) {
841 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
844 if (!CRM_Utils_Array
::value('assignee_contact_name', $values[$activityID])) {
845 $values[$activityID]['assignee_contact_name'] = array();
848 if (!CRM_Utils_Array
::value('target_contact_name', $values[$activityID])) {
849 $values[$activityID]['target_contact_name'] = array();
852 if ($dao->record_type
== 'Source' && $dao->contact_id
) {
853 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
854 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
857 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
858 // build array of target / assignee names
859 if ($dao->record_type
== 'Target' && $dao->contact_id
) {
860 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
862 if ($dao->record_type
== 'Assignee' && $dao->contact_id
) {
863 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
866 // case related fields
867 $values[$activityID]['case_id'] = $dao->case_id
;
868 $values[$activityID]['case_subject'] = $dao->case_subject
;
871 $values[$activityID]['recipients'] = ts('(recipients)');
872 $values[$activityID]['mailingId'] = '';
875 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
877 $values[$activityID]['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
878 "mid={$dao->source_record_id}&reset=1&cid={$dao->source_contact_id}&context=activitySelector"
884 // add info on whether the related contacts are deleted (CRM-5673)
885 // FIXME: ideally this should be tied to ACLs
887 // grab all the related contact ids
889 foreach ($values as $value) {
890 $cids[] = $value['source_contact_id'];
892 $cids = array_filter(array_unique($cids));
894 // see which of the cids are of deleted contacts
896 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
897 $dao = CRM_Core_DAO
::executeQuery($sql);
899 while ($dao->fetch()) {
903 // hide the deleted contacts
904 foreach ($values as & $value) {
905 if (in_array($value['source_contact_id'], $dels)) {
906 unset($value['source_contact_id'], $value['source_contact_name']);
915 * Get the component id and name those are enabled and logged in
916 * user has permission. To decide whether we are going to include
917 * component related activities w/ core activity retrieve process.
919 * return an array of component id and name.
922 static function activityComponents() {
923 $components = array();
924 $compInfo = CRM_Core_Component
::getEnabledComponents();
925 foreach ($compInfo as $compObj) {
926 if (CRM_Utils_Array
::value('showActivitiesInCore', $compObj->info
)) {
927 if ($compObj->info
['name'] == 'CiviCampaign') {
928 $componentPermission = "administer {$compObj->name}";
931 $componentPermission = "access {$compObj->name}";
933 if ($compObj->info
['name'] == 'CiviCase') {
934 if (CRM_Case_BAO_Case
::accessCiviCase()) {
935 $components[$compObj->componentID
] = $compObj->info
['name'];
938 elseif (CRM_Core_Permission
::check($componentPermission)) {
939 $components[$compObj->componentID
] = $compObj->info
['name'];
948 * function to get the activity Count
950 * @param array $input array of parameters
952 * - contact_id int contact_id whose activties we want to retrieve
953 * - admin boolean if contact is admin
954 * - caseId int case ID
955 * - context string page on which selector is build
956 * - activity_type_id int|string the activitiy types we want to restrict by
958 * @return int count of activities
963 static function &getActivitiesCount($input) {
964 $input['count'] = TRUE;
965 list($sqlClause, $params) = self
::getActivitySQLClause($input);
967 //filter case activities - CRM-5761
968 $components = self
::activityComponents();
969 if (!in_array('CiviCase', $components)) {
971 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
972 FROM ( {$sqlClause} ) as tbl
973 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
974 WHERE civicrm_case_activity.id IS NULL";
977 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
980 return CRM_Core_DAO
::singleValueQuery($query, $params);
984 * function to get the activity sql clause to pick activities
986 * @param array $input array of parameters
988 * - contact_id int contact_id whose activties we want to retrieve
989 * - admin boolean if contact is admin
990 * - caseId int case ID
991 * - context string page on which selector is build
992 * - count boolean are we interested in the count clause only?
993 * - activity_type_id int|string the activitiy types we want to restrict by
995 * @return int count of activities
1000 static function getActivitySQLClause($input) {
1002 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1004 $config = CRM_Core_Config
::singleton();
1005 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
1006 $sourceWhere = ' ac.contact_id = %1 ';
1007 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1009 $params = array(1 => array($input['contact_id'], 'Integer'));
1012 $commonClauses = array(
1013 "civicrm_option_group.name = 'activity_type'",
1014 "civicrm_activity.is_deleted = 0",
1015 "civicrm_activity.is_current_revision = 1",
1016 "civicrm_activity.is_test = 0",
1019 if ($input['context'] != 'activity') {
1020 $commonClauses[] = "civicrm_activity.status_id = 1";
1023 //Filter on component IDs.
1024 $components = self
::activityComponents();
1025 if (!empty($components)) {
1026 $componentsIn = implode(',', array_keys($components));
1027 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1030 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1033 // activity type ID clause
1034 if (!empty($input['activity_type_id'])) {
1035 if (is_array($input['activity_type_id'])) {
1036 foreach ($input['activity_type_id'] as $idx => $value) {
1037 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1039 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1042 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1043 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1047 // exclude by activity type clause
1048 if (!empty($input['activity_type_exclude_id'])) {
1049 if (is_array($input['activity_type_exclude_id'])) {
1050 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1051 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1053 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1056 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1057 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1061 $commonClause = implode(' AND ', $commonClauses);
1063 $includeCaseActivities = FALSE;
1064 if (in_array('CiviCase', $components)) {
1065 $includeCaseActivities = TRUE;
1069 // build main activity table select clause
1073 if (!$input['count']) {
1075 civicrm_activity.activity_date_time,
1076 civicrm_activity.status_id,
1077 civicrm_activity.subject,
1078 civicrm_activity.source_record_id,
1079 sourceContact.sort_name as source_contact_name,
1080 civicrm_option_value.value as activity_type_id,
1081 civicrm_option_value.label as activity_type,
1082 null as case_id, null as case_subject,
1083 civicrm_activity.campaign_id as campaign_id,
1084 activityContact.contact_id as contact_id,
1085 activityContact.record_type as record_type,
1086 contact.sort_name as sort_name
1090 INNER JOIN civicrm_activity_contact activityContact ON activityContact.activity_id = civicrm_activity.id
1091 INNER JOIN civicrm_contact contact ON activityContact.contact_id = contact.id
1096 SELECT civicrm_activity.id as activity_id
1098 from civicrm_activity
1099 left join civicrm_option_value on
1100 civicrm_activity.activity_type_id = civicrm_option_value.value
1101 left join civicrm_option_group on
1102 civicrm_option_group.id = civicrm_option_value.option_group_id
1109 // Build case clause
1110 // or else exclude Inbound Emails that have been filed on a case.
1113 if ($includeCaseActivities) {
1115 if (!$input['count']) {
1117 civicrm_activity.activity_date_time,
1118 civicrm_activity.status_id,
1119 civicrm_activity.subject,
1120 civicrm_activity.source_contact_id,
1121 civicrm_activity.source_record_id,
1122 sourceContact.sort_name as source_contact_name,
1123 civicrm_option_value.value as activity_type_id,
1124 civicrm_option_value.label as activity_type,
1125 null as case_id, null as case_subject,
1126 civicrm_activity.campaign_id as campaign_id';
1132 SELECT civicrm_activity.id as activity_id
1134 from civicrm_activity
1135 inner join civicrm_case_activity on
1136 civicrm_case_activity.activity_id = civicrm_activity.id
1137 inner join civicrm_case on
1138 civicrm_case_activity.case_id = civicrm_case.id
1139 inner join civicrm_case_contact on
1140 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1141 left join civicrm_option_value on
1142 civicrm_activity.activity_type_id = civicrm_option_value.value
1143 left join civicrm_option_group on
1144 civicrm_option_group.id = civicrm_option_value.option_group_id
1149 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1150 ( civicrm_option_value.name <> 'Inbound Email' AND
1151 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1157 $returnClause = " {$sourceClause} union all {$caseClause} ";
1159 return array($returnClause, $params);
1163 * send the message to all the contacts and also insert a
1164 * contact activity in each contacts record
1166 * @param array $contactDetails the array of contact details to send the email
1167 * @param string $subject the subject of the message
1168 * @param string $message the message contents
1169 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1170 * @param int $userID use this userID if set
1171 * @param string $from
1172 * @param array $attachments the array of attachments if any
1173 * @param string $cc cc recepient
1174 * @param string $bcc bcc recepient
1175 * @param array $contactIds contact ids
1177 * @return array ( sent, activityId) if any email is sent and activityId
1181 static function sendEmail(
1189 $attachments = NULL,
1192 $contactIds // FIXME a param with no default shouldn't be last
1194 // get the contact details of logged in contact, which we set as from email
1195 if ($userID == NULL) {
1196 $session = CRM_Core_Session
::singleton();
1197 $userID = $session->get('userID');
1200 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1202 return array(count($contactDetails), 0, count($contactDetails));
1204 if (!trim($fromDisplayName)) {
1205 $fromDisplayName = $fromEmail;
1209 // token replacement of addressee/email/postal greetings
1210 // get the tokens added in subject and message
1211 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1212 $messageToken = CRM_Utils_Token
::getTokens($text);
1213 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1216 $from = "$fromDisplayName <$fromEmail>";
1219 //create the meta level record first ( email activity )
1220 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1225 // CRM-6265: save both text and HTML parts in details (if present)
1226 if ($html and $text) {
1227 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1230 $details = $html ?
$html : $text;
1233 $activityParams = array(
1234 'source_contact_id' => $userID,
1235 'activity_type_id' => $activityTypeID,
1236 'activity_date_time' => date('YmdHis'),
1237 'subject' => $subject,
1238 'details' => $details,
1239 // FIXME: check for name Completed and get ID from that lookup
1243 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1244 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1246 // add the attachments to activity params here
1248 // first process them
1249 $activityParams = array_merge($activityParams,
1254 $activity = self
::create($activityParams);
1256 // get the set of attachments from where they are stored
1257 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1260 $returnProperties = array();
1261 if (isset($messageToken['contact'])) {
1262 foreach ($messageToken['contact'] as $key => $value) {
1263 $returnProperties[$value] = 1;
1267 if (isset($subjectToken['contact'])) {
1268 foreach ($subjectToken['contact'] as $key => $value) {
1269 if (!isset($returnProperties[$value])) {
1270 $returnProperties[$value] = 1;
1276 // get token details for contacts, call only if tokens are used
1278 if (!empty($returnProperties)) {
1279 list($details) = CRM_Utils_Token
::getTokenDetails(
1284 'CRM_Activity_BAO_Activity'
1290 CRM_Utils_Hook
::tokens($tokens);
1291 $categories = array_keys($tokens);
1293 $escapeSmarty = FALSE;
1294 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1295 $smarty = CRM_Core_Smarty
::singleton();
1296 $escapeSmarty = TRUE;
1299 $sent = $notSent = array();
1300 foreach ($contactDetails as $values) {
1301 $contactId = $values['contact_id'];
1302 $emailAddress = $values['email'];
1304 if (!empty($details) && is_array($details["{$contactId}"])) {
1305 // unset email from details since it always returns primary email address
1306 unset($details["{$contactId}"]['email']);
1307 unset($details["{$contactId}"]['email_id']);
1308 $values = array_merge($values, $details["{$contactId}"]);
1311 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1312 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1315 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1316 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1317 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1323 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1324 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1325 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1331 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1332 // also add the contact tokens to the template
1333 $smarty->assign_by_ref('contact', $values);
1335 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1336 $tokenText = $smarty->fetch("string:$tokenText");
1337 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1341 if (self
::sendMessage(
1358 return array($sent, $activity->id
);
1361 static function sendSMS(&$contactDetails,
1363 &$smsParams = array(),
1367 if ($userID == NULL) {
1368 $session = CRM_Core_Session
::singleton();
1369 $userID = $session->get('userID');
1372 $text = &$activityParams['text_message'];
1373 $html = &$activityParams['html_message'];
1376 // token replacement of addressee/email/postal greetings
1377 // get the tokens added in subject and message
1378 $messageToken = CRM_Utils_Token
::getTokens($text);
1379 $messageToken = array_merge($messageToken,
1380 CRM_Utils_Token
::getTokens($html)
1383 //create the meta level record first ( sms activity )
1384 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1389 // CRM-6265: save both text and HTML parts in details (if present)
1390 if ($html and $text) {
1391 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1394 $details = $html ?
$html : $text;
1397 $activitySubject = $activityParams['activity_subject'];
1398 $activityParams = array(
1399 'source_contact_id' => $userID,
1400 'activity_type_id' => $activityTypeID,
1401 'activity_date_time' => date('YmdHis'),
1402 'subject' => $activitySubject,
1403 'details' => $details,
1404 // FIXME: check for name Completed and get ID from that lookup
1408 $activity = self
::create($activityParams);
1409 $activityID = $activity->id
;
1411 $returnProperties = array();
1413 if (isset($messageToken['contact'])) {
1414 foreach ($messageToken['contact'] as $key => $value) {
1415 $returnProperties[$value] = 1;
1421 CRM_Utils_Hook
::tokens($tokens);
1422 $categories = array_keys($tokens);
1424 // get token details for contacts, call only if tokens are used
1426 if (!empty($returnProperties) ||
!empty($tokens)) {
1427 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1431 'CRM_Activity_BAO_Activity'
1435 $escapeSmarty = $sent = FALSE;
1436 foreach ($contactDetails as $values) {
1437 $contactId = $values['contact_id'];
1439 if (!empty($details) && is_array($details["{$contactId}"])) {
1440 // unset email from details since it always returns primary email address
1441 unset($details["{$contactId}"]['email']);
1442 unset($details["{$contactId}"]['email_id']);
1443 $values = array_merge($values, $details["{$contactId}"]);
1446 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1447 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1449 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1450 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1452 // Only send if the phone is of type mobile
1453 if($values['phone_type_id'] == 2) {
1454 $smsParams['To'] = $values['phone'];
1456 $smsParams['To'] = '';
1459 if (self
::sendSMSMessage($contactId,
1465 // even a single successful delivery should set this falg to true
1470 return array($sent, $activity->id
);
1474 * send the sms message to a specific contact
1476 * @param int $toID the contact id of the recipient
1477 * @param int $activityID the activity ID that tracks the message
1478 * @param array $smsParams the params used for sending sms
1480 * @return boolean true if successfull else false.
1484 static function sendSMSMessage($toID,
1487 $smsParams = array(),
1491 $toPhoneNumber = "";
1493 if ($smsParams['To']) {
1494 $toPhoneNumber = trim($smsParams['To']);
1497 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1498 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1499 //to get primary mobile ph,if not get a first mobile ph
1500 if (!empty($toPhoneNumbers)) {
1501 $toPhoneNumerDetails = reset($toPhoneNumbers);
1502 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1503 //contact allows to send sms
1508 // make sure both phone are valid
1509 // and that the recipient wants to receive sms
1510 if (empty($toPhoneNumber) or $toDoNotSms) {
1514 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1515 $recipient = $smsParams['To'];
1516 $smsParams['contact_id'] = $toID;
1517 $smsParams['parent_activity_id'] = $activityID;
1519 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1520 if (!$providerObj->send($recipient, $smsParams, $message, NULL)) {
1524 // add activity target record for every sms that is send
1525 $activityTargetParams = array(
1526 'activity_id' => $activityID,
1527 'target_contact_id' => $toID,
1529 self
::createActivityTarget($activityTargetParams);
1535 * send the message to a specific contact
1537 * @param string $from the name and email of the sender
1538 * @param int $toID the contact id of the recipient
1539 * @param string $subject the subject of the message
1540 * @param string $message the message contents
1541 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1542 * @param int $activityID the activity ID that tracks the message
1544 * @return boolean true if successfull else false.
1548 static function sendMessage($from,
1556 $attachments = NULL,
1560 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1561 if ($emailAddress) {
1562 $toEmail = trim($emailAddress);
1565 // make sure both email addresses are valid
1566 // and that the recipient wants to receive email
1567 if (empty($toEmail) or $toDoNotEmail) {
1570 if (!trim($toDisplayName)) {
1571 $toDisplayName = $toEmail;
1574 // create the params array
1575 $mailParams = array(
1576 'groupName' => 'Activity Email Sender',
1578 'toName' => $toDisplayName,
1579 'toEmail' => $toEmail,
1580 'subject' => $subject,
1583 'text' => $text_message,
1584 'html' => $html_message,
1585 'attachments' => $attachments,
1588 if (!CRM_Utils_Mail
::send($mailParams)) {
1592 // add activity target record for every mail that is send
1593 $activityTargetParams = array(
1594 'activity_id' => $activityID,
1595 'target_contact_id' => $toID,
1597 self
::createActivityTarget($activityTargetParams);
1602 * combine all the importable fields from the lower levels object
1604 * The ordering is important, since currently we do not have a weight
1605 * scheme. Adding weight is super important and should be done in the
1606 * next week or so, before this can be called complete.
1610 * @return array array of importable Fields
1614 static function &importableFields($status = FALSE) {
1615 if (!self
::$_importableFields) {
1616 if (!self
::$_importableFields) {
1617 self
::$_importableFields = array();
1620 $fields = array('' => array('title' => ts('- do not import -')));
1623 $fields = array('' => array('title' => ts('- Activity Fields -')));
1626 $tmpFields = CRM_Activity_DAO_Activity
::import();
1627 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1629 // Using new Dedupe rule.
1630 $ruleParams = array(
1631 'contact_type' => 'Individual',
1632 'used' => 'Unsupervised',
1634 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1636 $tmpConatctField = array();
1637 if (is_array($fieldsArray)) {
1638 foreach ($fieldsArray as $value) {
1639 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1644 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1645 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1646 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1649 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1650 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1651 $fields = array_merge($fields, $tmpConatctField);
1652 $fields = array_merge($fields, $tmpFields);
1653 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1654 self
::$_importableFields = $fields;
1656 return self
::$_importableFields;
1660 * To get the Activities of a target contact
1662 * @param $contactId Integer ContactId of the contact whose activities
1665 * @return array array of activity fields
1668 static function getContactActivity($contactId) {
1669 $activities = array();
1671 // First look for activities where contactId is one of the targets
1674 FROM civicrm_activity_contact
1675 WHERE contact_id = $contactId
1677 $dao = CRM_Core_DAO
::executeQuery($query);
1678 while ($dao->fetch()) {
1679 if ($dao->record_type
== 'Target') {
1680 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1682 else if ($dao->record_type
== 'Assignee') {
1683 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1686 // do source stuff here
1687 $activities[$dao->activity_id
]['source_contact_id'][] = $contactId;
1691 $activityIds = array_keys($activities);
1692 if (count($activityIds) < 1) {
1696 $activityIds = implode(',', $activityIds);
1698 SELECT activity.id as activity_id,
1700 subject, location, activity_date_time, details, status_id
1701 FROM civicrm_activity activity
1702 WHERE activity.id IN ($activityIds)";
1704 $dao = CRM_Core_DAO
::executeQuery($query);
1706 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1707 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1709 while ($dao->fetch()) {
1710 $activities[$dao->activity_id
]['source_contact_id'] = $dao->source_contact_id
;
1711 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1712 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1713 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1714 $activities[$dao->activity_id
]['location'] = $dao->location
;
1715 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1716 $activities[$dao->activity_id
]['details'] = $dao->details
;
1717 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1718 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1719 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1725 * Function to add activity for Membership/Event/Contribution
1727 * @param object $activity (reference) perticular component object
1728 * @param string $activityType for Membership Signup or Renewal
1734 static function addActivity(&$activity,
1735 $activityType = 'Membership Signup',
1736 $targetContactID = NULL
1738 if ($activity->__table
== 'civicrm_membership') {
1739 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1741 if (!$membershipType) {
1742 $membershipType = ts('Membership');
1745 $subject = "{$membershipType}";
1747 if (!empty($activity->source
) && $activity->source
!= 'null') {
1748 $subject .= " - {$activity->source}";
1751 if ($activity->owner_membership_id
) {
1754 FROM civicrm_contact, civicrm_membership
1755 WHERE civicrm_contact.id = civicrm_membership.contact_id
1756 AND civicrm_membership.id = $activity->owner_membership_id
1758 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1759 $subject .= " (by {$displayName})";
1762 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1763 // CRM-72097 changed from start date to today
1764 $date = date('YmdHis');
1765 $component = 'Membership';
1767 elseif ($activity->__table
== 'civicrm_participant') {
1768 $event = CRM_Event_BAO_Event
::getEvents(TRUE, $activity->event_id
, TRUE, FALSE);
1770 $roles = CRM_Event_PseudoConstant
::participantRole();
1771 $status = CRM_Event_PseudoConstant
::participantStatus();
1773 $subject = $event[$activity->event_id
];
1774 if (CRM_Utils_Array
::value($activity->role_id
, $roles)) {
1775 $subject .= ' - ' . $roles[$activity->role_id
];
1777 if (CRM_Utils_Array
::value($activity->status_id
, $status)) {
1778 $subject .= ' - ' . $status[$activity->status_id
];
1780 $date = date('YmdHis');
1781 if ($activityType != 'Email') {
1782 $activityType = 'Event Registration';
1784 $component = 'Event';
1786 elseif ($activity->__table
== 'civicrm_contribution') {
1787 //create activity record only for Completed Contributions
1788 if ($activity->contribution_status_id
!= 1) {
1794 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1795 if (!empty($activity->source
) && $activity->source
!= 'null') {
1796 $subject .= " - {$activity->source}";
1798 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1799 $activityType = $component = 'Contribution';
1801 $activityParams = array(
1802 'source_contact_id' => $activity->contact_id
,
1803 'source_record_id' => $activity->id
,
1804 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1808 'subject' => $subject,
1809 'activity_date_time' => $date,
1810 'is_test' => $activity->is_test
,
1811 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1815 'skipRecentView' => TRUE,
1816 'campaign_id' => $activity->campaign_id
,
1819 // create activity with target contacts
1820 $session = CRM_Core_Session
::singleton();
1821 $id = $session->get('userID');
1823 $activityParams['source_contact_id'] = $id;
1824 $activityParams['target_contact_id'][] = $activity->contact_id
;
1828 if ($targetContactID) {
1829 $activityParams['target_contact_id'][] = $targetContactID;
1831 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1832 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1838 * Function to get Parent activity for currently viewd activity
1840 * @param int $activityId current activity id
1842 * @return int $parentId Id of parent acyivity otherwise false.
1845 static function getParentActivity($activityId) {
1846 static $parentActivities = array();
1848 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1850 if (!array_key_exists($activityId, $parentActivities)) {
1851 $parentActivities[$activityId] = array();
1853 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1858 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1861 return $parentActivities[$activityId];
1865 * Function to get total count of prior revision of currently viewd activity
1867 * @param int $activityId current activity id
1869 * @return int $params count of prior acyivities otherwise false.
1872 static function getPriorCount($activityID) {
1873 static $priorCounts = array();
1875 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1877 if (!array_key_exists($activityID, $priorCounts)) {
1878 $priorCounts[$activityID] = array();
1879 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1886 SELECT count( id ) AS cnt
1887 FROM civicrm_activity
1888 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1889 AND is_current_revision = 0
1890 AND id < {$activityID}
1892 $params = array(1 => array($originalID, 'Integer'));
1893 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1895 $priorCounts[$activityID] = $count ?
$count : 0;
1898 return $priorCounts[$activityID];
1902 * Function to get all prior activities of currently viewd activity
1904 * @param int $activityId current activity id
1906 * @return array $result prior acyivities info.
1909 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1910 static $priorActivities = array();
1912 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1913 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1915 if (!array_key_exists($index, $priorActivities)) {
1916 $priorActivities[$index] = array();
1918 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1924 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1925 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1926 WHERE (ca.id = %1 OR ca.original_id = %1)
1927 AND cl.entity_table = 'civicrm_activity'
1928 AND cl.entity_id = ca.id
1929 AND cl.modified_id = c.id
1931 if ($onlyPriorRevisions) {
1932 $query .= " AND ca.id < {$activityID}";
1934 $query .= " ORDER BY ca.id DESC";
1936 $params = array(1 => array($originalID, 'Integer'));
1937 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1939 while ($dao->fetch()) {
1940 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1941 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1942 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1943 $priorActivities[$index][$dao->activityID
]['link'] = 'javascript:viewActivity( $dao->activityID );';
1948 return $priorActivities[$index];
1952 * Function to find the latest revision of a given activity
1954 * @param int $activityId prior activity id
1956 * @return int $params current activity id.
1959 static function getLatestActivityId($activityID) {
1960 static $latestActivityIds = array();
1962 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1964 if (!array_key_exists($activityID, $latestActivityIds)) {
1965 $latestActivityIds[$activityID] = array();
1967 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1972 $activityID = $originalID;
1974 $params = array(1 => array($activityID, 'Integer'));
1975 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1977 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
1980 return $latestActivityIds[$activityID];
1984 * Function to create a follow up a given activity
1986 * @activityId int activity id of parent activity
1988 * @param array $activity details
1992 static function createFollowupActivity($activityId, $params) {
1997 $session = CRM_Core_Session
::singleton();
1999 $followupParams = array();
2000 $followupParams['parent_id'] = $activityId;
2001 $followupParams['source_contact_id'] = $session->get('userID');
2002 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2004 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2005 // Get Subject of Follow-up Activiity, CRM-4491
2006 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2008 //create target contact for followup
2009 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2010 $followupParams['target_contact_id'] = $params['target_contact_id'];
2013 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2014 $params['followup_date_time']
2016 $followupActivity = self
::create($followupParams);
2018 return $followupActivity;
2022 * Function to get Activity specific File according activity type Id.
2024 * @param int $activityTypeId activity id
2026 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2030 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2031 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2033 if ($activityTypes[$activityTypeId]['name']) {
2034 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2040 global $civicrm_root;
2041 $config = CRM_Core_Config
::singleton();
2042 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2043 if (empty($config->customPHPPathDir
)) {
2046 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2051 return $activityTypeFile;
2055 * Function to restore the activity
2057 * @param array $params associated array
2063 public static function restoreActivity(&$params) {
2064 $activity = new CRM_Activity_DAO_Activity();
2065 $activity->copyValues($params);
2067 $activity->is_deleted
= 0;
2068 $result = $activity->save();
2074 * Get the exportable fields for Activities
2076 * @param string $name if it is called by case $name = Case else $name = Activity
2078 * @return array array of exportable Fields
2082 static function &exportableFields($name = 'Activity') {
2083 if (!isset(self
::$_exportableFields[$name])) {
2084 self
::$_exportableFields[$name] = array();
2086 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2087 // my case hence we have defined fields as case_*
2088 if ($name == 'Activity') {
2089 $exportableFields = CRM_Activity_DAO_Activity
::export();
2090 if (isset($exportableFields['activity_campaign_id'])) {
2091 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2093 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2094 $exportableFields['source_contact'] = array(
2095 'title' => ts('Source Contact'),
2096 'type' => CRM_Utils_Type
::T_STRING
,
2100 $Activityfields = array(
2101 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2102 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2104 $fields = array_merge($Activityfields, $exportableFields);
2107 //set title to activity fields
2109 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2110 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2111 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2112 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2113 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2114 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2115 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2116 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2117 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2118 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2121 // add custom data for cases
2122 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2125 // add custom data for case activities
2126 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2128 self
::$_exportableFields[$name] = $fields;
2130 return self
::$_exportableFields[$name];
2134 * Get the allowed profile fields for Activities
2136 * @return array array of activity profile Fields
2139 static function getProfileFields() {
2140 $exportableFields = self
::exportableFields('Activity');
2141 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2142 $config = CRM_Core_Config
::singleton();
2143 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2144 $skipFields[] = 'activity_engagement_level';
2147 foreach ($skipFields as $field) {
2148 if (isset($exportableFields[$field])) {
2149 unset($exportableFields[$field]);
2153 // hack to use 'activity_type_id' instead of 'activity_type'
2154 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2155 unset($exportableFields['activity_status']);
2157 return $exportableFields;
2161 * This function delete activity record related to contact record,
2162 * when there are no target and assignee record w/ other contact.
2164 * @param int $contactId contactId
2169 public static function cleanupActivity($contactId) {
2175 $transaction = new CRM_Core_Transaction();
2177 // delete activity if there are no record in
2178 // civicrm_activity_assignment or civicrm_activity_target
2179 // pointing to any other contact record.
2182 $activity = new CRM_Activity_DAO_Activity();
2183 $activity->source_contact_id
= $contactId;
2186 while ($activity->fetch()) {
2187 $noTarget = $noAssignee = TRUE;
2189 // check for target activity record.
2190 $target = new CRM_Activity_DAO_ActivityTarget();
2191 $target->activity_id
= $activity->id
;
2193 while ($target->fetch()) {
2194 if ($target->target_contact_id
!= $contactId) {
2201 // check for assignee activity record.
2202 $assignee = new CRM_Activity_DAO_ActivityAssignment();
2203 $assignee->activity_id
= $activity->id
;
2205 while ($assignee->fetch()) {
2206 if ($assignee->assignee_contact_id
!= $contactId) {
2207 $noAssignee = FALSE;
2213 // finally delete activity.
2214 if ($noTarget && $noAssignee) {
2215 $activityParams = array('id' => $activity->id
);
2216 $result = self
::deleteActivity($activityParams);
2221 $transaction->commit();
2227 * Does user has sufficient permission for view/edit activity record.
2229 * @param int $activityId activity record id.
2230 * @param int $action edit/view
2232 * @return boolean $allow true/false
2235 public static function checkPermission($activityId, $action) {
2238 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2243 $activity = new CRM_Activity_DAO_Activity();
2244 $activity->id
= $activityId;
2245 if (!$activity->find(TRUE)) {
2249 //component related permissions.
2250 $compPermissions = array(
2251 'CiviCase' => array('administer CiviCase',
2252 'access my cases and activities',
2253 'access all cases and activities',
2255 'CiviMail' => array('access CiviMail'),
2256 'CiviEvent' => array('access CiviEvent'),
2257 'CiviGrant' => array('access CiviGrant'),
2258 'CiviPledge' => array('access CiviPledge'),
2259 'CiviMember' => array('access CiviMember'),
2260 'CiviReport' => array('access CiviReport'),
2261 'CiviContribute' => array('access CiviContribute'),
2262 'CiviCampaign' => array('administer CiviCampaign'),
2265 //return early when it is case activity.
2266 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2267 //check for civicase related permission.
2268 if ($isCaseActivity) {
2270 foreach ($compPermissions['CiviCase'] as $per) {
2271 if (CRM_Core_Permission
::check($per)) {
2277 //check for case specific permissions.
2280 if ($action == CRM_Core_Action
::UPDATE
) {
2283 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2285 $activity->activity_type_id
2293 //first check the component permission.
2296 FROM civicrm_option_value val
2297 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2298 WHERE val.value = %2";
2299 $params = array(1 => array('activity_type', 'String'),
2300 2 => array($activity->activity_type_id
, 'Integer'),
2302 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2305 $componentName = CRM_Core_Component
::getComponentName($componentId);
2306 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2308 //here we are interesting in any single permission.
2309 if (is_array($compPermission)) {
2310 foreach ($compPermission as $per) {
2311 if (CRM_Core_Permission
::check($per)) {
2319 //check for this permission related to contact.
2320 $permission = CRM_Core_Permission
::VIEW
;
2321 if ($action == CRM_Core_Action
::UPDATE
) {
2322 $permission = CRM_Core_Permission
::EDIT
;
2325 //check for source contact.
2326 if (!$componentId ||
$allow) {
2327 $allow = CRM_Contact_BAO_Contact_Permission
::allow($activity->source_contact_id
, $permission);
2330 //check for target and assignee contacts.
2332 //first check for supper permission.
2333 $supPermission = 'view all contacts';
2334 if ($action == CRM_Core_Action
::UPDATE
) {
2335 $supPermission = 'edit all contacts';
2337 $allow = CRM_Core_Permission
::check($supPermission);
2339 //user might have sufficient permission, through acls.
2342 //get the target contacts.
2343 $targetContacts = CRM_Activity_BAO_ActivityTarget
::retrieveTargetIdsByActivityId($activity->id
);
2344 foreach ($targetContacts as $cnt => $contactId) {
2345 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2351 //get the assignee contacts.
2353 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment
::retrieveAssigneeIdsByActivityId($activity->id
);
2354 foreach ($assigneeContacts as $cnt => $contactId) {
2355 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2368 * This function is a wrapper for ajax activity selector
2370 * @param array $params associated array for params record id.
2372 * @return array $contactActivities associated array of contact activities
2375 public static function getContactActivitySelector(&$params) {
2376 // format the params
2377 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2378 $params['rowCount'] = $params['rp'];
2379 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2380 $params['caseId'] = NULL;
2381 $context = CRM_Utils_Array
::value('context', $params);
2383 // get contact activities
2384 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2387 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2389 // format params and add links
2390 $contactActivities = array();
2392 if (!empty($activities)) {
2393 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2395 // check logged in user for permission
2396 $page = new CRM_Core_Page();
2397 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2398 $permissions = array($page->_permission
);
2399 if (CRM_Core_Permission
::check('delete activities')) {
2400 $permissions[] = CRM_Core_Permission
::DELETE
;
2403 $mask = CRM_Core_Action
::mask($permissions);
2405 foreach ($activities as $activityId => $values) {
2406 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2407 $contactActivities[$activityId]['subject'] = $values['subject'];
2408 if ($params['contact_id'] == $values['source_contact_id']) {
2409 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2411 elseif ($values['source_contact_id']) {
2412 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2415 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2418 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2419 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System
::href($values['recipients'], 'civicrm/mailing/report', "mid={$values['source_record_id']}&reset=1&cid={$values['source_contact_id']}&context=activitySelector");
2421 elseif (CRM_Utils_Array
::value('recipients', $values)) {
2422 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2424 elseif (!$values['target_contact_name']) {
2425 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2427 elseif (!empty($values['target_contact_name'])) {
2429 $contactActivities[$activityId]['target_contact'] = '';
2430 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2431 if ($tcID && $count < 5) {
2432 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2435 $contactActivities[$activityId]['target_contact'] .= "; ";
2439 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2446 if (empty($values['assignee_contact_name'])) {
2447 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2449 elseif (!empty($values['assignee_contact_name'])) {
2451 $contactActivities[$activityId]['assignee_contact'] = '';
2452 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2453 if ($acID && $count < 5) {
2454 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2457 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2461 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2467 if ( $values['activity_type'] == 'Bulk Email'){
2468 $contactActivities[$activityId]['openstats'] = "Opens: ".
2469 count(CRM_Mailing_Event_BAO_Opened
::getRows(
2470 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2473 count(CRM_Mailing_Event_BAO_TrackableURLOpen
::getRows(
2474 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2477 $contactActivities[$activityId]['openstats'] = '';
2480 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2481 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2483 // add class to this row if overdue
2484 $contactActivities[$activityId]['class'] = '';
2485 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2486 && CRM_Utils_Array
::value('status_id', $values) == 1
2488 $contactActivities[$activityId]['class'] = 'status-overdue';
2491 $contactActivities[$activityId]['class'] = 'status-ontime';
2495 $contactActivities[$activityId]['links'] = '';
2496 $accessMailingReport = FALSE;
2497 if (CRM_Utils_Array
::value('mailingId', $values)) {
2498 $accessMailingReport = TRUE;
2501 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2502 CRM_Utils_Array
::value('activity_type_id', $values),
2503 CRM_Utils_Array
::value('source_record_id', $values),
2504 $accessMailingReport,
2505 CRM_Utils_Array
::value('activity_id', $values)
2508 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2510 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2513 'id' => $values['activity_id'],
2514 'cid' => $params['contact_id'],
2516 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2522 return $contactActivities;
2526 * Used to copy custom fields and attachments from an existing activity to another.
2527 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2529 static function copyExtendedActivityData($params) {
2530 // attach custom data to the new activity
2531 $customParams = $htmlType = array();
2532 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2534 if (!empty($customValues)) {
2535 $fieldIds = implode(', ', array_keys($customValues));
2536 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2537 $result = CRM_Core_DAO
::executeQuery($sql);
2539 while ($result->fetch()) {
2540 $htmlType[] = $result->id
;
2543 foreach ($customValues as $key => $value) {
2544 if ($value !== NULL) { // CRM-10542
2545 if (in_array($key, $htmlType)) {
2546 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2547 $customParams["custom_{$key}_-1"] = array(
2548 'name' => $fileValues[0],
2549 'path' => $fileValues[1],
2553 $customParams["custom_{$key}_-1"] = $value;
2557 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2558 $params['mainActivityId'], 'Activity'
2562 // copy activity attachments ( if any )
2563 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);