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);
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={$activity->source_contact_id}&context=activity"
121 $defaults['target_contact_value'] = ts('(recipients)');
124 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
126 if ($sourceContactId &&
127 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
132 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
139 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
141 CRM_Core_DAO
::storeValues($activity, $defaults);
149 * Function to delete the activity
151 * @param array $params associated array
157 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
159 if (CRM_Utils_Array
::value('id', $params) && !is_array($params['id'])) {
160 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
163 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
166 $transaction = new CRM_Core_Transaction();
167 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
168 $sourceRecordIds = implode(',', $params['source_record_id']);
171 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
176 if (!isset($params['id'])) {
177 if (is_array($params['activity_type_id'])) {
178 $activityTypes = implode(',', $params['activity_type_id']);
181 $activityTypes = $params['activity_type_id'];
184 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
185 $dao = CRM_Core_DAO
::executeQuery($query);
188 $activity = new CRM_Activity_DAO_Activity();
189 $activity->copyValues($params);
190 $result = $activity->delete();
193 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
197 $activity = new CRM_Activity_DAO_Activity();
198 $activity->copyValues($params);
200 $activity->is_deleted
= 1;
201 $result = $activity->save();
203 //log activty delete.CRM-4525.
204 $logMsg = 'Case Activity deleted for';
207 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
208 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
209 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
210 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
211 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
212 if ($sourceContactId) {
213 $msgs[] = " source={$sourceContactId}";
216 //get target contacts.
217 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
218 if (!empty($targetContactIds)) {
219 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
221 //get assignee contacts.
222 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
223 if (!empty($assigneeContactIds)) {
224 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
227 $logMsg .= implode(', ', $msgs);
229 self
::logActivityAction($activity, $logMsg);
232 // delete the recently created Activity
234 $activityRecent = array(
235 'id' => $activity->id
,
236 'type' => 'Activity',
238 CRM_Utils_Recent
::del($activityRecent);
241 $transaction->commit();
242 if (isset($activity)) {
244 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
245 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
252 * Delete activity assignment record
254 * @param int $id activity id
259 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
260 $activityContact = new CRM_Activity_BAO_ActivityContact();
261 $activityContact->activity_id
= $activityId;
263 $activityContact->record_type_id
= $recordTypeID;
265 $activityContact->delete();
269 * Function to process the activities
271 * @param object $form form object
272 * @param array $params associated array of the submitted values
273 * @param array $ids array of ids
274 * @param string $activityType activity Type
275 * @param boolean $record true if it is Record Activity
280 public static function create(&$params) {
281 // check required params
282 if (!self
::dataExists($params)) {
283 CRM_Core_Error
::fatal('Not enough data to create activity object,');
286 $activity = new CRM_Activity_DAO_Activity();
288 if (isset($params['id']) && empty($params['id'])) {
289 unset($params['id']);
292 if (!CRM_Utils_Array
::value('status_id', $params) &&
293 !CRM_Utils_Array
::value('activity_status_id', $params) &&
294 !CRM_Utils_Array
::value('id', $params)
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
::priority();
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 (CRM_Utils_Array
::value('id', $params)) {
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_PseudoConstant
::activityContacts('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 CRM_Activity_BAO_ActivityContact
::create($acParams);
365 // check and attach and files as needed
366 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
368 // attempt to save activity assignment
369 $resultAssignment = NULL;
370 if (CRM_Utils_Array
::value('assignee_contact_id', $params)) {
372 $assignmentParams = array('activity_id' => $activityId);
374 if (is_array($params['assignee_contact_id'])) {
375 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
376 // first delete existing assignments if any
377 self
::deleteActivityContact($activityId, $assigneeID);
381 foreach ($params['assignee_contact_id'] as $acID) {
383 $values[] = "( $activityId, $acID, $assigneeID )";
386 while (!empty($values)) {
387 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
388 $str = implode(',', $input);
389 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
390 CRM_Core_DAO
::executeQuery($sql);
394 $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
395 $assignmentParams['record_type_id'] = $assigneeID;
396 if (CRM_Utils_Array
::value('id', $params)) {
397 $assignment = new CRM_Activity_BAO_ActivityAssignment();
398 $assignment->activity_id
= $activityId;
399 $assignment->record_type_id
= $assigneeID;
400 $assignment->find(TRUE);
402 if ($assignment->assignee_contact_id
!= $params['assignee_contact_id']) {
403 $assignmentParams['id'] = $assignment->id
;
404 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
408 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
413 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
414 self
::deleteActivityContact($activityId, $assigneeID);
418 if (is_a($resultAssignment, 'CRM_Core_Error')) {
419 $transaction->rollback();
420 return $resultAssignment;
423 // attempt to save activity targets
424 $resultTarget = NULL;
425 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
427 $targetParams = array('activity_id' => $activityId);
428 $resultTarget = array();
429 if (is_array($params['target_contact_id'])) {
430 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
431 // first delete existing targets if any
432 self
::deleteActivityContact($activityId, $targetID );
436 foreach ($params['target_contact_id'] as $tid) {
438 $values[] = "( $activityId, $tid, $targetID )";
442 while (!empty($values)) {
443 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
444 $str = implode(',', $input);
445 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
446 CRM_Core_DAO
::executeQuery($sql);
450 $targetParams['target_contact_id'] = $params['target_contact_id'];
451 $targetParams['record_type_id'] = $targetID;
452 if (CRM_Utils_Array
::value('id', $params)) {
453 $target = new CRM_Activity_BAO_ActivityContact();
454 $target->activity_id
= $activityId;
455 $target->record_type_id
= $targetID;
458 if ($target->target_contact_id
!= $params['target_contact_id']) {
459 $targetParams['id'] = $target->id
;
460 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
464 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
469 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
470 self
::deleteActivityContact($activityId, $targetID );
474 // write to changelog before transation is committed/rolled
475 // back (and prepare status to display)
476 if (CRM_Utils_Array
::value('id', $params)) {
477 $logMsg = "Activity (id: {$result->id} ) updated with ";
480 $logMsg = "Activity created for ";
484 if (isset($params['source_contact_id'])) {
485 $msgs[] = "source={$params['source_contact_id']}";
488 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
489 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
490 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
491 // take only first target
492 // will be used for recently viewed display
493 $t = array_slice($params['target_contact_id'], 0, 1);
494 $recentContactId = $t[0];
496 elseif (isset($params['target_contact_id'])) {
497 $msgs[] = "target={$params['target_contact_id']}";
498 // will be used for recently viewed display
499 $recentContactId = $params['target_contact_id'];
503 // at worst, take source for recently viewed display
504 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
507 if (isset($params['assignee_contact_id'])) {
508 if (is_array($params['assignee_contact_id'])) {
509 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
512 $msgs[] = "assignee={$params['assignee_contact_id']}";
515 $logMsg .= implode(', ', $msgs);
517 self
::logActivityAction($result, $logMsg);
519 if (CRM_Utils_Array
::value('custom', $params) &&
520 is_array($params['custom'])
522 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
525 $transaction->commit();
526 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
527 $recentOther = array();
528 if (CRM_Utils_Array
::value('case_id', $params)) {
529 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
530 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
531 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
535 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
536 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
537 $url = CRM_Utils_System
::url('civicrm/activity', $q);
538 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
539 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
540 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
544 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
545 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
549 if (CRM_Core_Permission
::check("delete activities")) {
550 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
551 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
556 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
557 if (CRM_Core_Permission
::check('delete activities')) {
558 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
559 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
565 if (!isset($activity->parent_id
)) {
566 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
567 // add the recently created Activity
568 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
569 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
572 if (isset($activitySubject)) {
573 $title = $activitySubject . ' - ';
576 $title = $title . $recentContactDisplay;
577 if (CRM_Utils_Array
::value($activity->activity_type_id
, $activityTypes)) {
578 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
581 CRM_Utils_Recent
::add($title,
586 $recentContactDisplay,
592 // reset the group contact cache since smart groups might be affected due to this
593 CRM_Contact_BAO_GroupContactCache
::remove();
595 if (CRM_Utils_Array
::value('id', $params)) {
596 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
599 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
602 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
604 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
605 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
607 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
609 'activity_id' => $activity->id
,
610 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
612 if ($caseParams['case_id']) {
613 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
616 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
623 public static function logActivityAction($activity, $logMessage = NULL) {
624 $session = CRM_Core_Session
::singleton();
625 $id = $session->get('userID');
627 $id = $activity->source_contact_id
;
630 'entity_table' => 'civicrm_activity',
631 'entity_id' => $activity->id
,
632 'modified_id' => $id,
633 'modified_date' => date('YmdHis'),
634 'data' => $logMessage,
636 CRM_Core_BAO_Log
::add($logParams);
641 * function to get the list Actvities
643 * @param array $input array of parameters
645 * - contact_id int contact_id whose activties we want to retrieve
646 * - offset int which row to start from ?
647 * - rowCount int how many rows to fetch
648 * - sort object|array object or array describing sort order for sql query.
649 * - admin boolean if contact is admin
650 * - caseId int case ID
651 * - context string page on which selector is build
652 * - activity_type_id int|string the activitiy types we want to restrict by
654 * @return array (reference) $values the relevant data object values of open activitie
659 static function &getActivities($input) {
660 //step 1: Get the basic activity data
661 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
666 $config = CRM_Core_Config
::singleton();
668 $randomNum = md5(uniqid());
669 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
671 $tableFields = array(
672 'activity_id' => 'int unsigned',
673 'activity_date_time' => 'datetime',
674 'status_id' => 'int unsigned',
675 'subject' => 'varchar(255)',
676 'source_record_id' => 'int unsigned',
677 'activity_type_id' => 'int unsigned',
678 'activity_type' => 'varchar(128)',
679 'case_id' => 'int unsigned',
680 'case_subject' => 'varchar(255)',
681 'campaign_id' => 'int unsigned',
684 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
685 $insertValueSQL = array();
686 foreach ($tableFields as $name => $desc) {
687 $sql .= "$name $desc,\n";
688 $insertValueSQL[] = $name;
692 PRIMARY KEY ( activity_id )
693 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
696 CRM_Core_DAO
::executeQuery($sql);
698 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
700 $order = $limit = $groupBy = '';
702 if (!empty($input['sort'])) {
703 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
704 $orderBy = $input['sort']->orderBy();
705 if (!empty($orderBy)) {
706 $order = " ORDER BY $orderBy";
709 elseif (trim($input['sort'])) {
710 $order = " ORDER BY {$input['sort']}";
715 $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 ";
718 if (!empty($input['rowCount']) &&
719 $input['rowCount'] > 0
721 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
724 $input['count'] = FALSE;
725 list($sqlClause, $params) = self
::getActivitySQLClause($input);
727 $query = "{$insertSQL}
728 SELECT DISTINCT tbl.* from ( {$sqlClause} )
731 //filter case activities - CRM-5761
732 $components = self
::activityComponents();
733 if (!in_array('CiviCase', $components)) {
735 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
736 WHERE civicrm_case_activity.id IS NULL";
739 $query = $query . $groupBy . $order . $limit;
741 $dao = CRM_Core_DAO
::executeQuery($query, $params);
743 $notbulkActivityClause = '';
744 if ($bulkActivityTypeID) {
745 $notbulkActivityClause = " AND {$activityTempTable}.activity_type_id <> {$bulkActivityTypeID} ";
748 // step 2: Get target and assignee contacts for above activities
749 // create temp table for target contacts
750 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
751 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
752 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16), contact_name varchar(255) )
753 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
755 CRM_Core_DAO
::executeQuery($query);
757 // note that we ignore bulk email for targets, since we don't show it in selector
759 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name )
760 SELECT ac.activity_id,
764 FROM civicrm_activity_contact ac
765 INNER JOIN {$activityTempTable} ON ( ac.activity_id = {$activityTempTable}.activity_id
766 INNER JOIN civicrm_contact c ON c.id = at.contact_id
767 WHERE c.is_deleted = 0
768 {$notbulkActivityClause} )
770 CRM_Core_DAO
::executeQuery($query);
772 CRM_Core_DAO
::executeQuery($query);
774 // step 3: Combine all temp tables to get final query for activity selector
776 SELECT {$activityTempTable}.*,
777 {$activityContactTempTable}.contact_id,
778 {$activityContactTempTable}.record_type_id,
779 {$activityContactTempTable}.contact_name,
780 FROM {$activityTempTable}
781 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
785 $dao = CRM_Core_DAO
::executeQuery($query);
787 //CRM-3553, need to check user has access to target groups.
788 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
790 (CRM_Core_Permission
::check('access CiviMail')) ||
791 (CRM_Mailing_Info
::workflowEnabled() &&
792 CRM_Core_Permission
::check('create mailings'))
796 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
799 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
800 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
801 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
802 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
805 while ($dao->fetch()) {
806 $activityID = $dao->activity_id
;
807 $values[$activityID]['activity_id'] = $dao->activity_id
;
808 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
809 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
810 $values[$activityID]['activity_type'] = $dao->activity_type
;
811 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
812 $values[$activityID]['status_id'] = $dao->status_id
;
813 $values[$activityID]['subject'] = $dao->subject
;
814 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
816 if ($dao->campaign_id
) {
817 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
820 if (!CRM_Utils_Array
::value('assignee_contact_name', $values[$activityID])) {
821 $values[$activityID]['assignee_contact_name'] = array();
824 if (!CRM_Utils_Array
::value('target_contact_name', $values[$activityID])) {
825 $values[$activityID]['target_contact_name'] = array();
828 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
829 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
830 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
833 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
834 // build array of target / assignee names
835 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
836 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
838 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
839 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
842 // case related fields
843 $values[$activityID]['case_id'] = $dao->case_id
;
844 $values[$activityID]['case_subject'] = $dao->case_subject
;
847 $values[$activityID]['recipients'] = ts('(recipients)');
848 $values[$activityID]['mailingId'] = '';
851 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
853 $values[$activityID]['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
854 "mid={$dao->source_record_id}&reset=1&cid={$dao->source_contact_id}&context=activitySelector"
860 // add info on whether the related contacts are deleted (CRM-5673)
861 // FIXME: ideally this should be tied to ACLs
863 // grab all the related contact ids
865 foreach ($values as $value) {
866 $cids[] = $value['source_contact_id'];
868 $cids = array_filter(array_unique($cids));
870 // see which of the cids are of deleted contacts
872 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
873 $dao = CRM_Core_DAO
::executeQuery($sql);
875 while ($dao->fetch()) {
879 // hide the deleted contacts
880 foreach ($values as & $value) {
881 if (in_array($value['source_contact_id'], $dels)) {
882 unset($value['source_contact_id'], $value['source_contact_name']);
891 * Get the component id and name those are enabled and logged in
892 * user has permission. To decide whether we are going to include
893 * component related activities w/ core activity retrieve process.
895 * return an array of component id and name.
898 static function activityComponents() {
899 $components = array();
900 $compInfo = CRM_Core_Component
::getEnabledComponents();
901 foreach ($compInfo as $compObj) {
902 if (CRM_Utils_Array
::value('showActivitiesInCore', $compObj->info
)) {
903 if ($compObj->info
['name'] == 'CiviCampaign') {
904 $componentPermission = "administer {$compObj->name}";
907 $componentPermission = "access {$compObj->name}";
909 if ($compObj->info
['name'] == 'CiviCase') {
910 if (CRM_Case_BAO_Case
::accessCiviCase()) {
911 $components[$compObj->componentID
] = $compObj->info
['name'];
914 elseif (CRM_Core_Permission
::check($componentPermission)) {
915 $components[$compObj->componentID
] = $compObj->info
['name'];
924 * function to get the activity Count
926 * @param array $input array of parameters
928 * - contact_id int contact_id whose activties we want to retrieve
929 * - admin boolean if contact is admin
930 * - caseId int case ID
931 * - context string page on which selector is build
932 * - activity_type_id int|string the activitiy types we want to restrict by
934 * @return int count of activities
939 static function &getActivitiesCount($input) {
940 $input['count'] = TRUE;
941 list($sqlClause, $params) = self
::getActivitySQLClause($input);
943 //filter case activities - CRM-5761
944 $components = self
::activityComponents();
945 if (!in_array('CiviCase', $components)) {
947 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
948 FROM ( {$sqlClause} ) as tbl
949 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
950 WHERE civicrm_case_activity.id IS NULL";
953 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
956 return CRM_Core_DAO
::singleValueQuery($query, $params);
960 * function to get the activity sql clause to pick activities
962 * @param array $input array of parameters
964 * - contact_id int contact_id whose activties we want to retrieve
965 * - admin boolean if contact is admin
966 * - caseId int case ID
967 * - context string page on which selector is build
968 * - count boolean are we interested in the count clause only?
969 * - activity_type_id int|string the activitiy types we want to restrict by
971 * @return int count of activities
976 static function getActivitySQLClause($input) {
978 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
980 $config = CRM_Core_Config
::singleton();
981 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
982 $sourceWhere = ' ac.contact_id = %1 ';
983 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
985 $params = array(1 => array($input['contact_id'], 'Integer'));
988 $commonClauses = array(
989 "civicrm_option_group.name = 'activity_type'",
990 "civicrm_activity.is_deleted = 0",
991 "civicrm_activity.is_current_revision = 1",
992 "civicrm_activity.is_test = 0",
995 if ($input['context'] != 'activity') {
996 $commonClauses[] = "civicrm_activity.status_id = 1";
999 //Filter on component IDs.
1000 $components = self
::activityComponents();
1001 if (!empty($components)) {
1002 $componentsIn = implode(',', array_keys($components));
1003 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1006 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1009 // activity type ID clause
1010 if (!empty($input['activity_type_id'])) {
1011 if (is_array($input['activity_type_id'])) {
1012 foreach ($input['activity_type_id'] as $idx => $value) {
1013 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1015 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1018 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1019 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1023 // exclude by activity type clause
1024 if (!empty($input['activity_type_exclude_id'])) {
1025 if (is_array($input['activity_type_exclude_id'])) {
1026 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1027 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1029 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1032 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1033 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1037 $commonClause = implode(' AND ', $commonClauses);
1039 $includeCaseActivities = FALSE;
1040 if (in_array('CiviCase', $components)) {
1041 $includeCaseActivities = TRUE;
1045 // build main activity table select clause
1048 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1049 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1052 if (!$input['count']) {
1054 civicrm_activity.activity_date_time,
1055 civicrm_activity.status_id,
1056 civicrm_activity.subject,
1057 civicrm_activity.source_record_id,
1058 sourceContact.sort_name as source_contact_name,
1059 civicrm_option_value.value as activity_type_id,
1060 civicrm_option_value.label as activity_type,
1061 null as case_id, null as case_subject,
1062 civicrm_activity.campaign_id as campaign_id,
1063 activityContact.contact_id as contact_id,
1064 activityContact.record_type_id as record_type_id,
1065 contact.sort_name as sort_name
1071 SELECT civicrm_activity.id as activity_id
1073 from civicrm_activity
1074 left join civicrm_option_value on
1075 civicrm_activity.activity_type_id = civicrm_option_value.value
1076 left join civicrm_option_group on
1077 civicrm_option_group.id = civicrm_option_value.option_group_id
1084 // Build case clause
1085 // or else exclude Inbound Emails that have been filed on a case.
1088 if ($includeCaseActivities) {
1090 if (!$input['count']) {
1092 civicrm_activity.activity_date_time,
1093 civicrm_activity.status_id,
1094 civicrm_activity.subject,
1095 civicrm_activity.source_contact_id,
1096 civicrm_activity.source_record_id,
1097 sourceContact.sort_name as source_contact_name,
1098 civicrm_option_value.value as activity_type_id,
1099 civicrm_option_value.label as activity_type,
1100 null as case_id, null as case_subject,
1101 civicrm_activity.campaign_id as campaign_id';
1107 SELECT civicrm_activity.id as activity_id
1109 from civicrm_activity
1110 inner join civicrm_case_activity on
1111 civicrm_case_activity.activity_id = civicrm_activity.id
1112 inner join civicrm_case on
1113 civicrm_case_activity.case_id = civicrm_case.id
1114 inner join civicrm_case_contact on
1115 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1116 left join civicrm_option_value on
1117 civicrm_activity.activity_type_id = civicrm_option_value.value
1118 left join civicrm_option_group on
1119 civicrm_option_group.id = civicrm_option_value.option_group_id
1124 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1125 ( civicrm_option_value.name <> 'Inbound Email' AND
1126 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1132 $returnClause = " {$sourceClause} {$caseClause} ";
1134 return array($returnClause, $params);
1138 * send the message to all the contacts and also insert a
1139 * contact activity in each contacts record
1141 * @param array $contactDetails the array of contact details to send the email
1142 * @param string $subject the subject of the message
1143 * @param string $message the message contents
1144 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1145 * @param int $userID use this userID if set
1146 * @param string $from
1147 * @param array $attachments the array of attachments if any
1148 * @param string $cc cc recepient
1149 * @param string $bcc bcc recepient
1150 * @param array $contactIds contact ids
1152 * @return array ( sent, activityId) if any email is sent and activityId
1156 static function sendEmail(
1164 $attachments = NULL,
1167 $contactIds // FIXME a param with no default shouldn't be last
1169 // get the contact details of logged in contact, which we set as from email
1170 if ($userID == NULL) {
1171 $session = CRM_Core_Session
::singleton();
1172 $userID = $session->get('userID');
1175 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1177 return array(count($contactDetails), 0, count($contactDetails));
1179 if (!trim($fromDisplayName)) {
1180 $fromDisplayName = $fromEmail;
1184 // token replacement of addressee/email/postal greetings
1185 // get the tokens added in subject and message
1186 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1187 $messageToken = CRM_Utils_Token
::getTokens($text);
1188 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1191 $from = "$fromDisplayName <$fromEmail>";
1194 //create the meta level record first ( email activity )
1195 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1200 // CRM-6265: save both text and HTML parts in details (if present)
1201 if ($html and $text) {
1202 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1205 $details = $html ?
$html : $text;
1208 $activityParams = array(
1209 'source_contact_id' => $userID,
1210 'activity_type_id' => $activityTypeID,
1211 'activity_date_time' => date('YmdHis'),
1212 'subject' => $subject,
1213 'details' => $details,
1214 // FIXME: check for name Completed and get ID from that lookup
1218 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1219 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1221 // add the attachments to activity params here
1223 // first process them
1224 $activityParams = array_merge($activityParams,
1229 $activity = self
::create($activityParams);
1231 // get the set of attachments from where they are stored
1232 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1235 $returnProperties = array();
1236 if (isset($messageToken['contact'])) {
1237 foreach ($messageToken['contact'] as $key => $value) {
1238 $returnProperties[$value] = 1;
1242 if (isset($subjectToken['contact'])) {
1243 foreach ($subjectToken['contact'] as $key => $value) {
1244 if (!isset($returnProperties[$value])) {
1245 $returnProperties[$value] = 1;
1251 // get token details for contacts, call only if tokens are used
1253 if (!empty($returnProperties)) {
1254 list($details) = CRM_Utils_Token
::getTokenDetails(
1259 'CRM_Activity_BAO_Activity'
1265 CRM_Utils_Hook
::tokens($tokens);
1266 $categories = array_keys($tokens);
1268 $escapeSmarty = FALSE;
1269 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1270 $smarty = CRM_Core_Smarty
::singleton();
1271 $escapeSmarty = TRUE;
1274 $sent = $notSent = array();
1275 foreach ($contactDetails as $values) {
1276 $contactId = $values['contact_id'];
1277 $emailAddress = $values['email'];
1279 if (!empty($details) && is_array($details["{$contactId}"])) {
1280 // unset email from details since it always returns primary email address
1281 unset($details["{$contactId}"]['email']);
1282 unset($details["{$contactId}"]['email_id']);
1283 $values = array_merge($values, $details["{$contactId}"]);
1286 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1287 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1290 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1291 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1292 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1298 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1299 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1300 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1306 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1307 // also add the contact tokens to the template
1308 $smarty->assign_by_ref('contact', $values);
1310 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1311 $tokenText = $smarty->fetch("string:$tokenText");
1312 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1316 if (self
::sendMessage(
1333 return array($sent, $activity->id
);
1336 static function sendSMS(&$contactDetails,
1338 &$smsParams = array(),
1342 if ($userID == NULL) {
1343 $session = CRM_Core_Session
::singleton();
1344 $userID = $session->get('userID');
1347 $text = &$activityParams['text_message'];
1348 $html = &$activityParams['html_message'];
1351 // token replacement of addressee/email/postal greetings
1352 // get the tokens added in subject and message
1353 $messageToken = CRM_Utils_Token
::getTokens($text);
1354 $messageToken = array_merge($messageToken,
1355 CRM_Utils_Token
::getTokens($html)
1358 //create the meta level record first ( sms activity )
1359 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1364 // CRM-6265: save both text and HTML parts in details (if present)
1365 if ($html and $text) {
1366 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1369 $details = $html ?
$html : $text;
1372 $activitySubject = $activityParams['activity_subject'];
1373 $activityParams = array(
1374 'source_contact_id' => $userID,
1375 'activity_type_id' => $activityTypeID,
1376 'activity_date_time' => date('YmdHis'),
1377 'subject' => $activitySubject,
1378 'details' => $details,
1379 // FIXME: check for name Completed and get ID from that lookup
1383 $activity = self
::create($activityParams);
1384 $activityID = $activity->id
;
1386 $returnProperties = array();
1388 if (isset($messageToken['contact'])) {
1389 foreach ($messageToken['contact'] as $key => $value) {
1390 $returnProperties[$value] = 1;
1396 CRM_Utils_Hook
::tokens($tokens);
1397 $categories = array_keys($tokens);
1399 // get token details for contacts, call only if tokens are used
1401 if (!empty($returnProperties) ||
!empty($tokens)) {
1402 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1406 'CRM_Activity_BAO_Activity'
1410 $escapeSmarty = $sent = FALSE;
1411 foreach ($contactDetails as $values) {
1412 $contactId = $values['contact_id'];
1414 if (!empty($details) && is_array($details["{$contactId}"])) {
1415 // unset email from details since it always returns primary email address
1416 unset($details["{$contactId}"]['email']);
1417 unset($details["{$contactId}"]['email_id']);
1418 $values = array_merge($values, $details["{$contactId}"]);
1421 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1422 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1424 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1425 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1427 // Only send if the phone is of type mobile
1428 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1429 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1430 $smsParams['To'] = $values['phone'];
1433 $smsParams['To'] = '';
1436 if (self
::sendSMSMessage(
1443 // even a single successful delivery should set this falg to true
1448 return array($sent, $activity->id
);
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
]['source_contact_id'] = $dao->source_contact_id
;
1705 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1706 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1707 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1708 $activities[$dao->activity_id
]['location'] = $dao->location
;
1709 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1710 $activities[$dao->activity_id
]['details'] = $dao->details
;
1711 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1712 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1713 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1719 * Function to add activity for Membership/Event/Contribution
1721 * @param object $activity (reference) perticular component object
1722 * @param string $activityType for Membership Signup or Renewal
1728 static function addActivity(&$activity,
1729 $activityType = 'Membership Signup',
1730 $targetContactID = NULL
1732 if ($activity->__table
== 'civicrm_membership') {
1733 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1735 if (!$membershipType) {
1736 $membershipType = ts('Membership');
1739 $subject = "{$membershipType}";
1741 if (!empty($activity->source
) && $activity->source
!= 'null') {
1742 $subject .= " - {$activity->source}";
1745 if ($activity->owner_membership_id
) {
1748 FROM civicrm_contact, civicrm_membership
1749 WHERE civicrm_contact.id = civicrm_membership.contact_id
1750 AND civicrm_membership.id = $activity->owner_membership_id
1752 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1753 $subject .= " (by {$displayName})";
1756 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1757 // CRM-72097 changed from start date to today
1758 $date = date('YmdHis');
1759 $component = 'Membership';
1761 elseif ($activity->__table
== 'civicrm_participant') {
1762 $event = CRM_Event_BAO_Event
::getEvents(TRUE, $activity->event_id
, TRUE, FALSE);
1764 $roles = CRM_Event_PseudoConstant
::participantRole();
1765 $status = CRM_Event_PseudoConstant
::participantStatus();
1767 $subject = $event[$activity->event_id
];
1768 if (CRM_Utils_Array
::value($activity->role_id
, $roles)) {
1769 $subject .= ' - ' . $roles[$activity->role_id
];
1771 if (CRM_Utils_Array
::value($activity->status_id
, $status)) {
1772 $subject .= ' - ' . $status[$activity->status_id
];
1774 $date = date('YmdHis');
1775 if ($activityType != 'Email') {
1776 $activityType = 'Event Registration';
1778 $component = 'Event';
1780 elseif ($activity->__table
== 'civicrm_contribution') {
1781 //create activity record only for Completed Contributions
1782 if ($activity->contribution_status_id
!= 1) {
1788 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1789 if (!empty($activity->source
) && $activity->source
!= 'null') {
1790 $subject .= " - {$activity->source}";
1792 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1793 $activityType = $component = 'Contribution';
1795 $activityParams = array(
1796 'source_contact_id' => $activity->contact_id
,
1797 'source_record_id' => $activity->id
,
1798 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1802 'subject' => $subject,
1803 'activity_date_time' => $date,
1804 'is_test' => $activity->is_test
,
1805 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1809 'skipRecentView' => TRUE,
1810 'campaign_id' => $activity->campaign_id
,
1813 // create activity with target contacts
1814 $session = CRM_Core_Session
::singleton();
1815 $id = $session->get('userID');
1817 $activityParams['source_contact_id'] = $id;
1818 $activityParams['target_contact_id'][] = $activity->contact_id
;
1822 if ($targetContactID) {
1823 $activityParams['target_contact_id'][] = $targetContactID;
1825 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1826 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1832 * Function to get Parent activity for currently viewd activity
1834 * @param int $activityId current activity id
1836 * @return int $parentId Id of parent acyivity otherwise false.
1839 static function getParentActivity($activityId) {
1840 static $parentActivities = array();
1842 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1844 if (!array_key_exists($activityId, $parentActivities)) {
1845 $parentActivities[$activityId] = array();
1847 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1852 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1855 return $parentActivities[$activityId];
1859 * Function to get total count of prior revision of currently viewd activity
1861 * @param int $activityId current activity id
1863 * @return int $params count of prior acyivities otherwise false.
1866 static function getPriorCount($activityID) {
1867 static $priorCounts = array();
1869 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1871 if (!array_key_exists($activityID, $priorCounts)) {
1872 $priorCounts[$activityID] = array();
1873 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1880 SELECT count( id ) AS cnt
1881 FROM civicrm_activity
1882 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1883 AND is_current_revision = 0
1884 AND id < {$activityID}
1886 $params = array(1 => array($originalID, 'Integer'));
1887 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1889 $priorCounts[$activityID] = $count ?
$count : 0;
1892 return $priorCounts[$activityID];
1896 * Function to get all prior activities of currently viewd activity
1898 * @param int $activityId current activity id
1900 * @return array $result prior acyivities info.
1903 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1904 static $priorActivities = array();
1906 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1907 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1909 if (!array_key_exists($index, $priorActivities)) {
1910 $priorActivities[$index] = array();
1912 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1918 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1919 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1920 WHERE (ca.id = %1 OR ca.original_id = %1)
1921 AND cl.entity_table = 'civicrm_activity'
1922 AND cl.entity_id = ca.id
1923 AND cl.modified_id = c.id
1925 if ($onlyPriorRevisions) {
1926 $query .= " AND ca.id < {$activityID}";
1928 $query .= " ORDER BY ca.id DESC";
1930 $params = array(1 => array($originalID, 'Integer'));
1931 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1933 while ($dao->fetch()) {
1934 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1935 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1936 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1937 $priorActivities[$index][$dao->activityID
]['link'] = 'javascript:viewActivity( $dao->activityID );';
1942 return $priorActivities[$index];
1946 * Function to find the latest revision of a given activity
1948 * @param int $activityId prior activity id
1950 * @return int $params current activity id.
1953 static function getLatestActivityId($activityID) {
1954 static $latestActivityIds = array();
1956 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1958 if (!array_key_exists($activityID, $latestActivityIds)) {
1959 $latestActivityIds[$activityID] = array();
1961 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1966 $activityID = $originalID;
1968 $params = array(1 => array($activityID, 'Integer'));
1969 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1971 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
1974 return $latestActivityIds[$activityID];
1978 * Function to create a follow up a given activity
1980 * @activityId int activity id of parent activity
1982 * @param array $activity details
1986 static function createFollowupActivity($activityId, $params) {
1991 $session = CRM_Core_Session
::singleton();
1993 $followupParams = array();
1994 $followupParams['parent_id'] = $activityId;
1995 $followupParams['source_contact_id'] = $session->get('userID');
1996 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
1998 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1999 // Get Subject of Follow-up Activiity, CRM-4491
2000 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2002 //create target contact for followup
2003 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2004 $followupParams['target_contact_id'] = $params['target_contact_id'];
2007 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2008 $params['followup_date_time']
2010 $followupActivity = self
::create($followupParams);
2012 return $followupActivity;
2016 * Function to get Activity specific File according activity type Id.
2018 * @param int $activityTypeId activity id
2020 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2024 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2025 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2027 if ($activityTypes[$activityTypeId]['name']) {
2028 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2034 global $civicrm_root;
2035 $config = CRM_Core_Config
::singleton();
2036 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2037 if (empty($config->customPHPPathDir
)) {
2040 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2045 return $activityTypeFile;
2049 * Function to restore the activity
2051 * @param array $params associated array
2057 public static function restoreActivity(&$params) {
2058 $activity = new CRM_Activity_DAO_Activity();
2059 $activity->copyValues($params);
2061 $activity->is_deleted
= 0;
2062 $result = $activity->save();
2068 * Get the exportable fields for Activities
2070 * @param string $name if it is called by case $name = Case else $name = Activity
2072 * @return array array of exportable Fields
2076 static function &exportableFields($name = 'Activity') {
2077 if (!isset(self
::$_exportableFields[$name])) {
2078 self
::$_exportableFields[$name] = array();
2080 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2081 // my case hence we have defined fields as case_*
2082 if ($name == 'Activity') {
2083 $exportableFields = CRM_Activity_DAO_Activity
::export();
2084 if (isset($exportableFields['activity_campaign_id'])) {
2085 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2087 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2088 $exportableFields['source_contact'] = array(
2089 'title' => ts('Source Contact'),
2090 'type' => CRM_Utils_Type
::T_STRING
,
2094 $Activityfields = array(
2095 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2096 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2098 $fields = array_merge($Activityfields, $exportableFields);
2101 //set title to activity fields
2103 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2104 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2105 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2106 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2107 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2108 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2109 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2110 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2111 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2112 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2115 // add custom data for cases
2116 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2119 // add custom data for case activities
2120 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2122 self
::$_exportableFields[$name] = $fields;
2124 return self
::$_exportableFields[$name];
2128 * Get the allowed profile fields for Activities
2130 * @return array array of activity profile Fields
2133 static function getProfileFields() {
2134 $exportableFields = self
::exportableFields('Activity');
2135 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2136 $config = CRM_Core_Config
::singleton();
2137 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2138 $skipFields[] = 'activity_engagement_level';
2141 foreach ($skipFields as $field) {
2142 if (isset($exportableFields[$field])) {
2143 unset($exportableFields[$field]);
2147 // hack to use 'activity_type_id' instead of 'activity_type'
2148 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2149 unset($exportableFields['activity_status']);
2151 return $exportableFields;
2155 * This function delete activity record related to contact record,
2156 * when there are no target and assignee record w/ other contact.
2158 * @param int $contactId contactId
2163 public static function cleanupActivity($contactId) {
2169 $transaction = new CRM_Core_Transaction();
2171 // delete activity if there is no record in
2172 // civicrm_activity_contact
2173 // pointing to any other contact record.
2174 $activity = new CRM_Activity_DAO_Activity();
2175 $activity->source_contact_id
= $contactId;
2178 while ($activity->fetch()) {
2183 FROM civicrm_activity_contact
2184 WHERE activity_id = %1
2185 AND contact_id <> %2
2188 1 => array($activity->id
, 'Integer'),
2189 2 => array($contactId, 'Integer')
2192 // finally delete activity.
2193 if (CRM_Core_DAO
::singleValueQuery($sql)) {
2194 $activityParams = array('id' => $activity->id
);
2195 $result = self
::deleteActivity($activityParams);
2200 $transaction->commit();
2206 * Does user has sufficient permission for view/edit activity record.
2208 * @param int $activityId activity record id.
2209 * @param int $action edit/view
2211 * @return boolean $allow true/false
2214 public static function checkPermission($activityId, $action) {
2217 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2222 $activity = new CRM_Activity_DAO_Activity();
2223 $activity->id
= $activityId;
2224 if (!$activity->find(TRUE)) {
2228 //component related permissions.
2229 $compPermissions = array(
2230 'CiviCase' => array('administer CiviCase',
2231 'access my cases and activities',
2232 'access all cases and activities',
2234 'CiviMail' => array('access CiviMail'),
2235 'CiviEvent' => array('access CiviEvent'),
2236 'CiviGrant' => array('access CiviGrant'),
2237 'CiviPledge' => array('access CiviPledge'),
2238 'CiviMember' => array('access CiviMember'),
2239 'CiviReport' => array('access CiviReport'),
2240 'CiviContribute' => array('access CiviContribute'),
2241 'CiviCampaign' => array('administer CiviCampaign'),
2244 //return early when it is case activity.
2245 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2246 //check for civicase related permission.
2247 if ($isCaseActivity) {
2249 foreach ($compPermissions['CiviCase'] as $per) {
2250 if (CRM_Core_Permission
::check($per)) {
2256 //check for case specific permissions.
2259 if ($action == CRM_Core_Action
::UPDATE
) {
2262 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2264 $activity->activity_type_id
2271 //first check the component permission.
2274 FROM civicrm_option_value val
2275 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2276 WHERE val.value = %2";
2277 $params = array(1 => array('activity_type', 'String'),
2278 2 => array($activity->activity_type_id
, 'Integer'),
2280 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2283 $componentName = CRM_Core_Component
::getComponentName($componentId);
2284 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2286 //here we are interesting in any single permission.
2287 if (is_array($compPermission)) {
2288 foreach ($compPermission as $per) {
2289 if (CRM_Core_Permission
::check($per)) {
2297 //check for this permission related to contact.
2298 $permission = CRM_Core_Permission
::VIEW
;
2299 if ($action == CRM_Core_Action
::UPDATE
) {
2300 $permission = CRM_Core_Permission
::EDIT
;
2303 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
2304 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2305 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2306 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2308 //check for source contact.
2309 if (!$componentId ||
$allow) {
2310 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2311 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2314 //check for target and assignee contacts.
2316 //first check for supper permission.
2317 $supPermission = 'view all contacts';
2318 if ($action == CRM_Core_Action
::UPDATE
) {
2319 $supPermission = 'edit all contacts';
2321 $allow = CRM_Core_Permission
::check($supPermission);
2323 //user might have sufficient permission, through acls.
2326 //get the target contacts.
2327 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2328 foreach ($targetContacts as $cnt => $contactId) {
2329 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2335 //get the assignee contacts.
2337 $assigneeContacts = CRM_Activity_BAO_Contact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2338 foreach ($assigneeContacts as $cnt => $contactId) {
2339 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2352 * This function is a wrapper for ajax activity selector
2354 * @param array $params associated array for params record id.
2356 * @return array $contactActivities associated array of contact activities
2359 public static function getContactActivitySelector(&$params) {
2360 // format the params
2361 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2362 $params['rowCount'] = $params['rp'];
2363 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2364 $params['caseId'] = NULL;
2365 $context = CRM_Utils_Array
::value('context', $params);
2367 // get contact activities
2368 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2371 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2373 // format params and add links
2374 $contactActivities = array();
2376 if (!empty($activities)) {
2377 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2379 // check logged in user for permission
2380 $page = new CRM_Core_Page();
2381 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2382 $permissions = array($page->_permission
);
2383 if (CRM_Core_Permission
::check('delete activities')) {
2384 $permissions[] = CRM_Core_Permission
::DELETE
;
2387 $mask = CRM_Core_Action
::mask($permissions);
2389 foreach ($activities as $activityId => $values) {
2390 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2391 $contactActivities[$activityId]['subject'] = $values['subject'];
2392 if ($params['contact_id'] == $values['source_contact_id']) {
2393 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2395 elseif ($values['source_contact_id']) {
2396 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2399 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2402 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2403 $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");
2405 elseif (CRM_Utils_Array
::value('recipients', $values)) {
2406 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2408 elseif (!$values['target_contact_name']) {
2409 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2411 elseif (!empty($values['target_contact_name'])) {
2413 $contactActivities[$activityId]['target_contact'] = '';
2414 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2415 if ($tcID && $count < 5) {
2416 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2419 $contactActivities[$activityId]['target_contact'] .= "; ";
2423 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2430 if (empty($values['assignee_contact_name'])) {
2431 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2433 elseif (!empty($values['assignee_contact_name'])) {
2435 $contactActivities[$activityId]['assignee_contact'] = '';
2436 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2437 if ($acID && $count < 5) {
2438 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2441 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2445 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2451 if ( $values['activity_type'] == 'Bulk Email'){
2452 $contactActivities[$activityId]['openstats'] = "Opens: ".
2453 count(CRM_Mailing_Event_BAO_Opened
::getRows(
2454 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2457 count(CRM_Mailing_Event_BAO_TrackableURLOpen
::getRows(
2458 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2461 $contactActivities[$activityId]['openstats'] = '';
2464 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2465 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2467 // add class to this row if overdue
2468 $contactActivities[$activityId]['class'] = '';
2469 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2470 && CRM_Utils_Array
::value('status_id', $values) == 1
2472 $contactActivities[$activityId]['class'] = 'status-overdue';
2475 $contactActivities[$activityId]['class'] = 'status-ontime';
2479 $contactActivities[$activityId]['links'] = '';
2480 $accessMailingReport = FALSE;
2481 if (CRM_Utils_Array
::value('mailingId', $values)) {
2482 $accessMailingReport = TRUE;
2485 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2486 CRM_Utils_Array
::value('activity_type_id', $values),
2487 CRM_Utils_Array
::value('source_record_id', $values),
2488 $accessMailingReport,
2489 CRM_Utils_Array
::value('activity_id', $values)
2492 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2494 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2497 'id' => $values['activity_id'],
2498 'cid' => $params['contact_id'],
2500 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2506 return $contactActivities;
2510 * Used to copy custom fields and attachments from an existing activity to another.
2511 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2513 static function copyExtendedActivityData($params) {
2514 // attach custom data to the new activity
2515 $customParams = $htmlType = array();
2516 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2518 if (!empty($customValues)) {
2519 $fieldIds = implode(', ', array_keys($customValues));
2520 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2521 $result = CRM_Core_DAO
::executeQuery($sql);
2523 while ($result->fetch()) {
2524 $htmlType[] = $result->id
;
2527 foreach ($customValues as $key => $value) {
2528 if ($value !== NULL) { // CRM-10542
2529 if (in_array($key, $htmlType)) {
2530 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2531 $customParams["custom_{$key}_-1"] = array(
2532 'name' => $fileValues[0],
2533 'path' => $fileValues[1],
2537 $customParams["custom_{$key}_-1"] = $value;
2541 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2542 $params['mainActivityId'], 'Activity'
2546 // copy activity attachments ( if any )
2547 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2550 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2551 $activityContact = new CRM_Activity_BAO_ActivityContact();
2552 $activityContact->activity_id
= $activityId;
2553 if ($recordTypeID) {
2554 $activityContact->record_type_id
= $recordTypeID;
2556 if ($activityContact->find(TRUE)) {
2557 return $activityContact->$column;