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 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('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 $activity->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_PseudoConstant
::activityContacts('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
::priority();
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_PseudoConstant
::activityContacts('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_ActivityAssignment();
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 transation 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_PseudoConstant
::activityContacts('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 Actvities
647 * @param array $input array of parameters
649 * - contact_id int contact_id whose activties 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 activitie
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 'status_id' => 'int unsigned',
680 'subject' => 'varchar(255)',
681 'source_record_id' => 'int unsigned',
682 'activity_type_id' => 'int unsigned',
683 'activity_type' => 'varchar(128)',
684 'case_id' => 'int unsigned',
685 'case_subject' => 'varchar(255)',
686 'campaign_id' => 'int unsigned',
689 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
690 $insertValueSQL = array();
691 foreach ($tableFields as $name => $desc) {
692 $sql .= "$name $desc,\n";
693 $insertValueSQL[] = $name;
697 PRIMARY KEY ( activity_id )
698 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
701 CRM_Core_DAO
::executeQuery($sql);
703 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
705 $order = $limit = $groupBy = '';
707 if (!empty($input['sort'])) {
708 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
709 $orderBy = $input['sort']->orderBy();
710 if (!empty($orderBy)) {
711 $order = " ORDER BY $orderBy";
714 elseif (trim($input['sort'])) {
715 $order = " ORDER BY {$input['sort']}";
720 $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 ";
723 if (!empty($input['rowCount']) &&
724 $input['rowCount'] > 0
726 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
729 $input['count'] = FALSE;
730 list($sqlClause, $params) = self
::getActivitySQLClause($input);
732 $query = "{$insertSQL}
733 SELECT DISTINCT tbl.* from ( {$sqlClause} )
736 //filter case activities - CRM-5761
737 $components = self
::activityComponents();
738 if (!in_array('CiviCase', $components)) {
740 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
741 WHERE civicrm_case_activity.id IS NULL";
744 $query = $query . $groupBy . $order . $limit;
746 $dao = CRM_Core_DAO
::executeQuery($query, $params);
748 $notbulkActivityClause = '';
749 if ($bulkActivityTypeID) {
750 $notbulkActivityClause = " AND {$activityTempTable}.activity_type_id <> {$bulkActivityTypeID} ";
753 // step 2: Get target and assignee contacts for above activities
754 // create temp table for target contacts
755 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
756 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
757 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16), contact_name varchar(255) )
758 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
760 CRM_Core_DAO
::executeQuery($query);
762 // note that we ignore bulk email for targets, since we don't show it in selector
764 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name )
765 SELECT ac.activity_id,
769 FROM civicrm_activity_contact ac
770 INNER JOIN {$activityTempTable} ON ( ac.activity_id = {$activityTempTable}.activity_id {$notbulkActivityClause} )
771 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
772 WHERE c.is_deleted = 0
775 CRM_Core_DAO
::executeQuery($query);
777 // step 3: Combine all temp tables to get final query for activity selector
779 SELECT {$activityTempTable}.*,
780 {$activityContactTempTable}.contact_id,
781 {$activityContactTempTable}.record_type_id,
782 {$activityContactTempTable}.contact_name
783 FROM {$activityTempTable}
784 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
788 $dao = CRM_Core_DAO
::executeQuery($query);
790 //CRM-3553, need to check user has access to target groups.
791 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
793 (CRM_Core_Permission
::check('access CiviMail')) ||
794 (CRM_Mailing_Info
::workflowEnabled() &&
795 CRM_Core_Permission
::check('create mailings'))
799 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
802 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
803 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
804 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
805 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
808 while ($dao->fetch()) {
809 $activityID = $dao->activity_id
;
810 $values[$activityID]['activity_id'] = $dao->activity_id
;
811 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
812 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
813 $values[$activityID]['activity_type'] = $dao->activity_type
;
814 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
815 $values[$activityID]['status_id'] = $dao->status_id
;
816 $values[$activityID]['subject'] = $dao->subject
;
817 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
819 if ($dao->campaign_id
) {
820 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
823 if (!CRM_Utils_Array
::value('assignee_contact_name', $values[$activityID])) {
824 $values[$activityID]['assignee_contact_name'] = array();
827 if (!CRM_Utils_Array
::value('target_contact_name', $values[$activityID])) {
828 $values[$activityID]['target_contact_name'] = array();
831 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
832 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
833 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
836 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
837 // build array of target / assignee names
838 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
839 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
841 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
842 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
845 // case related fields
846 $values[$activityID]['case_id'] = $dao->case_id
;
847 $values[$activityID]['case_subject'] = $dao->case_subject
;
850 $values[$activityID]['recipients'] = ts('(recipients)');
851 $values[$activityID]['mailingId'] = '';
854 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
856 $values[$activityID]['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
857 "mid={$dao->source_record_id}&reset=1&cid={$dao->source_contact_id}&context=activitySelector"
863 // add info on whether the related contacts are deleted (CRM-5673)
864 // FIXME: ideally this should be tied to ACLs
866 // grab all the related contact ids
868 foreach ($values as $value) {
869 $cids[] = $value['source_contact_id'];
871 $cids = array_filter(array_unique($cids));
873 // see which of the cids are of deleted contacts
875 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
876 $dao = CRM_Core_DAO
::executeQuery($sql);
878 while ($dao->fetch()) {
882 // hide the deleted contacts
883 foreach ($values as & $value) {
884 if (in_array($value['source_contact_id'], $dels)) {
885 unset($value['source_contact_id'], $value['source_contact_name']);
894 * Get the component id and name those are enabled and logged in
895 * user has permission. To decide whether we are going to include
896 * component related activities w/ core activity retrieve process.
898 * return an array of component id and name.
901 static function activityComponents() {
902 $components = array();
903 $compInfo = CRM_Core_Component
::getEnabledComponents();
904 foreach ($compInfo as $compObj) {
905 if (CRM_Utils_Array
::value('showActivitiesInCore', $compObj->info
)) {
906 if ($compObj->info
['name'] == 'CiviCampaign') {
907 $componentPermission = "administer {$compObj->name}";
910 $componentPermission = "access {$compObj->name}";
912 if ($compObj->info
['name'] == 'CiviCase') {
913 if (CRM_Case_BAO_Case
::accessCiviCase()) {
914 $components[$compObj->componentID
] = $compObj->info
['name'];
917 elseif (CRM_Core_Permission
::check($componentPermission)) {
918 $components[$compObj->componentID
] = $compObj->info
['name'];
927 * function to get the activity Count
929 * @param array $input array of parameters
931 * - contact_id int contact_id whose activties we want to retrieve
932 * - admin boolean if contact is admin
933 * - caseId int case ID
934 * - context string page on which selector is build
935 * - activity_type_id int|string the activitiy types we want to restrict by
937 * @return int count of activities
942 static function &getActivitiesCount($input) {
943 $input['count'] = TRUE;
944 list($sqlClause, $params) = self
::getActivitySQLClause($input);
946 //filter case activities - CRM-5761
947 $components = self
::activityComponents();
948 if (!in_array('CiviCase', $components)) {
950 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
951 FROM ( {$sqlClause} ) as tbl
952 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
953 WHERE civicrm_case_activity.id IS NULL";
956 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
959 return CRM_Core_DAO
::singleValueQuery($query, $params);
963 * function to get the activity sql clause to pick activities
965 * @param array $input array of parameters
967 * - contact_id int contact_id whose activties we want to retrieve
968 * - admin boolean if contact is admin
969 * - caseId int case ID
970 * - context string page on which selector is build
971 * - count boolean are we interested in the count clause only?
972 * - activity_type_id int|string the activitiy types we want to restrict by
974 * @return int count of activities
979 static function getActivitySQLClause($input) {
981 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
983 $config = CRM_Core_Config
::singleton();
984 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
985 $sourceWhere = ' ac.contact_id = %1 ';
986 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
988 $params = array(1 => array($input['contact_id'], 'Integer'));
991 $commonClauses = array(
992 "civicrm_option_group.name = 'activity_type'",
993 "civicrm_activity.is_deleted = 0",
994 "civicrm_activity.is_current_revision = 1",
995 "civicrm_activity.is_test= 0",
998 if ($input['context'] != 'activity') {
999 $commonClauses[] = "civicrm_activity.status_id = 1";
1002 //Filter on component IDs.
1003 $components = self
::activityComponents();
1004 if (!empty($components)) {
1005 $componentsIn = implode(',', array_keys($components));
1006 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1009 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1012 // activity type ID clause
1013 if (!empty($input['activity_type_id'])) {
1014 if (is_array($input['activity_type_id'])) {
1015 foreach ($input['activity_type_id'] as $idx => $value) {
1016 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1018 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1021 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1022 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1026 // exclude by activity type clause
1027 if (!empty($input['activity_type_exclude_id'])) {
1028 if (is_array($input['activity_type_exclude_id'])) {
1029 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1030 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1032 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1035 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1036 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1040 $commonClause = implode(' AND ', $commonClauses);
1042 $includeCaseActivities = FALSE;
1043 if (in_array('CiviCase', $components)) {
1044 $includeCaseActivities = TRUE;
1048 // build main activity table select clause
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.status_id,
1059 civicrm_activity.subject,
1060 civicrm_activity.source_record_id,
1061 civicrm_option_value.value as activity_type_id,
1062 civicrm_option_value.label as activity_type,
1063 null as case_id, null as case_subject,
1064 civicrm_activity.campaign_id as campaign_id
1070 SELECT civicrm_activity.id as activity_id
1072 from civicrm_activity
1073 left join civicrm_option_value on
1074 civicrm_activity.activity_type_id = civicrm_option_value.value
1075 left join civicrm_option_group on
1076 civicrm_option_group.id = civicrm_option_value.option_group_id
1083 // Build case clause
1084 // or else exclude Inbound Emails that have been filed on a case.
1087 if ($includeCaseActivities) {
1089 if (!$input['count']) {
1091 civicrm_activity.activity_date_time,
1092 civicrm_activity.status_id,
1093 civicrm_activity.subject,
1094 civicrm_activity.source_contact_id,
1095 civicrm_activity.source_record_id,
1096 civicrm_option_value.value as activity_type_id,
1097 civicrm_option_value.label as activity_type,
1098 null as case_id, null as case_subject,
1099 civicrm_activity.campaign_id as campaign_id';
1105 SELECT civicrm_activity.id as activity_id
1107 from civicrm_activity
1108 inner join civicrm_case_activity on
1109 civicrm_case_activity.activity_id = civicrm_activity.id
1110 inner join civicrm_case on
1111 civicrm_case_activity.case_id = civicrm_case.id
1112 inner join civicrm_case_contact on
1113 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1114 left join civicrm_option_value on
1115 civicrm_activity.activity_type_id = civicrm_option_value.value
1116 left join civicrm_option_group on
1117 civicrm_option_group.id = civicrm_option_value.option_group_id
1122 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1123 ( civicrm_option_value.name <> 'Inbound Email' AND
1124 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1130 $returnClause = " {$sourceClause} {$caseClause} ";
1132 return array($returnClause, $params);
1136 * send the message to all the contacts and also insert a
1137 * contact activity in each contacts record
1139 * @param array $contactDetails the array of contact details to send the email
1140 * @param string $subject the subject of the message
1141 * @param string $message the message contents
1142 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1143 * @param int $userID use this userID if set
1144 * @param string $from
1145 * @param array $attachments the array of attachments if any
1146 * @param string $cc cc recepient
1147 * @param string $bcc bcc recepient
1148 * @param array $contactIds contact ids
1150 * @return array ( sent, activityId) if any email is sent and activityId
1154 static function sendEmail(
1162 $attachments = NULL,
1165 $contactIds // FIXME a param with no default shouldn't be last
1167 // get the contact details of logged in contact, which we set as from email
1168 if ($userID == NULL) {
1169 $session = CRM_Core_Session
::singleton();
1170 $userID = $session->get('userID');
1173 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1175 return array(count($contactDetails), 0, count($contactDetails));
1177 if (!trim($fromDisplayName)) {
1178 $fromDisplayName = $fromEmail;
1182 // token replacement of addressee/email/postal greetings
1183 // get the tokens added in subject and message
1184 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1185 $messageToken = CRM_Utils_Token
::getTokens($text);
1186 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1189 $from = "$fromDisplayName <$fromEmail>";
1192 //create the meta level record first ( email activity )
1193 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1198 // CRM-6265: save both text and HTML parts in details (if present)
1199 if ($html and $text) {
1200 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1203 $details = $html ?
$html : $text;
1206 $activityParams = array(
1207 'source_contact_id' => $userID,
1208 'activity_type_id' => $activityTypeID,
1209 'activity_date_time' => date('YmdHis'),
1210 'subject' => $subject,
1211 'details' => $details,
1212 // FIXME: check for name Completed and get ID from that lookup
1216 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1217 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1219 // add the attachments to activity params here
1221 // first process them
1222 $activityParams = array_merge($activityParams,
1227 $activity = self
::create($activityParams);
1229 // get the set of attachments from where they are stored
1230 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1233 $returnProperties = array();
1234 if (isset($messageToken['contact'])) {
1235 foreach ($messageToken['contact'] as $key => $value) {
1236 $returnProperties[$value] = 1;
1240 if (isset($subjectToken['contact'])) {
1241 foreach ($subjectToken['contact'] as $key => $value) {
1242 if (!isset($returnProperties[$value])) {
1243 $returnProperties[$value] = 1;
1249 // get token details for contacts, call only if tokens are used
1251 if (!empty($returnProperties)) {
1252 list($details) = CRM_Utils_Token
::getTokenDetails(
1257 'CRM_Activity_BAO_Activity'
1263 CRM_Utils_Hook
::tokens($tokens);
1264 $categories = array_keys($tokens);
1266 $escapeSmarty = FALSE;
1267 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1268 $smarty = CRM_Core_Smarty
::singleton();
1269 $escapeSmarty = TRUE;
1272 $sent = $notSent = array();
1273 foreach ($contactDetails as $values) {
1274 $contactId = $values['contact_id'];
1275 $emailAddress = $values['email'];
1277 if (!empty($details) && is_array($details["{$contactId}"])) {
1278 // unset email from details since it always returns primary email address
1279 unset($details["{$contactId}"]['email']);
1280 unset($details["{$contactId}"]['email_id']);
1281 $values = array_merge($values, $details["{$contactId}"]);
1284 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1285 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1288 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1289 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1290 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1296 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1297 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1298 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1304 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1305 // also add the contact tokens to the template
1306 $smarty->assign_by_ref('contact', $values);
1308 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1309 $tokenText = $smarty->fetch("string:$tokenText");
1310 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1314 if (self
::sendMessage(
1331 return array($sent, $activity->id
);
1334 static function sendSMS(&$contactDetails,
1336 &$smsParams = array(),
1340 if ($userID == NULL) {
1341 $session = CRM_Core_Session
::singleton();
1342 $userID = $session->get('userID');
1345 $text = &$activityParams['text_message'];
1346 $html = &$activityParams['html_message'];
1349 // token replacement of addressee/email/postal greetings
1350 // get the tokens added in subject and message
1351 $messageToken = CRM_Utils_Token
::getTokens($text);
1352 $messageToken = array_merge($messageToken,
1353 CRM_Utils_Token
::getTokens($html)
1356 //create the meta level record first ( sms activity )
1357 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1362 // CRM-6265: save both text and HTML parts in details (if present)
1363 if ($html and $text) {
1364 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1367 $details = $html ?
$html : $text;
1370 $activitySubject = $activityParams['activity_subject'];
1371 $activityParams = array(
1372 'source_contact_id' => $userID,
1373 'activity_type_id' => $activityTypeID,
1374 'activity_date_time' => date('YmdHis'),
1375 'subject' => $activitySubject,
1376 'details' => $details,
1377 // FIXME: check for name Completed and get ID from that lookup
1381 $activity = self
::create($activityParams);
1382 $activityID = $activity->id
;
1384 $returnProperties = array();
1386 if (isset($messageToken['contact'])) {
1387 foreach ($messageToken['contact'] as $key => $value) {
1388 $returnProperties[$value] = 1;
1394 CRM_Utils_Hook
::tokens($tokens);
1395 $categories = array_keys($tokens);
1397 // get token details for contacts, call only if tokens are used
1399 if (!empty($returnProperties) ||
!empty($tokens)) {
1400 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1404 'CRM_Activity_BAO_Activity'
1409 $escapeSmarty = $sent = FALSE;
1410 foreach ($contactDetails as $values) {
1411 $contactId = $values['contact_id'];
1413 if (!empty($details) && is_array($details["{$contactId}"])) {
1414 // unset email from details since it always returns primary email address
1415 unset($details["{$contactId}"]['email']);
1416 unset($details["{$contactId}"]['email_id']);
1417 $values = array_merge($values, $details["{$contactId}"]);
1420 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1421 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1423 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1424 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1426 // Only send if the phone is of type mobile
1427 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1428 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1429 $smsParams['To'] = $values['phone'];
1432 $smsParams['To'] = '';
1435 if (self
::sendSMSMessage(
1442 // even a single successful delivery should set this falg to true
1448 return array($sent, $activity->id
, $success);
1452 * send the sms message to a specific contact
1454 * @param int $toID the contact id of the recipient
1455 * @param int $activityID the activity ID that tracks the message
1456 * @param array $smsParams the params used for sending sms
1458 * @return boolean true if successfull else false.
1462 static function sendSMSMessage($toID,
1465 $smsParams = array(),
1469 $toPhoneNumber = "";
1471 if ($smsParams['To']) {
1472 $toPhoneNumber = trim($smsParams['To']);
1475 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1476 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1477 //to get primary mobile ph,if not get a first mobile ph
1478 if (!empty($toPhoneNumbers)) {
1479 $toPhoneNumerDetails = reset($toPhoneNumbers);
1480 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1481 //contact allows to send sms
1486 // make sure both phone are valid
1487 // and that the recipient wants to receive sms
1488 if (empty($toPhoneNumber) or $toDoNotSms) {
1492 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1493 $recipient = $smsParams['To'];
1494 $smsParams['contact_id'] = $toID;
1495 $smsParams['parent_activity_id'] = $activityID;
1497 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1498 if (!$providerObj->send($recipient, $smsParams, $message, NULL)) {
1502 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
1503 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1506 // add activity target record for every sms that is send
1507 $activityTargetParams = array(
1508 'activity_id' => $activityID,
1509 'contact_id' => $toID,
1510 'record_type_id' => $targetID
1512 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1518 * send the message to a specific contact
1520 * @param string $from the name and email of the sender
1521 * @param int $toID the contact id of the recipient
1522 * @param string $subject the subject of the message
1523 * @param string $message the message contents
1524 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1525 * @param int $activityID the activity ID that tracks the message
1527 * @return boolean true if successfull else false.
1531 static function sendMessage($from,
1539 $attachments = NULL,
1543 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1544 if ($emailAddress) {
1545 $toEmail = trim($emailAddress);
1548 // make sure both email addresses are valid
1549 // and that the recipient wants to receive email
1550 if (empty($toEmail) or $toDoNotEmail) {
1553 if (!trim($toDisplayName)) {
1554 $toDisplayName = $toEmail;
1557 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
1558 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1559 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1560 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1562 // create the params array
1563 $mailParams = array(
1564 'groupName' => 'Activity Email Sender',
1566 'toName' => $toDisplayName,
1567 'toEmail' => $toEmail,
1568 'subject' => $subject,
1571 'text' => $text_message,
1572 'html' => $html_message,
1573 'attachments' => $attachments,
1576 if (!CRM_Utils_Mail
::send($mailParams)) {
1580 // add activity target record for every mail that is send
1581 $activityTargetParams = array(
1582 'activity_id' => $activityID,
1583 'contact_id' => $toID,
1584 'record_type_id' => $targetID
1586 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1591 * combine all the importable fields from the lower levels object
1593 * The ordering is important, since currently we do not have a weight
1594 * scheme. Adding weight is super important and should be done in the
1595 * next week or so, before this can be called complete.
1599 * @return array array of importable Fields
1603 static function &importableFields($status = FALSE) {
1604 if (!self
::$_importableFields) {
1605 if (!self
::$_importableFields) {
1606 self
::$_importableFields = array();
1609 $fields = array('' => array('title' => ts('- do not import -')));
1612 $fields = array('' => array('title' => ts('- Activity Fields -')));
1615 $tmpFields = CRM_Activity_DAO_Activity
::import();
1616 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1618 // Using new Dedupe rule.
1619 $ruleParams = array(
1620 'contact_type' => 'Individual',
1621 'used' => 'Unsupervised',
1623 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1625 $tmpConatctField = array();
1626 if (is_array($fieldsArray)) {
1627 foreach ($fieldsArray as $value) {
1628 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1633 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1634 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1635 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1638 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1639 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1640 $fields = array_merge($fields, $tmpConatctField);
1641 $fields = array_merge($fields, $tmpFields);
1642 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1643 self
::$_importableFields = $fields;
1645 return self
::$_importableFields;
1649 * To get the Activities of a target contact
1651 * @param $contactId Integer ContactId of the contact whose activities
1654 * @return array array of activity fields
1657 static function getContactActivity($contactId) {
1658 $activities = array();
1659 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
1660 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1661 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1662 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1665 // First look for activities where contactId is one of the targets
1667 SELECT activity_id, record_type_id
1668 FROM civicrm_activity_contact
1669 WHERE contact_id = $contactId
1671 $dao = CRM_Core_DAO
::executeQuery($query);
1672 while ($dao->fetch()) {
1673 if ($dao->record_type_id
== $targetID ) {
1674 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1676 else if ($dao->record_type_id
== $assigneeID) {
1677 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1680 // do source stuff here
1681 $activities[$dao->activity_id
]['source_contact_id'][] = $contactId;
1685 $activityIds = array_keys($activities);
1686 if (count($activityIds) < 1) {
1690 $activityIds = implode(',', $activityIds);
1692 SELECT activity.id as activity_id,
1694 subject, location, activity_date_time, details, status_id
1695 FROM civicrm_activity activity
1696 WHERE activity.id IN ($activityIds)";
1698 $dao = CRM_Core_DAO
::executeQuery($query);
1700 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1701 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1703 while ($dao->fetch()) {
1704 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1705 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1706 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1707 $activities[$dao->activity_id
]['location'] = $dao->location
;
1708 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1709 $activities[$dao->activity_id
]['details'] = $dao->details
;
1710 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1711 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1712 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1718 * Function to add activity for Membership/Event/Contribution
1720 * @param object $activity (reference) perticular component object
1721 * @param string $activityType for Membership Signup or Renewal
1727 static function addActivity(&$activity,
1728 $activityType = 'Membership Signup',
1729 $targetContactID = NULL
1731 if ($activity->__table
== 'civicrm_membership') {
1732 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1734 if (!$membershipType) {
1735 $membershipType = ts('Membership');
1738 $subject = "{$membershipType}";
1740 if (!empty($activity->source
) && $activity->source
!= 'null') {
1741 $subject .= " - {$activity->source}";
1744 if ($activity->owner_membership_id
) {
1747 FROM civicrm_contact, civicrm_membership
1748 WHERE civicrm_contact.id = civicrm_membership.contact_id
1749 AND civicrm_membership.id = $activity->owner_membership_id
1751 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1752 $subject .= " (by {$displayName})";
1755 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1756 // CRM-72097 changed from start date to today
1757 $date = date('YmdHis');
1758 $component = 'Membership';
1760 elseif ($activity->__table
== 'civicrm_participant') {
1761 $event = CRM_Event_BAO_Event
::getEvents(TRUE, $activity->event_id
, TRUE, FALSE);
1763 $roles = CRM_Event_PseudoConstant
::participantRole();
1764 $status = CRM_Event_PseudoConstant
::participantStatus();
1766 $subject = $event[$activity->event_id
];
1767 if (CRM_Utils_Array
::value($activity->role_id
, $roles)) {
1768 $subject .= ' - ' . $roles[$activity->role_id
];
1770 if (CRM_Utils_Array
::value($activity->status_id
, $status)) {
1771 $subject .= ' - ' . $status[$activity->status_id
];
1773 $date = date('YmdHis');
1774 if ($activityType != 'Email') {
1775 $activityType = 'Event Registration';
1777 $component = 'Event';
1779 elseif ($activity->__table
== 'civicrm_contribution') {
1780 //create activity record only for Completed Contributions
1781 if ($activity->contribution_status_id
!= 1) {
1787 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1788 if (!empty($activity->source
) && $activity->source
!= 'null') {
1789 $subject .= " - {$activity->source}";
1791 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1792 $activityType = $component = 'Contribution';
1794 $activityParams = array(
1795 'source_contact_id' => $activity->contact_id
,
1796 'source_record_id' => $activity->id
,
1797 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1801 'subject' => $subject,
1802 'activity_date_time' => $date,
1803 'is_test' => $activity->is_test
,
1804 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1808 'skipRecentView' => TRUE,
1809 'campaign_id' => $activity->campaign_id
,
1812 // create activity with target contacts
1813 $session = CRM_Core_Session
::singleton();
1814 $id = $session->get('userID');
1816 $activityParams['source_contact_id'] = $id;
1817 $activityParams['target_contact_id'][] = $activity->contact_id
;
1821 if ($targetContactID) {
1822 $activityParams['target_contact_id'][] = $targetContactID;
1824 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1825 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1831 * Function to get Parent activity for currently viewd activity
1833 * @param int $activityId current activity id
1835 * @return int $parentId Id of parent acyivity otherwise false.
1838 static function getParentActivity($activityId) {
1839 static $parentActivities = array();
1841 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1843 if (!array_key_exists($activityId, $parentActivities)) {
1844 $parentActivities[$activityId] = array();
1846 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1851 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1854 return $parentActivities[$activityId];
1858 * Function to get total count of prior revision of currently viewd activity
1860 * @param int $activityId current activity id
1862 * @return int $params count of prior acyivities otherwise false.
1865 static function getPriorCount($activityID) {
1866 static $priorCounts = array();
1868 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1870 if (!array_key_exists($activityID, $priorCounts)) {
1871 $priorCounts[$activityID] = array();
1872 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1879 SELECT count( id ) AS cnt
1880 FROM civicrm_activity
1881 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1882 AND is_current_revision = 0
1883 AND id < {$activityID}
1885 $params = array(1 => array($originalID, 'Integer'));
1886 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1888 $priorCounts[$activityID] = $count ?
$count : 0;
1891 return $priorCounts[$activityID];
1895 * Function to get all prior activities of currently viewd activity
1897 * @param int $activityId current activity id
1899 * @return array $result prior acyivities info.
1902 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1903 static $priorActivities = array();
1905 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1906 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1908 if (!array_key_exists($index, $priorActivities)) {
1909 $priorActivities[$index] = array();
1911 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1917 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1918 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1919 WHERE (ca.id = %1 OR ca.original_id = %1)
1920 AND cl.entity_table = 'civicrm_activity'
1921 AND cl.entity_id = ca.id
1922 AND cl.modified_id = c.id
1924 if ($onlyPriorRevisions) {
1925 $query .= " AND ca.id < {$activityID}";
1927 $query .= " ORDER BY ca.id DESC";
1929 $params = array(1 => array($originalID, 'Integer'));
1930 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1932 while ($dao->fetch()) {
1933 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1934 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1935 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1936 $priorActivities[$index][$dao->activityID
]['link'] = 'javascript:viewActivity( $dao->activityID );';
1941 return $priorActivities[$index];
1945 * Function to find the latest revision of a given activity
1947 * @param int $activityId prior activity id
1949 * @return int $params current activity id.
1952 static function getLatestActivityId($activityID) {
1953 static $latestActivityIds = array();
1955 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1957 if (!array_key_exists($activityID, $latestActivityIds)) {
1958 $latestActivityIds[$activityID] = array();
1960 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1965 $activityID = $originalID;
1967 $params = array(1 => array($activityID, 'Integer'));
1968 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1970 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
1973 return $latestActivityIds[$activityID];
1977 * Function to create a follow up a given activity
1979 * @activityId int activity id of parent activity
1981 * @param array $activity details
1985 static function createFollowupActivity($activityId, $params) {
1990 $session = CRM_Core_Session
::singleton();
1992 $followupParams = array();
1993 $followupParams['parent_id'] = $activityId;
1994 $followupParams['source_contact_id'] = $session->get('userID');
1995 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
1997 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1998 // Get Subject of Follow-up Activiity, CRM-4491
1999 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2001 //create target contact for followup
2002 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2003 $followupParams['target_contact_id'] = $params['target_contact_id'];
2006 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2007 $params['followup_date_time']
2009 $followupActivity = self
::create($followupParams);
2011 return $followupActivity;
2015 * Function to get Activity specific File according activity type Id.
2017 * @param int $activityTypeId activity id
2019 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2023 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2024 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2026 if ($activityTypes[$activityTypeId]['name']) {
2027 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2033 global $civicrm_root;
2034 $config = CRM_Core_Config
::singleton();
2035 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2036 if (empty($config->customPHPPathDir
)) {
2039 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2044 return $activityTypeFile;
2048 * Function to restore the activity
2050 * @param array $params associated array
2056 public static function restoreActivity(&$params) {
2057 $activity = new CRM_Activity_DAO_Activity();
2058 $activity->copyValues($params);
2060 $activity->is_deleted
= 0;
2061 $result = $activity->save();
2067 * Get the exportable fields for Activities
2069 * @param string $name if it is called by case $name = Case else $name = Activity
2071 * @return array array of exportable Fields
2075 static function &exportableFields($name = 'Activity') {
2076 if (!isset(self
::$_exportableFields[$name])) {
2077 self
::$_exportableFields[$name] = array();
2079 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2080 // my case hence we have defined fields as case_*
2081 if ($name == 'Activity') {
2082 $exportableFields = CRM_Activity_DAO_Activity
::export();
2083 if (isset($exportableFields['activity_campaign_id'])) {
2084 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2086 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2087 $exportableFields['source_contact'] = array(
2088 'title' => ts('Source Contact'),
2089 'type' => CRM_Utils_Type
::T_STRING
,
2093 $Activityfields = array(
2094 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2095 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2097 $fields = array_merge($Activityfields, $exportableFields);
2100 //set title to activity fields
2102 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2103 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2104 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2105 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2106 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2107 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2108 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2109 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2110 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2111 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2114 // add custom data for cases
2115 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2118 // add custom data for case activities
2119 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2121 self
::$_exportableFields[$name] = $fields;
2123 return self
::$_exportableFields[$name];
2127 * Get the allowed profile fields for Activities
2129 * @return array array of activity profile Fields
2132 static function getProfileFields() {
2133 $exportableFields = self
::exportableFields('Activity');
2134 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2135 $config = CRM_Core_Config
::singleton();
2136 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2137 $skipFields[] = 'activity_engagement_level';
2140 foreach ($skipFields as $field) {
2141 if (isset($exportableFields[$field])) {
2142 unset($exportableFields[$field]);
2146 // hack to use 'activity_type_id' instead of 'activity_type'
2147 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2148 unset($exportableFields['activity_status']);
2150 return $exportableFields;
2154 * This function delete activity record related to contact record,
2155 * when there are no target and assignee record w/ other contact.
2157 * @param int $contactId contactId
2162 public static function cleanupActivity($contactId) {
2167 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
2168 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2170 $transaction = new CRM_Core_Transaction();
2172 // delete activity if there is no record in
2173 // civicrm_activity_contact
2174 // pointing to any other contact record.
2175 $activityContact = new CRM_Activity_DAO_ActivityContact();
2176 $activityContact->contact_id
= $contactId;
2177 $activityContact->record_type_id
= $sourceID;
2178 $activityContact->find();
2180 while ($activityContact->fetch()) {
2181 // finally delete activity.
2182 if (CRM_Core_DAO
::singleValueQuery($sql)) {
2183 $activityParams = array('id' => $activityContact->activity_id
);
2184 $result = self
::deleteActivity($activityParams);
2188 $activityContact->free();
2189 $transaction->commit();
2195 * Does user has sufficient permission for view/edit activity record.
2197 * @param int $activityId activity record id.
2198 * @param int $action edit/view
2200 * @return boolean $allow true/false
2203 public static function checkPermission($activityId, $action) {
2206 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2211 $activity = new CRM_Activity_DAO_Activity();
2212 $activity->id
= $activityId;
2213 if (!$activity->find(TRUE)) {
2217 //component related permissions.
2218 $compPermissions = array(
2219 'CiviCase' => array('administer CiviCase',
2220 'access my cases and activities',
2221 'access all cases and activities',
2223 'CiviMail' => array('access CiviMail'),
2224 'CiviEvent' => array('access CiviEvent'),
2225 'CiviGrant' => array('access CiviGrant'),
2226 'CiviPledge' => array('access CiviPledge'),
2227 'CiviMember' => array('access CiviMember'),
2228 'CiviReport' => array('access CiviReport'),
2229 'CiviContribute' => array('access CiviContribute'),
2230 'CiviCampaign' => array('administer CiviCampaign'),
2233 //return early when it is case activity.
2234 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2235 //check for civicase related permission.
2236 if ($isCaseActivity) {
2238 foreach ($compPermissions['CiviCase'] as $per) {
2239 if (CRM_Core_Permission
::check($per)) {
2245 //check for case specific permissions.
2248 if ($action == CRM_Core_Action
::UPDATE
) {
2251 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2253 $activity->activity_type_id
2260 //first check the component permission.
2263 FROM civicrm_option_value val
2264 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2265 WHERE val.value = %2";
2266 $params = array(1 => array('activity_type', 'String'),
2267 2 => array($activity->activity_type_id
, 'Integer'),
2269 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2272 $componentName = CRM_Core_Component
::getComponentName($componentId);
2273 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2275 //here we are interesting in any single permission.
2276 if (is_array($compPermission)) {
2277 foreach ($compPermission as $per) {
2278 if (CRM_Core_Permission
::check($per)) {
2286 //check for this permission related to contact.
2287 $permission = CRM_Core_Permission
::VIEW
;
2288 if ($action == CRM_Core_Action
::UPDATE
) {
2289 $permission = CRM_Core_Permission
::EDIT
;
2292 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
2293 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2294 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2295 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2297 //check for source contact.
2298 if (!$componentId ||
$allow) {
2299 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2300 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2303 //check for target and assignee contacts.
2305 //first check for supper permission.
2306 $supPermission = 'view all contacts';
2307 if ($action == CRM_Core_Action
::UPDATE
) {
2308 $supPermission = 'edit all contacts';
2310 $allow = CRM_Core_Permission
::check($supPermission);
2312 //user might have sufficient permission, through acls.
2315 //get the target contacts.
2316 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2317 foreach ($targetContacts as $cnt => $contactId) {
2318 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2324 //get the assignee contacts.
2326 $assigneeContacts = CRM_Activity_BAO_Contact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2327 foreach ($assigneeContacts as $cnt => $contactId) {
2328 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2341 * This function is a wrapper for ajax activity selector
2343 * @param array $params associated array for params record id.
2345 * @return array $contactActivities associated array of contact activities
2348 public static function getContactActivitySelector(&$params) {
2349 // format the params
2350 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2351 $params['rowCount'] = $params['rp'];
2352 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2353 $params['caseId'] = NULL;
2354 $context = CRM_Utils_Array
::value('context', $params);
2356 // get contact activities
2357 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2360 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2362 // format params and add links
2363 $contactActivities = array();
2365 if (!empty($activities)) {
2366 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2368 // check logged in user for permission
2369 $page = new CRM_Core_Page();
2370 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2371 $permissions = array($page->_permission
);
2372 if (CRM_Core_Permission
::check('delete activities')) {
2373 $permissions[] = CRM_Core_Permission
::DELETE
;
2376 $mask = CRM_Core_Action
::mask($permissions);
2378 foreach ($activities as $activityId => $values) {
2379 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2380 $contactActivities[$activityId]['subject'] = $values['subject'];
2381 if ($params['contact_id'] == $values['source_contact_id']) {
2382 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2384 elseif ($values['source_contact_id']) {
2385 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2388 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2391 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2392 $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");
2394 elseif (CRM_Utils_Array
::value('recipients', $values)) {
2395 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2397 elseif (!$values['target_contact_name']) {
2398 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2400 elseif (!empty($values['target_contact_name'])) {
2402 $contactActivities[$activityId]['target_contact'] = '';
2403 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2404 if ($tcID && $count < 5) {
2405 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2408 $contactActivities[$activityId]['target_contact'] .= "; ";
2412 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2419 if (empty($values['assignee_contact_name'])) {
2420 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2422 elseif (!empty($values['assignee_contact_name'])) {
2424 $contactActivities[$activityId]['assignee_contact'] = '';
2425 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2426 if ($acID && $count < 5) {
2427 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2430 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2434 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2440 if ( $values['activity_type'] == 'Bulk Email'){
2441 $contactActivities[$activityId]['openstats'] = "Opens: ".
2442 count(CRM_Mailing_Event_BAO_Opened
::getRows(
2443 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2446 count(CRM_Mailing_Event_BAO_TrackableURLOpen
::getRows(
2447 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2450 $contactActivities[$activityId]['openstats'] = '';
2453 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2454 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2456 // add class to this row if overdue
2457 $contactActivities[$activityId]['class'] = '';
2458 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2459 && CRM_Utils_Array
::value('status_id', $values) == 1
2461 $contactActivities[$activityId]['class'] = 'status-overdue';
2464 $contactActivities[$activityId]['class'] = 'status-ontime';
2468 $contactActivities[$activityId]['links'] = '';
2469 $accessMailingReport = FALSE;
2470 if (CRM_Utils_Array
::value('mailingId', $values)) {
2471 $accessMailingReport = TRUE;
2474 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2475 CRM_Utils_Array
::value('activity_type_id', $values),
2476 CRM_Utils_Array
::value('source_record_id', $values),
2477 $accessMailingReport,
2478 CRM_Utils_Array
::value('activity_id', $values)
2481 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2483 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2486 'id' => $values['activity_id'],
2487 'cid' => $params['contact_id'],
2489 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2495 return $contactActivities;
2499 * Used to copy custom fields and attachments from an existing activity to another.
2500 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2502 static function copyExtendedActivityData($params) {
2503 // attach custom data to the new activity
2504 $customParams = $htmlType = array();
2505 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2507 if (!empty($customValues)) {
2508 $fieldIds = implode(', ', array_keys($customValues));
2509 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2510 $result = CRM_Core_DAO
::executeQuery($sql);
2512 while ($result->fetch()) {
2513 $htmlType[] = $result->id
;
2516 foreach ($customValues as $key => $value) {
2517 if ($value !== NULL) { // CRM-10542
2518 if (in_array($key, $htmlType)) {
2519 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2520 $customParams["custom_{$key}_-1"] = array(
2521 'name' => $fileValues[0],
2522 'path' => $fileValues[1],
2526 $customParams["custom_{$key}_-1"] = $value;
2530 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2531 $params['mainActivityId'], 'Activity'
2535 // copy activity attachments ( if any )
2536 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2539 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2540 $activityContact = new CRM_Activity_BAO_ActivityContact();
2541 $activityContact->activity_id
= $activityId;
2542 if ($recordTypeID) {
2543 $activityContact->record_type_id
= $recordTypeID;
2545 if ($activityContact->find(TRUE)) {
2546 return $activityContact->$column;