3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class is for activity functions
40 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
43 * static field for all the activity information that we can potentially export
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 (!empty($params['source_contact_id']) ||
!empty($params['id'])) {
74 * Takes a bunch of params that are needed to match certain criteria and
75 * retrieves the relevant objects. Typically the valid params are only
76 * contact_id. We'll tweak this function to be more full featured over a period
77 * of time. This is the inverse function of create. It also stores all the retrieved
78 * values in the default array
80 * @param array $params (reference ) an assoc array of name/value pairs
81 * @param array $defaults (reference ) an assoc array to hold the flattened values
82 * @param string $activityType activity type
84 * @return object CRM_Core_BAO_Meeting object
87 public static function retrieve(&$params, &$defaults) {
88 $activity = new CRM_Activity_DAO_Activity();
89 $activity->copyValues($params);
91 if ($activity->find(TRUE)) {
92 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
93 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
94 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
95 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
97 // TODO: at some stage we'll have to deal
98 // TODO: with multiple values for assignees and targets, but
99 // TODO: for now, let's just fetch first row
100 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
101 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
102 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
103 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
104 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
105 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
106 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
107 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
109 elseif (CRM_Core_Permission
::check('access CiviMail') ||
110 (CRM_Mailing_Info
::workflowEnabled() &&
111 CRM_Core_Permission
::check('create mailings')
114 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
115 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
119 $defaults['target_contact_value'] = ts('(recipients)');
122 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
123 $defaults['source_contact_id'] = $sourceContactId;
125 if ($sourceContactId &&
126 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
131 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
138 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
140 CRM_Core_DAO
::storeValues($activity, $defaults);
148 * Function to delete the activity
150 * @param array $params associated array
156 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
158 if (!empty($params['id']) && !is_array($params['id'])) {
159 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
162 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
165 $transaction = new CRM_Core_Transaction();
166 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
167 $sourceRecordIds = implode(',', $params['source_record_id']);
170 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
175 if (!isset($params['id'])) {
176 if (is_array($params['activity_type_id'])) {
177 $activityTypes = implode(',', $params['activity_type_id']);
180 $activityTypes = $params['activity_type_id'];
183 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
184 $dao = CRM_Core_DAO
::executeQuery($query);
187 $activity = new CRM_Activity_DAO_Activity();
188 $activity->copyValues($params);
189 $result = $activity->delete();
192 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
194 // CRM-13994 delete activity entity_tag
195 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
196 $dao = CRM_Core_DAO
::executeQuery($query);
200 $activity = new CRM_Activity_DAO_Activity();
201 $activity->copyValues($params);
203 $activity->is_deleted
= 1;
204 $result = $activity->save();
206 // CRM-4525 log activity delete
207 $logMsg = 'Case Activity deleted for';
210 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
211 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
212 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
213 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
214 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
215 if ($sourceContactId) {
216 $msgs[] = " source={$sourceContactId}";
219 //get target contacts.
220 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
221 if (!empty($targetContactIds)) {
222 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
224 //get assignee contacts.
225 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
226 if (!empty($assigneeContactIds)) {
227 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
230 $logMsg .= implode(', ', $msgs);
232 self
::logActivityAction($activity, $logMsg);
235 // delete the recently created Activity
237 $activityRecent = array(
238 'id' => $activity->id
,
239 'type' => 'Activity',
241 CRM_Utils_Recent
::del($activityRecent);
244 $transaction->commit();
245 if (isset($activity)) {
247 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
248 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
255 * Delete activity assignment record
257 * @param int $id activity id
262 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
263 $activityContact = new CRM_Activity_BAO_ActivityContact();
264 $activityContact->activity_id
= $activityId;
266 $activityContact->record_type_id
= $recordTypeID;
268 $activityContact->delete();
272 * Function to process the activities
274 * @param object $form form object
275 * @param array $params associated array of the submitted values
276 * @param array $ids array of ids
277 * @param string $activityType activity Type
278 * @param boolean $record true if it is Record Activity
283 public static function create(&$params) {
284 // check required params
285 if (!self
::dataExists($params)) {
286 CRM_Core_Error
::fatal('Not enough data to create activity object,');
289 $activity = new CRM_Activity_DAO_Activity();
291 if (isset($params['id']) && empty($params['id'])) {
292 unset($params['id']);
295 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
296 if (isset($params['activity_date_time']) &&
297 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
299 $params['status_id'] = 2;
302 $params['status_id'] = 1;
306 //set priority to Normal for Auto-populated activities (for Cases)
307 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
308 // if not set and not 0
309 !CRM_Utils_Array
::value('id', $params)
311 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
312 $params['priority_id'] = array_search('Normal', $priority);
315 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
316 $params['target_contact_id'] = array_unique($params['target_contact_id']);
318 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
319 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
323 if (!empty($params['id'])) {
324 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
327 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
330 $activity->copyValues($params);
331 if (isset($params['case_id'])) {
332 // CRM-8708, preserve case ID even though it's not part of the SQL model
333 $activity->case_id
= $params['case_id'];
335 elseif (is_numeric($activity->id
)) {
336 // CRM-8708, preserve case ID even though it's not part of the SQL model
337 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
341 $transaction = new CRM_Core_Transaction();
343 $result = $activity->save();
345 if (is_a($result, 'CRM_Core_Error')) {
346 $transaction->rollback();
350 $activityId = $activity->id
;
351 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
352 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
353 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
354 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
356 if (isset($params['source_contact_id'])) {
358 'activity_id' => $activityId,
359 'contact_id' => $params['source_contact_id'],
360 'record_type_id' => $sourceID
362 self
::deleteActivityContact($activityId, $sourceID);
363 CRM_Activity_BAO_ActivityContact
::create($acParams);
366 // check and attach and files as needed
367 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
369 // attempt to save activity assignment
370 $resultAssignment = NULL;
371 if (!empty($params['assignee_contact_id'])) {
373 $assignmentParams = array('activity_id' => $activityId);
375 if (is_array($params['assignee_contact_id'])) {
376 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
377 // first delete existing assignments if any
378 self
::deleteActivityContact($activityId, $assigneeID);
382 foreach ($params['assignee_contact_id'] as $acID) {
384 $values[] = "( $activityId, $acID, $assigneeID )";
387 while (!empty($values)) {
388 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
389 $str = implode(',', $input);
390 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
391 CRM_Core_DAO
::executeQuery($sql);
395 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
396 $assignmentParams['record_type_id'] = $assigneeID;
397 if (!empty($params['id'])) {
398 $assignment = new CRM_Activity_BAO_ActivityContact();
399 $assignment->activity_id
= $activityId;
400 $assignment->record_type_id
= $assigneeID;
401 $assignment->find(TRUE);
403 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
404 $assignmentParams['id'] = $assignment->id
;
405 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
409 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
414 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
415 self
::deleteActivityContact($activityId, $assigneeID);
419 if (is_a($resultAssignment, 'CRM_Core_Error')) {
420 $transaction->rollback();
421 return $resultAssignment;
424 // attempt to save activity targets
425 $resultTarget = NULL;
426 if (!empty($params['target_contact_id'])) {
428 $targetParams = array('activity_id' => $activityId);
429 $resultTarget = array();
430 if (is_array($params['target_contact_id'])) {
431 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
432 // first delete existing targets if any
433 self
::deleteActivityContact($activityId, $targetID );
437 foreach ($params['target_contact_id'] as $tid) {
439 $values[] = "( $activityId, $tid, $targetID )";
443 while (!empty($values)) {
444 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
445 $str = implode(',', $input);
446 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
447 CRM_Core_DAO
::executeQuery($sql);
451 $targetParams['contact_id'] = $params['target_contact_id'];
452 $targetParams['record_type_id'] = $targetID;
453 if (!empty($params['id'])) {
454 $target = new CRM_Activity_BAO_ActivityContact();
455 $target->activity_id
= $activityId;
456 $target->record_type_id
= $targetID;
459 if ($target->contact_id
!= $params['target_contact_id']) {
460 $targetParams['id'] = $target->id
;
461 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
465 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
470 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
471 self
::deleteActivityContact($activityId, $targetID );
475 // write to changelog before transaction is committed/rolled
476 // back (and prepare status to display)
477 if (!empty($params['id'])) {
478 $logMsg = "Activity (id: {$result->id} ) updated with ";
481 $logMsg = "Activity created for ";
485 if (isset($params['source_contact_id'])) {
486 $msgs[] = "source={$params['source_contact_id']}";
489 if (!empty($params['target_contact_id'])) {
490 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
491 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
492 // take only first target
493 // will be used for recently viewed display
494 $t = array_slice($params['target_contact_id'], 0, 1);
495 $recentContactId = $t[0];
497 elseif (isset($params['target_contact_id'])) {
498 $msgs[] = "target={$params['target_contact_id']}";
499 // will be used for recently viewed display
500 $recentContactId = $params['target_contact_id'];
504 // at worst, take source for recently viewed display
505 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
508 if (isset($params['assignee_contact_id'])) {
509 if (is_array($params['assignee_contact_id'])) {
510 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
513 $msgs[] = "assignee={$params['assignee_contact_id']}";
516 $logMsg .= implode(', ', $msgs);
518 self
::logActivityAction($result, $logMsg);
520 if (!empty($params['custom']) &&
521 is_array($params['custom'])
523 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
526 $transaction->commit();
527 if (empty($params['skipRecentView'])) {
528 $recentOther = array();
529 if (!empty($params['case_id'])) {
530 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
531 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
532 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
536 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home";
537 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
538 $url = CRM_Utils_System
::url('civicrm/activity', $q);
539 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
540 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
541 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
545 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
546 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
550 if (CRM_Core_Permission
::check("delete activities")) {
551 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
552 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
557 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
558 if (CRM_Core_Permission
::check('delete activities')) {
559 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
560 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
566 if (!isset($activity->parent_id
)) {
567 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
568 // add the recently created Activity
569 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
570 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
573 if (isset($activitySubject)) {
574 $title = $activitySubject . ' - ';
577 $title = $title . $recentContactDisplay;
578 if (!empty($activityTypes[$activity->activity_type_id
])) {
579 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
582 CRM_Utils_Recent
::add($title,
587 $recentContactDisplay,
593 // reset the group contact cache since smart groups might be affected due to this
594 CRM_Contact_BAO_GroupContactCache
::remove();
596 if (!empty($params['id'])) {
597 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
600 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
603 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
605 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
606 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
608 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
610 'activity_id' => $activity->id
,
611 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
613 if ($caseParams['case_id']) {
614 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
617 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
624 public static function logActivityAction($activity, $logMessage = NULL) {
625 $session = CRM_Core_Session
::singleton();
626 $id = $session->get('userID');
628 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
629 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
630 $id = self
::getActivityContact($activity->id
. $sourceID);
633 'entity_table' => 'civicrm_activity',
634 'entity_id' => $activity->id
,
635 'modified_id' => $id,
636 'modified_date' => date('YmdHis'),
637 'data' => $logMessage,
639 CRM_Core_BAO_Log
::add($logParams);
644 * function to get the list Activities
646 * @param array $input array of parameters
648 * - contact_id int contact_id whose activities we want to retrieve
649 * - offset int which row to start from ?
650 * - rowCount int how many rows to fetch
651 * - sort object|array object or array describing sort order for sql query.
652 * - admin boolean if contact is admin
653 * - caseId int case ID
654 * - context string page on which selector is build
655 * - activity_type_id int|string the activitiy types we want to restrict by
657 * @return array (reference) $values the relevant data object values of open activities
662 static function &getActivities($input) {
663 //step 1: Get the basic activity data
664 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
670 $config = CRM_Core_Config
::singleton();
672 $randomNum = md5(uniqid());
673 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
675 $tableFields = array(
676 'activity_id' => 'int unsigned',
677 'activity_date_time' => 'datetime',
678 'source_record_id' => 'int unsigned',
679 'status_id' => 'int unsigned',
680 'subject' => 'varchar(255)',
681 'source_contact_name' => 'varchar(255)',
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 // The activityTempTable contains the sorted rows
692 // so in order to maintain the sort order as-is we add an auto_increment
693 // field; we can sort by this later to ensure the sort order stays correct.
694 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
695 foreach ($tableFields as $name => $desc) {
696 $sql .= "$name $desc,\n";
697 $insertValueSQL[] = $name;
700 // add unique key on activity_id just to be sure
701 // this cannot be primary key because we need that for the auto_increment
702 // fixed_sort_order field
704 UNIQUE KEY ( activity_id )
705 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
708 CRM_Core_DAO
::executeQuery($sql);
710 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
712 $order = $limit = $groupBy = '';
713 $groupBy = " GROUP BY tbl.activity_id ";
715 if (!empty($input['sort'])) {
716 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
717 $orderBy = $input['sort']->orderBy();
718 if (!empty($orderBy)) {
719 $order = " ORDER BY $orderBy";
722 elseif (trim($input['sort'])) {
723 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
724 $order = " ORDER BY $sort ";
729 // context = 'activity' in Activities tab.
730 $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 ";
733 if (!empty($input['rowCount']) &&
734 $input['rowCount'] > 0
736 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
739 $input['count'] = FALSE;
741 // skip bulk activities in activity tab
742 $input['activity_type_exclude_id'][$bulkActivityTypeID] = $bulkActivityTypeID;
743 list($sqlClause, $params) = self
::getActivitySQLClause($input);
745 $query = "{$insertSQL}
746 SELECT DISTINCT tbl.* from ( {$sqlClause} )
749 //filter case activities - CRM-5761
750 $components = self
::activityComponents();
751 if (!in_array('CiviCase', $components)) {
753 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
754 WHERE civicrm_case_activity.id IS NULL";
757 $query = $query . $groupBy . $order . $limit;
759 $dao = CRM_Core_DAO
::executeQuery($query, $params);
761 // step 2: Get target and assignee contacts for above activities
762 // create temp table for target contacts
763 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
764 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
765 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
766 contact_name varchar(255), is_deleted int unsigned, INDEX index_activity_id( activity_id ) )
767 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
769 CRM_Core_DAO
::executeQuery($query);
771 // note that we ignore bulk email for targets, since we don't show it in selector
773 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
774 SELECT ac.activity_id,
779 FROM {$activityTempTable}
780 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
781 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
782 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
784 CRM_Core_DAO
::executeQuery($query);
786 // step 3: Combine all temp tables to get final query for activity selector
787 // sort by the original sort order, stored in fixed_sort_order
789 SELECT {$activityTempTable}.*,
790 {$activityContactTempTable}.contact_id,
791 {$activityContactTempTable}.record_type_id,
792 {$activityContactTempTable}.contact_name,
793 {$activityContactTempTable}.is_deleted
794 FROM {$activityTempTable}
795 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
796 ORDER BY fixed_sort_order
800 $dao = CRM_Core_DAO
::executeQuery($query);
802 //CRM-3553, need to check user has access to target groups.
803 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
805 (CRM_Core_Permission
::check('access CiviMail')) ||
806 (CRM_Mailing_Info
::workflowEnabled() &&
807 CRM_Core_Permission
::check('create mailings'))
811 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
814 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
815 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
816 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
817 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
820 while ($dao->fetch()) {
821 $activityID = $dao->activity_id
;
822 $values[$activityID]['activity_id'] = $dao->activity_id
;
823 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
824 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
825 $values[$activityID]['activity_type'] = $dao->activity_type
;
826 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
827 $values[$activityID]['status_id'] = $dao->status_id
;
828 $values[$activityID]['subject'] = $dao->subject
;
829 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
831 if ($dao->campaign_id
) {
832 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
835 if (empty($values[$activityID]['assignee_contact_name'])) {
836 $values[$activityID]['assignee_contact_name'] = array();
839 if (empty($values[$activityID]['target_contact_name'])) {
840 $values[$activityID]['target_contact_name'] = array();
843 // if deleted, wrap in <del>
844 if ( $dao->is_deleted
) {
845 $dao->contact_name
= "<del>{$dao->contact_name}</dao>";
848 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
849 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
850 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
853 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
854 // build array of target / assignee names
855 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
856 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
858 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
859 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
862 // case related fields
863 $values[$activityID]['case_id'] = $dao->case_id
;
864 $values[$activityID]['case_subject'] = $dao->case_subject
;
867 $values[$activityID]['recipients'] = ts('(recipients)');
868 $values[$activityID]['mailingId'] = false;
871 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
873 $values[$activityID]['mailingId'] = true;
882 * Get the component id and name those are enabled and logged in
883 * user has permission. To decide whether we are going to include
884 * component related activities w/ core activity retrieve process.
886 * return an array of component id and name.
889 static function activityComponents() {
890 $components = array();
891 $compInfo = CRM_Core_Component
::getEnabledComponents();
892 foreach ($compInfo as $compObj) {
893 if (!empty($compObj->info
['showActivitiesInCore'])) {
894 if ($compObj->info
['name'] == 'CiviCampaign') {
895 $componentPermission = "administer {$compObj->name}";
898 $componentPermission = "access {$compObj->name}";
900 if ($compObj->info
['name'] == 'CiviCase') {
901 if (CRM_Case_BAO_Case
::accessCiviCase()) {
902 $components[$compObj->componentID
] = $compObj->info
['name'];
905 elseif (CRM_Core_Permission
::check($componentPermission)) {
906 $components[$compObj->componentID
] = $compObj->info
['name'];
915 * function to get the activity Count
917 * @param array $input array of parameters
919 * - contact_id int contact_id whose activities we want to retrieve
920 * - admin boolean if contact is admin
921 * - caseId int case ID
922 * - context string page on which selector is build
923 * - activity_type_id int|string the activity types we want to restrict by
925 * @return int count of activities
930 static function &getActivitiesCount($input) {
931 // skip bulk activities in activity tab
932 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
937 $input['activity_type_exclude_id'][$bulkActivityTypeID] = $bulkActivityTypeID;
939 $input['count'] = TRUE;
940 list($sqlClause, $params) = self
::getActivitySQLClause($input);
942 //filter case activities - CRM-5761
943 $components = self
::activityComponents();
944 if (!in_array('CiviCase', $components)) {
946 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
947 FROM ( {$sqlClause} ) as tbl
948 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
949 WHERE civicrm_case_activity.id IS NULL";
952 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
955 return CRM_Core_DAO
::singleValueQuery($query, $params);
959 * function to get the activity sql clause to pick activities
961 * @param array $input array of parameters
963 * - contact_id int contact_id whose activities we want to retrieve
964 * - admin boolean if contact is admin
965 * - caseId int case ID
966 * - context string page on which selector is build
967 * - count boolean are we interested in the count clause only?
968 * - activity_type_id int|string the activity types we want to restrict by
970 * @return int count of activities
975 static function getActivitySQLClause($input) {
977 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
979 $config = CRM_Core_Config
::singleton();
980 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
981 $sourceWhere = ' ac.contact_id = %1 ';
982 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
984 $params = array(1 => array($input['contact_id'], 'Integer'));
987 $commonClauses = array(
988 "civicrm_option_group.name = 'activity_type'",
989 "civicrm_activity.is_deleted = 0",
990 "civicrm_activity.is_current_revision = 1",
991 "civicrm_activity.is_test= 0",
994 if ($input['context'] != 'activity') {
995 $commonClauses[] = "civicrm_activity.status_id = 1";
998 //Filter on component IDs.
999 $components = self
::activityComponents();
1000 if (!empty($components)) {
1001 $componentsIn = implode(',', array_keys($components));
1002 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1005 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1008 // activity type ID clause
1009 if (!empty($input['activity_type_id'])) {
1010 if (is_array($input['activity_type_id'])) {
1011 foreach ($input['activity_type_id'] as $idx => $value) {
1012 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1014 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1017 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1018 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1022 // exclude by activity type clause
1023 if (!empty($input['activity_type_exclude_id'])) {
1024 if (is_array($input['activity_type_exclude_id'])) {
1025 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1026 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1028 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1031 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1032 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1036 $commonClause = implode(' AND ', $commonClauses);
1038 $includeCaseActivities = FALSE;
1039 if (in_array('CiviCase', $components)) {
1040 $includeCaseActivities = TRUE;
1044 // build main activity table select clause
1047 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1048 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1050 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1051 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1054 if (!$input['count']) {
1056 civicrm_activity.activity_date_time,
1057 civicrm_activity.source_record_id,
1058 civicrm_activity.status_id,
1059 civicrm_activity.subject,
1060 contact.sort_name as source_contact_name,
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
1068 LEFT JOIN civicrm_activity_contact src ON (src.activity_id = ac.activity_id AND src.record_type_id = {$sourceID} AND src.contact_id = contact.id)
1073 SELECT civicrm_activity.id as activity_id
1075 from civicrm_activity
1076 left join civicrm_option_value on
1077 civicrm_activity.activity_type_id = civicrm_option_value.value
1078 left join civicrm_option_group on
1079 civicrm_option_group.id = civicrm_option_value.option_group_id
1086 // Build case clause
1087 // or else exclude Inbound Emails that have been filed on a case.
1090 if ($includeCaseActivities) {
1092 if (!$input['count']) {
1094 civicrm_activity.activity_date_time,
1095 civicrm_activity.source_record_id,
1096 civicrm_activity.status_id,
1097 civicrm_activity.subject,
1098 contact.sort_name as source_contact_name,
1099 civicrm_option_value.value as activity_type_id,
1100 civicrm_option_value.label as activity_type,
1101 null as case_id, null as case_subject,
1102 civicrm_activity.campaign_id as campaign_id';
1108 SELECT civicrm_activity.id as activity_id
1110 from civicrm_activity
1111 inner join civicrm_case_activity on
1112 civicrm_case_activity.activity_id = civicrm_activity.id
1113 inner join civicrm_case on
1114 civicrm_case_activity.case_id = civicrm_case.id
1115 inner join civicrm_case_contact on
1116 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1117 left join civicrm_option_value on
1118 civicrm_activity.activity_type_id = civicrm_option_value.value
1119 left join civicrm_option_group on
1120 civicrm_option_group.id = civicrm_option_value.option_group_id
1125 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1126 ( civicrm_option_value.name <> 'Inbound Email' AND
1127 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1133 $returnClause = " {$sourceClause} {$caseClause} ";
1135 return array($returnClause, $params);
1139 * send the message to all the contacts and also insert a
1140 * contact activity in each contacts record
1142 * @param array $contactDetails the array of contact details to send the email
1143 * @param string $subject the subject of the message
1144 * @param string $message the message contents
1145 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1146 * @param int $userID use this userID if set
1147 * @param string $from
1148 * @param array $attachments the array of attachments if any
1149 * @param string $cc cc recipient
1150 * @param string $bcc bcc recipient
1151 * @param array $contactIds contact ids
1152 * @param string $additionalDetails the additional information of CC and BCC appended to the activity Details
1154 * @return array ( sent, activityId) if any email is sent and activityId
1158 static function sendEmail(
1166 $attachments = NULL,
1169 $contactIds, // FIXME a param with no default shouldn't be last
1170 $additionalDetails = NULL
1172 // get the contact details of logged in contact, which we set as from email
1173 if ($userID == NULL) {
1174 $session = CRM_Core_Session
::singleton();
1175 $userID = $session->get('userID');
1178 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1180 return array(count($contactDetails), 0, count($contactDetails));
1182 if (!trim($fromDisplayName)) {
1183 $fromDisplayName = $fromEmail;
1187 // token replacement of addressee/email/postal greetings
1188 // get the tokens added in subject and message
1189 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1190 $messageToken = CRM_Utils_Token
::getTokens($text);
1191 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1192 $allTokens = array_merge($messageToken, $subjectToken);
1195 $from = "$fromDisplayName <$fromEmail>";
1198 //create the meta level record first ( email activity )
1199 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1204 // CRM-6265: save both text and HTML parts in details (if present)
1205 if ($html and $text) {
1206 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1209 $details = $html ?
$html : $text;
1210 $details .= $additionalDetails;
1213 $activityParams = array(
1214 'source_contact_id' => $userID,
1215 'activity_type_id' => $activityTypeID,
1216 'activity_date_time' => date('YmdHis'),
1217 'subject' => $subject,
1218 'details' => $details,
1219 // FIXME: check for name Completed and get ID from that lookup
1223 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1224 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1226 // add the attachments to activity params here
1228 // first process them
1229 $activityParams = array_merge($activityParams,
1234 $activity = self
::create($activityParams);
1236 // get the set of attachments from where they are stored
1237 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1240 $returnProperties = array();
1241 if (isset($messageToken['contact'])) {
1242 foreach ($messageToken['contact'] as $key => $value) {
1243 $returnProperties[$value] = 1;
1247 if (isset($subjectToken['contact'])) {
1248 foreach ($subjectToken['contact'] as $key => $value) {
1249 if (!isset($returnProperties[$value])) {
1250 $returnProperties[$value] = 1;
1256 // get token details for contacts, call only if tokens are used
1258 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1259 list($details) = CRM_Utils_Token
::getTokenDetails(
1264 'CRM_Activity_BAO_Activity'
1270 CRM_Utils_Hook
::tokens($tokens);
1271 $categories = array_keys($tokens);
1273 $escapeSmarty = FALSE;
1274 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1275 $smarty = CRM_Core_Smarty
::singleton();
1276 $escapeSmarty = TRUE;
1279 $sent = $notSent = array();
1280 foreach ($contactDetails as $values) {
1281 $contactId = $values['contact_id'];
1282 $emailAddress = $values['email'];
1284 if (!empty($details) && is_array($details["{$contactId}"])) {
1285 // unset email from details since it always returns primary email address
1286 unset($details["{$contactId}"]['email']);
1287 unset($details["{$contactId}"]['email_id']);
1288 $values = array_merge($values, $details["{$contactId}"]);
1291 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1292 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1295 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1296 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1297 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1303 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1304 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1305 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1311 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1312 // also add the contact tokens to the template
1313 $smarty->assign_by_ref('contact', $values);
1315 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1316 $tokenText = $smarty->fetch("string:$tokenText");
1317 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1321 if (self
::sendMessage(
1338 return array($sent, $activity->id
);
1341 static function sendSMS(&$contactDetails,
1343 &$smsParams = array(),
1347 if ($userID == NULL) {
1348 $session = CRM_Core_Session
::singleton();
1349 $userID = $session->get('userID');
1352 $text = &$activityParams['text_message'];
1353 $html = &$activityParams['html_message'];
1356 // token replacement of addressee/email/postal greetings
1357 // get the tokens added in subject and message
1358 $messageToken = CRM_Utils_Token
::getTokens($text);
1359 $messageToken = array_merge($messageToken,
1360 CRM_Utils_Token
::getTokens($html)
1363 //create the meta level record first ( sms activity )
1364 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1369 // CRM-6265: save both text and HTML parts in details (if present)
1370 if ($html and $text) {
1371 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1374 $details = $html ?
$html : $text;
1377 $activitySubject = $activityParams['activity_subject'];
1378 $activityParams = array(
1379 'source_contact_id' => $userID,
1380 'activity_type_id' => $activityTypeID,
1381 'activity_date_time' => date('YmdHis'),
1382 'subject' => $activitySubject,
1383 'details' => $details,
1384 // FIXME: check for name Completed and get ID from that lookup
1388 $activity = self
::create($activityParams);
1389 $activityID = $activity->id
;
1391 $returnProperties = array();
1393 if (isset($messageToken['contact'])) {
1394 foreach ($messageToken['contact'] as $key => $value) {
1395 $returnProperties[$value] = 1;
1401 CRM_Utils_Hook
::tokens($tokens);
1402 $categories = array_keys($tokens);
1404 // get token details for contacts, call only if tokens are used
1406 if (!empty($returnProperties) ||
!empty($tokens)) {
1407 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1411 'CRM_Activity_BAO_Activity'
1416 $escapeSmarty = FALSE;
1418 foreach ($contactDetails as $values) {
1419 $contactId = $values['contact_id'];
1421 if (!empty($details) && is_array($details["{$contactId}"])) {
1422 // unset email from details since it always returns primary email address
1423 unset($details["{$contactId}"]['email']);
1424 unset($details["{$contactId}"]['email_id']);
1425 $values = array_merge($values, $details["{$contactId}"]);
1428 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1429 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1431 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1432 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1434 // Only send if the phone is of type mobile
1435 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1436 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1437 $smsParams['To'] = $values['phone'];
1440 $smsParams['To'] = '';
1443 $sendResult = self
::sendSMSMessage(
1452 if (PEAR
::isError($sendResult)) {
1453 // Collect all of the PEAR_Error objects
1454 $errMsgs[] = $sendResult;
1460 // If at least one message was sent and no errors
1461 // were generated then return a boolean value of TRUE.
1462 // Otherwise, return FALSE (no messages sent) or
1463 // and array of 1 or more PEAR_Error objects.
1465 if ($success > 0 && count($errMsgs) == 0) {
1467 } elseif (count($errMsgs) > 0) {
1471 return array($sent, $activity->id
, $success);
1475 * send the sms message to a specific contact
1477 * @param int $toID the contact id of the recipient
1478 * @param int $activityID the activity ID that tracks the message
1479 * @param array $smsParams the params used for sending sms
1481 * @return mixed true on success or PEAR_Error object
1485 static function sendSMSMessage($toID,
1488 $smsParams = array(),
1493 $toPhoneNumber = "";
1495 if ($smsParams['To']) {
1496 $toPhoneNumber = trim($smsParams['To']);
1499 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1500 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1501 //to get primary mobile ph,if not get a first mobile ph
1502 if (!empty($toPhoneNumbers)) {
1503 $toPhoneNumerDetails = reset($toPhoneNumbers);
1504 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1505 //contact allows to send sms
1510 // make sure both phone are valid
1511 // and that the recipient wants to receive sms
1512 if (empty($toPhoneNumber) or $toDoNotSms) {
1513 return PEAR
::raiseError(
1514 'Recipient phone number is invalid or recipient does not want to receive SMS',
1520 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1521 $recipient = $smsParams['To'];
1522 $smsParams['contact_id'] = $toID;
1523 $smsParams['parent_activity_id'] = $activityID;
1525 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1526 $sendResult = $providerObj->send($recipient, $smsParams, $message, NULL, $userID);
1527 if (PEAR
::isError($sendResult)) {
1531 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1532 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1535 // add activity target record for every sms that is send
1536 $activityTargetParams = array(
1537 'activity_id' => $activityID,
1538 'contact_id' => $toID,
1539 'record_type_id' => $targetID
1541 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1547 * send the message to a specific contact
1549 * @param string $from the name and email of the sender
1550 * @param int $toID the contact id of the recipient
1551 * @param string $subject the subject of the message
1552 * @param string $message the message contents
1553 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1554 * @param int $activityID the activity ID that tracks the message
1556 * @return boolean true if successfull else false.
1560 static function sendMessage($from,
1568 $attachments = NULL,
1572 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1573 if ($emailAddress) {
1574 $toEmail = trim($emailAddress);
1577 // make sure both email addresses are valid
1578 // and that the recipient wants to receive email
1579 if (empty($toEmail) or $toDoNotEmail) {
1582 if (!trim($toDisplayName)) {
1583 $toDisplayName = $toEmail;
1586 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1587 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1588 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1589 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1591 // create the params array
1592 $mailParams = array(
1593 'groupName' => 'Activity Email Sender',
1595 'toName' => $toDisplayName,
1596 'toEmail' => $toEmail,
1597 'subject' => $subject,
1600 'text' => $text_message,
1601 'html' => $html_message,
1602 'attachments' => $attachments,
1605 if (!CRM_Utils_Mail
::send($mailParams)) {
1609 // add activity target record for every mail that is send
1610 $activityTargetParams = array(
1611 'activity_id' => $activityID,
1612 'contact_id' => $toID,
1613 'record_type_id' => $targetID
1615 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1620 * combine all the importable fields from the lower levels object
1622 * The ordering is important, since currently we do not have a weight
1623 * scheme. Adding weight is super important and should be done in the
1624 * next week or so, before this can be called complete.
1628 * @return array array of importable Fields
1632 static function &importableFields($status = FALSE) {
1633 if (!self
::$_importableFields) {
1634 if (!self
::$_importableFields) {
1635 self
::$_importableFields = array();
1638 $fields = array('' => array('title' => ts('- do not import -')));
1641 $fields = array('' => array('title' => ts('- Activity Fields -')));
1644 $tmpFields = CRM_Activity_DAO_Activity
::import();
1645 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1647 // Using new Dedupe rule.
1648 $ruleParams = array(
1649 'contact_type' => 'Individual',
1650 'used' => 'Unsupervised',
1652 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1654 $tmpConatctField = array();
1655 if (is_array($fieldsArray)) {
1656 foreach ($fieldsArray as $value) {
1657 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1662 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1663 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1664 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1667 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1668 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1669 $fields = array_merge($fields, $tmpConatctField);
1670 $fields = array_merge($fields, $tmpFields);
1671 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1672 self
::$_importableFields = $fields;
1674 return self
::$_importableFields;
1678 * To get the Activities of a target contact
1680 * @param $contactId Integer ContactId of the contact whose activities
1683 * @return array array of activity fields
1686 static function getContactActivity($contactId) {
1687 $activities = array();
1688 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1689 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1690 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1691 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1694 // First look for activities where contactId is one of the targets
1696 SELECT activity_id, record_type_id
1697 FROM civicrm_activity_contact
1698 WHERE contact_id = $contactId
1700 $dao = CRM_Core_DAO
::executeQuery($query);
1701 while ($dao->fetch()) {
1702 if ($dao->record_type_id
== $targetID ) {
1703 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1705 else if ($dao->record_type_id
== $assigneeID) {
1706 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1709 // do source stuff here
1710 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1714 $activityIds = array_keys($activities);
1715 if (count($activityIds) < 1) {
1719 $activityIds = implode(',', $activityIds);
1721 SELECT activity.id as activity_id,
1723 subject, location, activity_date_time, details, status_id
1724 FROM civicrm_activity activity
1725 WHERE activity.id IN ($activityIds)";
1727 $dao = CRM_Core_DAO
::executeQuery($query);
1729 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1730 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1732 while ($dao->fetch()) {
1733 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1734 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1735 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1736 $activities[$dao->activity_id
]['location'] = $dao->location
;
1737 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1738 $activities[$dao->activity_id
]['details'] = $dao->details
;
1739 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1740 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1741 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1743 // set to null if not set
1744 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1745 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1752 * Function to add activity for Membership/Event/Contribution
1754 * @param object $activity (reference) particular component object
1755 * @param string $activityType for Membership Signup or Renewal
1761 static function addActivity(&$activity,
1762 $activityType = 'Membership Signup',
1763 $targetContactID = NULL
1765 if ($activity->__table
== 'civicrm_membership') {
1766 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1768 if (!$membershipType) {
1769 $membershipType = ts('Membership');
1772 $subject = "{$membershipType}";
1774 if (!empty($activity->source
) && $activity->source
!= 'null') {
1775 $subject .= " - {$activity->source}";
1778 if ($activity->owner_membership_id
) {
1781 FROM civicrm_contact, civicrm_membership
1782 WHERE civicrm_contact.id = civicrm_membership.contact_id
1783 AND civicrm_membership.id = $activity->owner_membership_id
1785 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1786 $subject .= " (by {$displayName})";
1789 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1790 // CRM-72097 changed from start date to today
1791 $date = date('YmdHis');
1792 $component = 'Membership';
1794 elseif ($activity->__table
== 'civicrm_participant') {
1795 $event = CRM_Event_BAO_Event
::getEvents(1, $activity->event_id
, TRUE, FALSE);
1797 $roles = CRM_Event_PseudoConstant
::participantRole();
1798 $status = CRM_Event_PseudoConstant
::participantStatus();
1800 $subject = $event[$activity->event_id
];
1801 if (!empty($roles[$activity->role_id
])) {
1802 $subject .= ' - ' . $roles[$activity->role_id
];
1804 if (!empty($status[$activity->status_id
])) {
1805 $subject .= ' - ' . $status[$activity->status_id
];
1807 $date = date('YmdHis');
1808 if ($activityType != 'Email') {
1809 $activityType = 'Event Registration';
1811 $component = 'Event';
1813 elseif ($activity->__table
== 'civicrm_contribution') {
1814 //create activity record only for Completed Contributions
1815 if ($activity->contribution_status_id
!= 1) {
1821 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1822 if (!empty($activity->source
) && $activity->source
!= 'null') {
1823 $subject .= " - {$activity->source}";
1825 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1826 $activityType = $component = 'Contribution';
1828 $activityParams = array(
1829 'source_contact_id' => $activity->contact_id
,
1830 'source_record_id' => $activity->id
,
1831 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1835 'subject' => $subject,
1836 'activity_date_time' => $date,
1837 'is_test' => $activity->is_test
,
1838 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1842 'skipRecentView' => TRUE,
1843 'campaign_id' => $activity->campaign_id
,
1846 // create activity with target contacts
1847 $session = CRM_Core_Session
::singleton();
1848 $id = $session->get('userID');
1850 $activityParams['source_contact_id'] = $id;
1851 $activityParams['target_contact_id'][] = $activity->contact_id
;
1855 if ($targetContactID) {
1856 $activityParams['target_contact_id'][] = $targetContactID;
1858 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1859 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1865 * Function to get Parent activity for currently viewed activity
1867 * @param int $activityId current activity id
1869 * @return int $parentId Id of parent activity otherwise false.
1872 static function getParentActivity($activityId) {
1873 static $parentActivities = array();
1875 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1877 if (!array_key_exists($activityId, $parentActivities)) {
1878 $parentActivities[$activityId] = array();
1880 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1885 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1888 return $parentActivities[$activityId];
1892 * Function to get total count of prior revision of currently viewd activity
1894 * @param int $activityId current activity id
1896 * @return int $params count of prior activities otherwise false.
1899 static function getPriorCount($activityID) {
1900 static $priorCounts = array();
1902 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1904 if (!array_key_exists($activityID, $priorCounts)) {
1905 $priorCounts[$activityID] = array();
1906 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1913 SELECT count( id ) AS cnt
1914 FROM civicrm_activity
1915 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1916 AND is_current_revision = 0
1917 AND id < {$activityID}
1919 $params = array(1 => array($originalID, 'Integer'));
1920 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1922 $priorCounts[$activityID] = $count ?
$count : 0;
1925 return $priorCounts[$activityID];
1929 * Function to get all prior activities of currently viewe
1932 * @param int $activityId current activity id
1934 * @return array $result prior activities info.
1937 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1938 static $priorActivities = array();
1940 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1941 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1943 if (!array_key_exists($index, $priorActivities)) {
1944 $priorActivities[$index] = array();
1946 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1952 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1953 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1954 WHERE (ca.id = %1 OR ca.original_id = %1)
1955 AND cl.entity_table = 'civicrm_activity'
1956 AND cl.entity_id = ca.id
1957 AND cl.modified_id = c.id
1959 if ($onlyPriorRevisions) {
1960 $query .= " AND ca.id < {$activityID}";
1962 $query .= " ORDER BY ca.id DESC";
1964 $params = array(1 => array($originalID, 'Integer'));
1965 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1967 while ($dao->fetch()) {
1968 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1969 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1970 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1975 return $priorActivities[$index];
1979 * Function to find the latest revision of a given activity
1981 * @param int $activityId prior activity id
1983 * @return int $params current activity id.
1986 static function getLatestActivityId($activityID) {
1987 static $latestActivityIds = array();
1989 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1991 if (!array_key_exists($activityID, $latestActivityIds)) {
1992 $latestActivityIds[$activityID] = array();
1994 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1999 $activityID = $originalID;
2001 $params = array(1 => array($activityID, 'Integer'));
2002 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2004 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2007 return $latestActivityIds[$activityID];
2011 * Function to create a follow up a given activity
2013 * @activityId int activity id of parent activity
2015 * @param array $activity details
2019 static function createFollowupActivity($activityId, $params) {
2024 $session = CRM_Core_Session
::singleton();
2026 $followupParams = array();
2027 $followupParams['parent_id'] = $activityId;
2028 $followupParams['source_contact_id'] = $session->get('userID');
2029 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2031 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2032 // Get Subject of Follow-up Activiity, CRM-4491
2033 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2034 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2036 //create target contact for followup
2037 if (!empty($params['target_contact_id'])) {
2038 $followupParams['target_contact_id'] = $params['target_contact_id'];
2041 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2042 $params['followup_date_time']
2044 $followupActivity = self
::create($followupParams);
2046 return $followupActivity;
2050 * Function to get Activity specific File according activity type Id.
2052 * @param int $activityTypeId activity id
2054 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2058 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2059 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2061 if ($activityTypes[$activityTypeId]['name']) {
2062 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2068 global $civicrm_root;
2069 $config = CRM_Core_Config
::singleton();
2070 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2071 if (empty($config->customPHPPathDir
)) {
2074 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2079 return $activityTypeFile;
2083 * Function to restore the activity
2085 * @param array $params associated array
2091 public static function restoreActivity(&$params) {
2092 $activity = new CRM_Activity_DAO_Activity();
2093 $activity->copyValues($params);
2095 $activity->is_deleted
= 0;
2096 $result = $activity->save();
2102 * Get the exportable fields for Activities
2104 * @param string $name if it is called by case $name = Case else $name = Activity
2106 * @return array array of exportable Fields
2110 static function &exportableFields($name = 'Activity') {
2111 if (!isset(self
::$_exportableFields[$name])) {
2112 self
::$_exportableFields[$name] = array();
2114 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2115 // my case hence we have defined fields as case_*
2116 if ($name == 'Activity') {
2117 $exportableFields = CRM_Activity_DAO_Activity
::export();
2118 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2119 $exportableFields['source_contact'] = array(
2120 'title' => ts('Source Contact'),
2121 'type' => CRM_Utils_Type
::T_STRING
,
2125 $Activityfields = array(
2126 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2127 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2129 $fields = array_merge($Activityfields, $exportableFields);
2132 //set title to activity fields
2134 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2135 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2136 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2137 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2138 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2139 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2140 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2141 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2142 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2143 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2146 // add custom data for cases
2147 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2150 // add custom data for case activities
2151 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2153 self
::$_exportableFields[$name] = $fields;
2155 return self
::$_exportableFields[$name];
2159 * Get the allowed profile fields for Activities
2161 * @return array array of activity profile Fields
2164 static function getProfileFields() {
2165 $exportableFields = self
::exportableFields('Activity');
2166 $skipFields = array(
2169 'source_contact_id',
2171 'activity_campaign',
2173 'is_current_revision',
2174 'activity_is_deleted',
2176 $config = CRM_Core_Config
::singleton();
2177 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2178 $skipFields[] = 'activity_engagement_level';
2181 foreach ($skipFields as $field) {
2182 if (isset($exportableFields[$field])) {
2183 unset($exportableFields[$field]);
2187 // hack to use 'activity_type_id' instead of 'activity_type'
2188 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2189 unset($exportableFields['activity_status']);
2191 return $exportableFields;
2195 * This function deletes the activity record related to contact record,
2196 * when there are no target and assignee record w/ other contact.
2198 * @param int $contactId contactId
2203 public static function cleanupActivity($contactId) {
2208 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2209 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2211 $transaction = new CRM_Core_Transaction();
2213 // delete activity if there is no record in civicrm_activity_contact
2214 // pointing to any other contact record
2215 $activityContact = new CRM_Activity_DAO_ActivityContact();
2216 $activityContact->contact_id
= $contactId;
2217 $activityContact->record_type_id
= $sourceID;
2218 $activityContact->find();
2220 while ($activityContact->fetch()) {
2221 // delete activity_contact record for the deleted contact
2222 $activityContact->delete();
2224 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2225 $activityContactOther->activity_id
= $activityContact->activity_id
;
2227 // delete activity only if no other contacts connected
2228 if ( ! $activityContactOther->find(TRUE) ) {
2229 $activityParams = array('id' => $activityContact->activity_id
);
2230 $result = self
::deleteActivity($activityParams);
2233 $activityContactOther->free();
2236 $activityContact->free();
2237 $transaction->commit();
2243 * Does user has sufficient permission for view/edit activity record.
2245 * @param int $activityId activity record id.
2246 * @param int $action edit/view
2248 * @return boolean $allow true/false
2251 public static function checkPermission($activityId, $action) {
2254 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2259 $activity = new CRM_Activity_DAO_Activity();
2260 $activity->id
= $activityId;
2261 if (!$activity->find(TRUE)) {
2265 //component related permissions.
2266 $compPermissions = array(
2267 'CiviCase' => array('administer CiviCase',
2268 'access my cases and activities',
2269 'access all cases and activities',
2271 'CiviMail' => array('access CiviMail'),
2272 'CiviEvent' => array('access CiviEvent'),
2273 'CiviGrant' => array('access CiviGrant'),
2274 'CiviPledge' => array('access CiviPledge'),
2275 'CiviMember' => array('access CiviMember'),
2276 'CiviReport' => array('access CiviReport'),
2277 'CiviContribute' => array('access CiviContribute'),
2278 'CiviCampaign' => array('administer CiviCampaign'),
2281 //return early when it is case activity.
2282 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2283 //check for civicase related permission.
2284 if ($isCaseActivity) {
2286 foreach ($compPermissions['CiviCase'] as $per) {
2287 if (CRM_Core_Permission
::check($per)) {
2293 //check for case specific permissions.
2296 if ($action == CRM_Core_Action
::UPDATE
) {
2299 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2301 $activity->activity_type_id
2308 //first check the component permission.
2311 FROM civicrm_option_value val
2312 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2313 WHERE val.value = %2";
2314 $params = array(1 => array('activity_type', 'String'),
2315 2 => array($activity->activity_type_id
, 'Integer'),
2317 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2320 $componentName = CRM_Core_Component
::getComponentName($componentId);
2321 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2323 //here we are interesting in any single permission.
2324 if (is_array($compPermission)) {
2325 foreach ($compPermission as $per) {
2326 if (CRM_Core_Permission
::check($per)) {
2334 //check for this permission related to contact.
2335 $permission = CRM_Core_Permission
::VIEW
;
2336 if ($action == CRM_Core_Action
::UPDATE
) {
2337 $permission = CRM_Core_Permission
::EDIT
;
2340 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2341 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2342 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2343 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2345 //check for source contact.
2346 if (!$componentId ||
$allow) {
2347 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2348 //account for possibility of activity not having a source contact (as it may have been deleted)
2349 if ( $sourceContactId ) {
2350 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2354 //check for target and assignee contacts.
2356 //first check for supper permission.
2357 $supPermission = 'view all contacts';
2358 if ($action == CRM_Core_Action
::UPDATE
) {
2359 $supPermission = 'edit all contacts';
2361 $allow = CRM_Core_Permission
::check($supPermission);
2363 //user might have sufficient permission, through acls.
2366 //get the target contacts.
2367 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2368 foreach ($targetContacts as $cnt => $contactId) {
2369 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2375 //get the assignee contacts.
2377 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2378 foreach ($assigneeContacts as $cnt => $contactId) {
2379 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2392 * This function is a wrapper for ajax activity selector
2394 * @param array $params associated array for params record id.
2396 * @return array $contactActivities associated array of contact activities
2399 public static function getContactActivitySelector(&$params) {
2400 // format the params
2401 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2402 $params['rowCount'] = $params['rp'];
2403 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2404 $params['caseId'] = NULL;
2405 $context = CRM_Utils_Array
::value('context', $params);
2407 // get contact activities
2408 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2411 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2413 // format params and add links
2414 $contactActivities = array();
2416 if (!empty($activities)) {
2417 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2419 // check logged in user for permission
2420 $page = new CRM_Core_Page();
2421 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2422 $permissions = array($page->_permission
);
2423 if (CRM_Core_Permission
::check('delete activities')) {
2424 $permissions[] = CRM_Core_Permission
::DELETE
;
2427 $mask = CRM_Core_Action
::mask($permissions);
2429 foreach ($activities as $activityId => $values) {
2430 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2431 $contactActivities[$activityId]['subject'] = $values['subject'];
2432 if ($params['contact_id'] == $values['source_contact_id']) {
2433 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2435 elseif ($values['source_contact_id']) {
2436 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'],
2437 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2440 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2443 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2444 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2445 'civicrm/mailing/report/event',
2446 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2448 elseif (!empty($values['recipients'])) {
2449 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2451 elseif (!$values['target_contact_name']) {
2452 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2454 elseif (!empty($values['target_contact_name'])) {
2456 $contactActivities[$activityId]['target_contact'] = '';
2457 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2458 if ($tcID && $count < 5) {
2459 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName,
2460 'civicrm/contact/view', "reset=1&cid={$tcID}");
2463 $contactActivities[$activityId]['target_contact'] .= "; ";
2467 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2474 if (empty($values['assignee_contact_name'])) {
2475 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2477 elseif (!empty($values['assignee_contact_name'])) {
2479 $contactActivities[$activityId]['assignee_contact'] = '';
2480 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2481 if ($acID && $count < 5) {
2482 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2485 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2489 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2496 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2497 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2499 // add class to this row if overdue
2500 $contactActivities[$activityId]['class'] = '';
2501 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2502 && CRM_Utils_Array
::value('status_id', $values) == 1
2504 $contactActivities[$activityId]['class'] = 'status-overdue';
2507 $contactActivities[$activityId]['class'] = 'status-ontime';
2511 $contactActivities[$activityId]['links'] = '';
2512 $accessMailingReport = FALSE;
2513 if (!empty($values['mailingId'])) {
2514 $accessMailingReport = TRUE;
2517 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2518 CRM_Utils_Array
::value('activity_type_id', $values),
2519 CRM_Utils_Array
::value('source_record_id', $values),
2520 $accessMailingReport,
2521 CRM_Utils_Array
::value('activity_id', $values)
2524 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2526 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2529 'id' => $values['activity_id'],
2530 'cid' => $params['contact_id'],
2532 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2538 $values['activity_id']
2543 return $contactActivities;
2547 * Used to copy custom fields and attachments from an existing activity to another.
2548 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2550 static function copyExtendedActivityData($params) {
2551 // attach custom data to the new activity
2552 $customParams = $htmlType = array();
2553 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2555 if (!empty($customValues)) {
2556 $fieldIds = implode(', ', array_keys($customValues));
2557 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2558 $result = CRM_Core_DAO
::executeQuery($sql);
2560 while ($result->fetch()) {
2561 $htmlType[] = $result->id
;
2564 foreach ($customValues as $key => $value) {
2565 if ($value !== NULL) { // CRM-10542
2566 if (in_array($key, $htmlType)) {
2567 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2568 $customParams["custom_{$key}_-1"] = array(
2569 'name' => $fileValues[0],
2570 'path' => $fileValues[1],
2574 $customParams["custom_{$key}_-1"] = $value;
2578 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2579 $params['mainActivityId'], 'Activity'
2583 // copy activity attachments ( if any )
2584 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2587 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2588 $activityContact = new CRM_Activity_BAO_ActivityContact();
2589 $activityContact->activity_id
= $activityId;
2590 if ($recordTypeID) {
2591 $activityContact->record_type_id
= $recordTypeID;
2593 if ($activityContact->find(TRUE)) {
2594 return $activityContact->$column;
2599 public static function getSourceContactID($activityId) {
2600 static $sourceID = NULL;
2602 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2603 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2606 return self
::getActivityContact($activityId, $sourceID);
2609 function setApiFilter(&$params) {
2610 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2612 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2613 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2614 $obj = new CRM_Activity_BAO_ActivityContact();
2615 $params['return.target_contact_id'] = 1;
2616 $this->joinAdd($obj, 'LEFT');
2617 $this->selectAdd('civicrm_activity.*');
2618 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");