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
83 * @internal param string $activityType activity type
85 * @return object CRM_Core_BAO_Meeting object
88 public static function retrieve(&$params, &$defaults) {
89 $activity = new CRM_Activity_DAO_Activity();
90 $activity->copyValues($params);
92 if ($activity->find(TRUE)) {
93 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
94 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
95 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
96 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
98 // TODO: at some stage we'll have to deal
99 // TODO: with multiple values for assignees and targets, but
100 // TODO: for now, let's just fetch first row
101 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
102 $assignee_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
103 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
104 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
105 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
106 $defaults['target_contact'] = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
107 $target_contact_names = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
108 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
110 elseif (CRM_Core_Permission
::check('access CiviMail') ||
111 (CRM_Mailing_Info
::workflowEnabled() &&
112 CRM_Core_Permission
::check('create mailings')
115 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
116 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$sourceContactId}&context=activity"
120 $defaults['target_contact_value'] = ts('(recipients)');
123 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
124 $defaults['source_contact_id'] = $sourceContactId;
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
153 * @param bool $moveToTrash
158 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
160 if (!empty($params['id']) && !is_array($params['id'])) {
161 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
164 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
167 $transaction = new CRM_Core_Transaction();
168 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
169 $sourceRecordIds = implode(',', $params['source_record_id']);
172 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
177 if (!isset($params['id'])) {
178 if (is_array($params['activity_type_id'])) {
179 $activityTypes = implode(',', $params['activity_type_id']);
182 $activityTypes = $params['activity_type_id'];
185 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
186 $dao = CRM_Core_DAO
::executeQuery($query);
189 $activity = new CRM_Activity_DAO_Activity();
190 $activity->copyValues($params);
191 $result = $activity->delete();
194 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
196 // CRM-13994 delete activity entity_tag
197 $query = "DELETE FROM civicrm_entity_tag WHERE entity_table = 'civicrm_activity' AND entity_id = {$activity->id}";
198 $dao = CRM_Core_DAO
::executeQuery($query);
202 $activity = new CRM_Activity_DAO_Activity();
203 $activity->copyValues($params);
205 $activity->is_deleted
= 1;
206 $result = $activity->save();
208 // CRM-4525 log activity delete
209 $logMsg = 'Case Activity deleted for';
212 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
213 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
214 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
215 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
216 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
217 if ($sourceContactId) {
218 $msgs[] = " source={$sourceContactId}";
221 //get target contacts.
222 $targetContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $targetID);
223 if (!empty($targetContactIds)) {
224 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
226 //get assignee contacts.
227 $assigneeContactIds = CRM_Activity_BAO_ActivityContact
::getNames($activity->id
, $assigneeID);
228 if (!empty($assigneeContactIds)) {
229 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
232 $logMsg .= implode(', ', $msgs);
234 self
::logActivityAction($activity, $logMsg);
237 // delete the recently created Activity
239 $activityRecent = array(
240 'id' => $activity->id
,
241 'type' => 'Activity',
243 CRM_Utils_Recent
::del($activityRecent);
246 $transaction->commit();
247 if (isset($activity)) {
249 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
250 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
257 * Delete activity assignment record
260 * @param null $recordTypeID
262 * @internal param int $id activity id
267 public static function deleteActivityContact($activityId, $recordTypeID = NULL) {
268 $activityContact = new CRM_Activity_BAO_ActivityContact();
269 $activityContact->activity_id
= $activityId;
271 $activityContact->record_type_id
= $recordTypeID;
273 $activityContact->delete();
277 * Function to process the activities
279 * @param array $params associated array of the submitted values
281 * @throws CRM_Core_Exception
282 * @internal param object $form form object
283 * @internal param array $ids array of ids
284 * @internal param string $activityType activity Type
285 * @internal param bool $record true if it is Record Activity
288 * @return $this|null|object
290 public static function create(&$params) {
291 // check required params
292 if (!self
::dataExists($params)) {
293 throw new CRM_Core_Exception('Not enough data to create activity object');
296 $activity = new CRM_Activity_DAO_Activity();
298 if (isset($params['id']) && empty($params['id'])) {
299 unset($params['id']);
302 if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
303 if (isset($params['activity_date_time']) &&
304 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
306 $params['status_id'] = 2;
309 $params['status_id'] = 1;
313 //set priority to Normal for Auto-populated activities (for Cases)
314 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
315 // if not set and not 0
316 !CRM_Utils_Array
::value('id', $params)
318 $priority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
319 $params['priority_id'] = array_search('Normal', $priority);
322 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
323 $params['target_contact_id'] = array_unique($params['target_contact_id']);
325 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
326 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
330 if (!empty($params['id'])) {
331 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
334 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
337 $activity->copyValues($params);
338 if (isset($params['case_id'])) {
339 // CRM-8708, preserve case ID even though it's not part of the SQL model
340 $activity->case_id
= $params['case_id'];
342 elseif (is_numeric($activity->id
)) {
343 // CRM-8708, preserve case ID even though it's not part of the SQL model
344 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
348 $transaction = new CRM_Core_Transaction();
350 $result = $activity->save();
352 if (is_a($result, 'CRM_Core_Error')) {
353 $transaction->rollback();
357 $activityId = $activity->id
;
358 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
359 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
360 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
361 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
363 if (isset($params['source_contact_id'])) {
365 'activity_id' => $activityId,
366 'contact_id' => $params['source_contact_id'],
367 'record_type_id' => $sourceID
369 self
::deleteActivityContact($activityId, $sourceID);
370 CRM_Activity_BAO_ActivityContact
::create($acParams);
373 // check and attach and files as needed
374 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
376 // attempt to save activity assignment
377 $resultAssignment = NULL;
378 if (!empty($params['assignee_contact_id'])) {
380 $assignmentParams = array('activity_id' => $activityId);
382 if (is_array($params['assignee_contact_id'])) {
383 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
384 // first delete existing assignments if any
385 self
::deleteActivityContact($activityId, $assigneeID);
389 foreach ($params['assignee_contact_id'] as $acID) {
391 $values[] = "( $activityId, $acID, $assigneeID )";
394 while (!empty($values)) {
395 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
396 $str = implode(',', $input);
397 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
398 CRM_Core_DAO
::executeQuery($sql);
402 $assignmentParams['contact_id'] = $params['assignee_contact_id'];
403 $assignmentParams['record_type_id'] = $assigneeID;
404 if (!empty($params['id'])) {
405 $assignment = new CRM_Activity_BAO_ActivityContact();
406 $assignment->activity_id
= $activityId;
407 $assignment->record_type_id
= $assigneeID;
408 $assignment->find(TRUE);
410 if ($assignment->contact_id
!= $params['assignee_contact_id']) {
411 $assignmentParams['id'] = $assignment->id
;
412 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
416 $resultAssignment = CRM_Activity_BAO_ActivityContact
::create($assignmentParams);
421 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
422 self
::deleteActivityContact($activityId, $assigneeID);
426 if (is_a($resultAssignment, 'CRM_Core_Error')) {
427 $transaction->rollback();
428 return $resultAssignment;
431 // attempt to save activity targets
432 $resultTarget = NULL;
433 if (!empty($params['target_contact_id'])) {
435 $targetParams = array('activity_id' => $activityId);
436 $resultTarget = array();
437 if (is_array($params['target_contact_id'])) {
438 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
439 // first delete existing targets if any
440 self
::deleteActivityContact($activityId, $targetID );
444 foreach ($params['target_contact_id'] as $tid) {
446 $values[] = "( $activityId, $tid, $targetID )";
450 while (!empty($values)) {
451 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
452 $str = implode(',', $input);
453 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES $str;";
454 CRM_Core_DAO
::executeQuery($sql);
458 $targetParams['contact_id'] = $params['target_contact_id'];
459 $targetParams['record_type_id'] = $targetID;
460 if (!empty($params['id'])) {
461 $target = new CRM_Activity_BAO_ActivityContact();
462 $target->activity_id
= $activityId;
463 $target->record_type_id
= $targetID;
466 if ($target->contact_id
!= $params['target_contact_id']) {
467 $targetParams['id'] = $target->id
;
468 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
472 $resultTarget = CRM_Activity_BAO_ActivityContact
::create($targetParams);
477 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
478 self
::deleteActivityContact($activityId, $targetID );
482 // write to changelog before transaction is committed/rolled
483 // back (and prepare status to display)
484 if (!empty($params['id'])) {
485 $logMsg = "Activity (id: {$result->id} ) updated with ";
488 $logMsg = "Activity created for ";
492 if (isset($params['source_contact_id'])) {
493 $msgs[] = "source={$params['source_contact_id']}";
496 if (!empty($params['target_contact_id'])) {
497 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
498 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
499 // take only first target
500 // will be used for recently viewed display
501 $t = array_slice($params['target_contact_id'], 0, 1);
502 $recentContactId = $t[0];
504 //is array check fixes warning without degrading functionality but it seems this bit of code may no longer work
505 // as it may always be an array
506 elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
507 $msgs[] = "target={$params['target_contact_id']}";
508 // will be used for recently viewed display
509 $recentContactId = $params['target_contact_id'];
513 // at worst, take source for recently viewed display
514 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
517 if (isset($params['assignee_contact_id'])) {
518 if (is_array($params['assignee_contact_id'])) {
519 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
522 $msgs[] = "assignee={$params['assignee_contact_id']}";
525 $logMsg .= implode(', ', $msgs);
527 self
::logActivityAction($result, $logMsg);
529 if (!empty($params['custom']) &&
530 is_array($params['custom'])
532 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
535 $transaction->commit();
536 if (empty($params['skipRecentView'])) {
537 $recentOther = array();
538 if (!empty($params['case_id'])) {
539 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
540 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
541 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
545 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home";
546 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
547 $url = CRM_Utils_System
::url('civicrm/activity', $q);
548 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
549 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
550 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home"
554 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
555 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
559 if (CRM_Core_Permission
::check("delete activities")) {
560 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
561 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
566 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
567 if (CRM_Core_Permission
::check('delete activities')) {
568 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
569 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array
::value('source_contact_id', $params) . "&context=home"
575 if (!isset($activity->parent_id
)) {
576 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
577 // add the recently created Activity
578 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
579 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
582 if (isset($activitySubject)) {
583 $title = $activitySubject . ' - ';
586 $title = $title . $recentContactDisplay;
587 if (!empty($activityTypes[$activity->activity_type_id
])) {
588 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
591 CRM_Utils_Recent
::add($title,
596 $recentContactDisplay,
602 // reset the group contact cache since smart groups might be affected due to this
603 CRM_Contact_BAO_GroupContactCache
::remove();
605 if (!empty($params['id'])) {
606 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
609 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
612 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
614 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
615 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
617 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
619 'activity_id' => $activity->id
,
620 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
622 if ($caseParams['case_id']) {
623 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
626 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
635 * @param null $logMessage
639 public static function logActivityAction($activity, $logMessage = NULL) {
640 $session = CRM_Core_Session
::singleton();
641 $id = $session->get('userID');
643 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
644 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
645 $id = self
::getActivityContact($activity->id
. $sourceID);
648 'entity_table' => 'civicrm_activity',
649 'entity_id' => $activity->id
,
650 'modified_id' => $id,
651 'modified_date' => date('YmdHis'),
652 'data' => $logMessage,
654 CRM_Core_BAO_Log
::add($logParams);
659 * function to get the list Activities
661 * @param array $input array of parameters
663 * - contact_id int contact_id whose activities we want to retrieve
664 * - offset int which row to start from ?
665 * - rowCount int how many rows to fetch
666 * - sort object|array object or array describing sort order for sql query.
667 * - admin boolean if contact is admin
668 * - caseId int case ID
669 * - context string page on which selector is build
670 * - activity_type_id int|string the activitiy types we want to restrict by
672 * @return array (reference) $values the relevant data object values of open activities
677 static function &getActivities($input) {
678 //step 1: Get the basic activity data
679 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue(
685 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
686 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
687 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
688 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
690 $config = CRM_Core_Config
::singleton();
692 $randomNum = md5(uniqid());
693 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
695 $tableFields = array(
696 'activity_id' => 'int unsigned',
697 'activity_date_time' => 'datetime',
698 'source_record_id' => 'int unsigned',
699 'status_id' => 'int unsigned',
700 'subject' => 'varchar(255)',
701 'source_contact_name' => 'varchar(255)',
702 'activity_type_id' => 'int unsigned',
703 'activity_type' => 'varchar(128)',
704 'case_id' => 'int unsigned',
705 'case_subject' => 'varchar(255)',
706 'campaign_id' => 'int unsigned',
709 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
710 $insertValueSQL = array();
711 // The activityTempTable contains the sorted rows
712 // so in order to maintain the sort order as-is we add an auto_increment
713 // field; we can sort by this later to ensure the sort order stays correct.
714 $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,";
715 foreach ($tableFields as $name => $desc) {
716 $sql .= "$name $desc,\n";
717 $insertValueSQL[] = $name;
720 // add unique key on activity_id just to be sure
721 // this cannot be primary key because we need that for the auto_increment
722 // fixed_sort_order field
724 UNIQUE KEY ( activity_id )
725 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
728 CRM_Core_DAO
::executeQuery($sql);
730 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
732 $order = $limit = $groupBy = '';
733 $groupBy = " GROUP BY tbl.activity_id ";
735 if (!empty($input['sort'])) {
736 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
737 $orderBy = $input['sort']->orderBy();
738 if (!empty($orderBy)) {
739 $order = " ORDER BY $orderBy";
742 elseif (trim($input['sort'])) {
743 $sort = CRM_Utils_Type
::escape($input['sort'], 'String');
744 $order = " ORDER BY $sort ";
749 // context = 'activity' in Activities tab.
750 $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 ";
753 if (!empty($input['rowCount']) &&
754 $input['rowCount'] > 0
756 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
759 $input['count'] = FALSE;
760 list($sqlClause, $params) = self
::getActivitySQLClause($input);
762 $query = "{$insertSQL}
763 SELECT DISTINCT tbl.* from ( {$sqlClause} )
766 //filter case activities - CRM-5761
767 $components = self
::activityComponents();
768 if (!in_array('CiviCase', $components)) {
770 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
771 WHERE civicrm_case_activity.id IS NULL";
774 $query = $query . $groupBy . $order . $limit;
776 $dao = CRM_Core_DAO
::executeQuery($query, $params);
778 // step 2: Get target and assignee contacts for above activities
779 // create temp table for target contacts
780 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
781 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
782 activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),
783 contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )
784 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
786 CRM_Core_DAO
::executeQuery($query);
788 // note that we ignore bulk email for targets, since we don't show it in selector
790 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )
791 SELECT ac.activity_id,
796 FROM {$activityTempTable}
797 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
798 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
799 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
800 WHERE ac.record_type_id != %1
802 $params = array(1 => array($targetID, 'Integer'));
803 CRM_Core_DAO
::executeQuery($query, $params);
805 // for each activity insert one target contact
806 // if we load all target contacts the performance will suffer a lot for mass-activities;
808 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )
809 SELECT ac.activity_id,
815 FROM {$activityTempTable}
816 INNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )
817 INNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )
818 INNER JOIN civicrm_contact c ON c.id = ac.contact_id
819 WHERE ac.record_type_id = %1
820 GROUP BY ac.activity_id
823 CRM_Core_DAO
::executeQuery($query, $params);
825 // step 3: Combine all temp tables to get final query for activity selector
826 // sort by the original sort order, stored in fixed_sort_order
828 SELECT {$activityTempTable}.*,
829 {$activityContactTempTable}.contact_id,
830 {$activityContactTempTable}.record_type_id,
831 {$activityContactTempTable}.contact_name,
832 {$activityContactTempTable}.is_deleted,
833 {$activityContactTempTable}.counter
834 FROM {$activityTempTable}
835 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
836 ORDER BY fixed_sort_order
839 $dao = CRM_Core_DAO
::executeQuery($query);
841 //CRM-3553, need to check user has access to target groups.
842 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
844 (CRM_Core_Permission
::check('access CiviMail')) ||
845 (CRM_Mailing_Info
::workflowEnabled() &&
846 CRM_Core_Permission
::check('create mailings'))
850 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
852 while ($dao->fetch()) {
853 $activityID = $dao->activity_id
;
854 $values[$activityID]['activity_id'] = $dao->activity_id
;
855 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
856 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
857 $values[$activityID]['activity_type'] = $dao->activity_type
;
858 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
859 $values[$activityID]['status_id'] = $dao->status_id
;
860 $values[$activityID]['subject'] = $dao->subject
;
861 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
863 if ($dao->campaign_id
) {
864 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
867 if (empty($values[$activityID]['assignee_contact_name'])) {
868 $values[$activityID]['assignee_contact_name'] = array();
871 if (empty($values[$activityID]['target_contact_name'])) {
872 $values[$activityID]['target_contact_name'] = array();
873 $values[$activityID]['target_contact_counter'] = $dao->counter
;
876 // if deleted, wrap in <del>
877 if ( $dao->is_deleted
) {
878 $dao->contact_name
= "<del>{$dao->contact_name}</dao>";
881 if ($dao->record_type_id
== $sourceID && $dao->contact_id
) {
882 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
883 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
886 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
887 // build array of target / assignee names
888 if ($dao->record_type_id
== $targetID && $dao->contact_id
) {
889 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
891 if ($dao->record_type_id
== $assigneeID && $dao->contact_id
) {
892 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
895 // case related fields
896 $values[$activityID]['case_id'] = $dao->case_id
;
897 $values[$activityID]['case_subject'] = $dao->case_subject
;
900 $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter
));
901 $values[$activityID]['mailingId'] = false;
904 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
906 $values[$activityID]['mailingId'] = true;
915 * Get the component id and name those are enabled and logged in
916 * user has permission. To decide whether we are going to include
917 * component related activities w/ core activity retrieve process.
919 * return an array of component id and name.
922 static function activityComponents() {
923 $components = array();
924 $compInfo = CRM_Core_Component
::getEnabledComponents();
925 foreach ($compInfo as $compObj) {
926 if (!empty($compObj->info
['showActivitiesInCore'])) {
927 if ($compObj->info
['name'] == 'CiviCampaign') {
928 $componentPermission = "administer {$compObj->name}";
931 $componentPermission = "access {$compObj->name}";
933 if ($compObj->info
['name'] == 'CiviCase') {
934 if (CRM_Case_BAO_Case
::accessCiviCase()) {
935 $components[$compObj->componentID
] = $compObj->info
['name'];
938 elseif (CRM_Core_Permission
::check($componentPermission)) {
939 $components[$compObj->componentID
] = $compObj->info
['name'];
948 * function to get the activity Count
950 * @param array $input array of parameters
952 * - contact_id int contact_id whose activities we want to retrieve
953 * - admin boolean if contact is admin
954 * - caseId int case ID
955 * - context string page on which selector is build
956 * - activity_type_id int|string the activity types we want to restrict by
958 * @return int count of activities
963 static function &getActivitiesCount($input) {
964 $input['count'] = TRUE;
965 list($sqlClause, $params) = self
::getActivitySQLClause($input);
967 //filter case activities - CRM-5761
968 $components = self
::activityComponents();
969 if (!in_array('CiviCase', $components)) {
971 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
972 FROM ( {$sqlClause} ) as tbl
973 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
974 WHERE civicrm_case_activity.id IS NULL";
977 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
980 return CRM_Core_DAO
::singleValueQuery($query, $params);
984 * function to get the activity sql clause to pick activities
986 * @param array $input array of parameters
988 * - contact_id int contact_id whose activities we want to retrieve
989 * - admin boolean if contact is admin
990 * - caseId int case ID
991 * - context string page on which selector is build
992 * - count boolean are we interested in the count clause only?
993 * - activity_type_id int|string the activity types we want to restrict by
995 * @return int count of activities
1000 static function getActivitySQLClause($input) {
1002 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1004 $config = CRM_Core_Config
::singleton();
1005 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
1006 $sourceWhere = ' ac.contact_id = %1 ';
1007 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1009 $params = array(1 => array($input['contact_id'], 'Integer'));
1012 $commonClauses = array(
1013 "civicrm_option_group.name = 'activity_type'",
1014 "civicrm_activity.is_deleted = 0",
1015 "civicrm_activity.is_current_revision = 1",
1016 "civicrm_activity.is_test= 0",
1019 if ($input['context'] != 'activity') {
1020 $commonClauses[] = "civicrm_activity.status_id = 1";
1023 //Filter on component IDs.
1024 $components = self
::activityComponents();
1025 if (!empty($components)) {
1026 $componentsIn = implode(',', array_keys($components));
1027 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1030 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1033 // activity type ID clause
1034 if (!empty($input['activity_type_id'])) {
1035 if (is_array($input['activity_type_id'])) {
1036 foreach ($input['activity_type_id'] as $idx => $value) {
1037 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1039 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1042 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1043 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1047 // exclude by activity type clause
1048 if (!empty($input['activity_type_exclude_id'])) {
1049 if (is_array($input['activity_type_exclude_id'])) {
1050 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1051 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1053 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1056 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1057 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1061 $commonClause = implode(' AND ', $commonClauses);
1063 $includeCaseActivities = FALSE;
1064 if (in_array('CiviCase', $components)) {
1065 $includeCaseActivities = TRUE;
1069 // build main activity table select clause
1072 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1073 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1075 INNER JOIN civicrm_activity_contact ac ON ac.activity_id = civicrm_activity.id
1076 INNER JOIN civicrm_contact contact ON ac.contact_id = contact.id
1079 if (!$input['count']) {
1081 civicrm_activity.activity_date_time,
1082 civicrm_activity.source_record_id,
1083 civicrm_activity.status_id,
1084 civicrm_activity.subject,
1085 contact.sort_name as source_contact_name,
1086 civicrm_option_value.value as activity_type_id,
1087 civicrm_option_value.label as activity_type,
1088 null as case_id, null as case_subject,
1089 civicrm_activity.campaign_id as campaign_id
1093 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)
1098 SELECT civicrm_activity.id as activity_id
1100 from civicrm_activity
1101 left join civicrm_option_value on
1102 civicrm_activity.activity_type_id = civicrm_option_value.value
1103 left join civicrm_option_group on
1104 civicrm_option_group.id = civicrm_option_value.option_group_id
1111 // Build case clause
1112 // or else exclude Inbound Emails that have been filed on a case.
1115 if ($includeCaseActivities) {
1117 if (!$input['count']) {
1119 civicrm_activity.activity_date_time,
1120 civicrm_activity.source_record_id,
1121 civicrm_activity.status_id,
1122 civicrm_activity.subject,
1123 contact.sort_name as source_contact_name,
1124 civicrm_option_value.value as activity_type_id,
1125 civicrm_option_value.label as activity_type,
1126 null as case_id, null as case_subject,
1127 civicrm_activity.campaign_id as campaign_id';
1133 SELECT civicrm_activity.id as activity_id
1135 from civicrm_activity
1136 inner join civicrm_case_activity on
1137 civicrm_case_activity.activity_id = civicrm_activity.id
1138 inner join civicrm_case on
1139 civicrm_case_activity.case_id = civicrm_case.id
1140 inner join civicrm_case_contact on
1141 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1142 left join civicrm_option_value on
1143 civicrm_activity.activity_type_id = civicrm_option_value.value
1144 left join civicrm_option_group on
1145 civicrm_option_group.id = civicrm_option_value.option_group_id
1150 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1151 ( civicrm_option_value.name <> 'Inbound Email' AND
1152 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1158 $returnClause = " {$sourceClause} {$caseClause} ";
1160 return array($returnClause, $params);
1164 * send the message to all the contacts and also insert a
1165 * contact activity in each contacts record
1167 * @param array $contactDetails the array of contact details to send the email
1168 * @param string $subject the subject of the message
1171 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1172 * @param int $userID use this userID if set
1173 * @param string $from
1174 * @param array $attachments the array of attachments if any
1175 * @param string $cc cc recipient
1176 * @param string $bcc bcc recipient
1177 * @param array $contactIds contact ids
1178 * @param string $additionalDetails the additional information of CC and BCC appended to the activity Details
1180 * @internal param string $message the message contents
1181 * @return array ( sent, activityId) if any email is sent and activityId
1185 static function sendEmail(
1193 $attachments = NULL,
1196 $contactIds, // FIXME a param with no default shouldn't be last
1197 $additionalDetails = NULL
1199 // get the contact details of logged in contact, which we set as from email
1200 if ($userID == NULL) {
1201 $session = CRM_Core_Session
::singleton();
1202 $userID = $session->get('userID');
1205 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1207 return array(count($contactDetails), 0, count($contactDetails));
1209 if (!trim($fromDisplayName)) {
1210 $fromDisplayName = $fromEmail;
1214 // token replacement of addressee/email/postal greetings
1215 // get the tokens added in subject and message
1216 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1217 $messageToken = CRM_Utils_Token
::getTokens($text);
1218 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1219 $allTokens = array_merge($messageToken, $subjectToken);
1222 $from = "$fromDisplayName <$fromEmail>";
1225 //create the meta level record first ( email activity )
1226 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1231 // CRM-6265: save both text and HTML parts in details (if present)
1232 if ($html and $text) {
1233 $details = "-ALTERNATIVE ITEM 0-\n$html$additionalDetails\n-ALTERNATIVE ITEM 1-\n$text$additionalDetails\n-ALTERNATIVE END-\n";
1236 $details = $html ?
$html : $text;
1237 $details .= $additionalDetails;
1240 $activityParams = array(
1241 'source_contact_id' => $userID,
1242 'activity_type_id' => $activityTypeID,
1243 'activity_date_time' => date('YmdHis'),
1244 'subject' => $subject,
1245 'details' => $details,
1246 // FIXME: check for name Completed and get ID from that lookup
1250 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1251 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1253 // add the attachments to activity params here
1255 // first process them
1256 $activityParams = array_merge($activityParams,
1261 $activity = self
::create($activityParams);
1263 // get the set of attachments from where they are stored
1264 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1267 $returnProperties = array();
1268 if (isset($messageToken['contact'])) {
1269 foreach ($messageToken['contact'] as $key => $value) {
1270 $returnProperties[$value] = 1;
1274 if (isset($subjectToken['contact'])) {
1275 foreach ($subjectToken['contact'] as $key => $value) {
1276 if (!isset($returnProperties[$value])) {
1277 $returnProperties[$value] = 1;
1283 // get token details for contacts, call only if tokens are used
1285 if (!empty($returnProperties) ||
!empty($tokens) ||
!empty($allTokens)) {
1286 list($details) = CRM_Utils_Token
::getTokenDetails(
1291 'CRM_Activity_BAO_Activity'
1297 CRM_Utils_Hook
::tokens($tokens);
1298 $categories = array_keys($tokens);
1300 $escapeSmarty = FALSE;
1301 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1302 $smarty = CRM_Core_Smarty
::singleton();
1303 $escapeSmarty = TRUE;
1306 $sent = $notSent = array();
1307 foreach ($contactDetails as $values) {
1308 $contactId = $values['contact_id'];
1309 $emailAddress = $values['email'];
1311 if (!empty($details) && is_array($details["{$contactId}"])) {
1312 // unset email from details since it always returns primary email address
1313 unset($details["{$contactId}"]['email']);
1314 unset($details["{$contactId}"]['email_id']);
1315 $values = array_merge($values, $details["{$contactId}"]);
1318 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1319 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1322 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1323 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1324 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1330 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1331 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1332 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1338 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1339 // also add the contact tokens to the template
1340 $smarty->assign_by_ref('contact', $values);
1342 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1343 $tokenText = $smarty->fetch("string:$tokenText");
1344 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1348 if (self
::sendMessage(
1365 return array($sent, $activity->id
);
1369 * @param $contactDetails
1370 * @param $activityParams
1371 * @param array $smsParams
1372 * @param $contactIds
1373 * @param null $userID
1376 * @throws CRM_Core_Exception
1378 static function sendSMS(&$contactDetails,
1380 &$smsParams = array(),
1384 if ($userID == NULL) {
1385 $session = CRM_Core_Session
::singleton();
1386 $userID = $session->get('userID');
1389 $text = &$activityParams['text_message'];
1390 $html = &$activityParams['html_message'];
1393 // token replacement of addressee/email/postal greetings
1394 // get the tokens added in subject and message
1395 $messageToken = CRM_Utils_Token
::getTokens($text);
1396 $messageToken = array_merge($messageToken,
1397 CRM_Utils_Token
::getTokens($html)
1400 //create the meta level record first ( sms activity )
1401 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1406 // CRM-6265: save both text and HTML parts in details (if present)
1407 if ($html and $text) {
1408 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1411 $details = $html ?
$html : $text;
1414 $activitySubject = $activityParams['activity_subject'];
1415 $activityParams = array(
1416 'source_contact_id' => $userID,
1417 'activity_type_id' => $activityTypeID,
1418 'activity_date_time' => date('YmdHis'),
1419 'subject' => $activitySubject,
1420 'details' => $details,
1421 // FIXME: check for name Completed and get ID from that lookup
1425 $activity = self
::create($activityParams);
1426 $activityID = $activity->id
;
1428 $returnProperties = array();
1430 if (isset($messageToken['contact'])) {
1431 foreach ($messageToken['contact'] as $key => $value) {
1432 $returnProperties[$value] = 1;
1438 CRM_Utils_Hook
::tokens($tokens);
1439 $categories = array_keys($tokens);
1441 // get token details for contacts, call only if tokens are used
1443 if (!empty($returnProperties) ||
!empty($tokens)) {
1444 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1448 'CRM_Activity_BAO_Activity'
1453 $escapeSmarty = FALSE;
1455 foreach ($contactDetails as $values) {
1456 $contactId = $values['contact_id'];
1458 if (!empty($details) && is_array($details["{$contactId}"])) {
1459 // unset email from details since it always returns primary email address
1460 unset($details["{$contactId}"]['email']);
1461 unset($details["{$contactId}"]['email_id']);
1462 $values = array_merge($values, $details["{$contactId}"]);
1465 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1466 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1468 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1469 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1471 // Only send if the phone is of type mobile
1472 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1473 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1474 $smsParams['To'] = $values['phone'];
1477 $smsParams['To'] = '';
1480 $sendResult = self
::sendSMSMessage(
1489 if (PEAR
::isError($sendResult)) {
1490 // Collect all of the PEAR_Error objects
1491 $errMsgs[] = $sendResult;
1497 // If at least one message was sent and no errors
1498 // were generated then return a boolean value of TRUE.
1499 // Otherwise, return FALSE (no messages sent) or
1500 // and array of 1 or more PEAR_Error objects.
1502 if ($success > 0 && count($errMsgs) == 0) {
1504 } elseif (count($errMsgs) > 0) {
1508 return array($sent, $activity->id
, $success);
1512 * send the sms message to a specific contact
1514 * @param int $toID the contact id of the recipient
1517 * @param array $smsParams the params used for sending sms
1519 * @param int $activityID the activity ID that tracks the message
1520 * @param null $userID
1522 * @return mixed true on success or PEAR_Error object
1526 static function sendSMSMessage($toID,
1529 $smsParams = array(),
1534 $toPhoneNumber = "";
1536 if ($smsParams['To']) {
1537 $toPhoneNumber = trim($smsParams['To']);
1540 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1541 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1542 //to get primary mobile ph,if not get a first mobile ph
1543 if (!empty($toPhoneNumbers)) {
1544 $toPhoneNumerDetails = reset($toPhoneNumbers);
1545 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1546 //contact allows to send sms
1551 // make sure both phone are valid
1552 // and that the recipient wants to receive sms
1553 if (empty($toPhoneNumber) or $toDoNotSms) {
1554 return PEAR
::raiseError(
1555 'Recipient phone number is invalid or recipient does not want to receive SMS',
1561 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1562 $recipient = $smsParams['To'];
1563 $smsParams['contact_id'] = $toID;
1564 $smsParams['parent_activity_id'] = $activityID;
1566 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1567 $sendResult = $providerObj->send($recipient, $smsParams, $message, NULL, $userID);
1568 if (PEAR
::isError($sendResult)) {
1572 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1573 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1576 // add activity target record for every sms that is send
1577 $activityTargetParams = array(
1578 'activity_id' => $activityID,
1579 'contact_id' => $toID,
1580 'record_type_id' => $targetID
1582 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1588 * send the message to a specific contact
1590 * @param string $from the name and email of the sender
1592 * @param int $toID the contact id of the recipient
1593 * @param string $subject the subject of the message
1594 * @param $text_message
1595 * @param $html_message
1596 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1597 * @param int $activityID the activity ID that tracks the message
1599 * @param null $attachments
1603 * @internal param string $message the message contents
1604 * @return boolean true if successfull else false.
1608 static function sendMessage($from,
1616 $attachments = NULL,
1620 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1621 if ($emailAddress) {
1622 $toEmail = trim($emailAddress);
1625 // make sure both email addresses are valid
1626 // and that the recipient wants to receive email
1627 if (empty($toEmail) or $toDoNotEmail) {
1630 if (!trim($toDisplayName)) {
1631 $toDisplayName = $toEmail;
1634 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1635 //$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1636 //$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1637 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1639 // create the params array
1640 $mailParams = array(
1641 'groupName' => 'Activity Email Sender',
1643 'toName' => $toDisplayName,
1644 'toEmail' => $toEmail,
1645 'subject' => $subject,
1648 'text' => $text_message,
1649 'html' => $html_message,
1650 'attachments' => $attachments,
1653 if (!CRM_Utils_Mail
::send($mailParams)) {
1657 // add activity target record for every mail that is send
1658 $activityTargetParams = array(
1659 'activity_id' => $activityID,
1660 'contact_id' => $toID,
1661 'record_type_id' => $targetID
1663 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1668 * combine all the importable fields from the lower levels object
1670 * The ordering is important, since currently we do not have a weight
1671 * scheme. Adding weight is super important and should be done in the
1672 * next week or so, before this can be called complete.
1674 * @param bool $status
1676 * @internal param $NULL
1678 * @return array array of importable Fields
1682 static function &importableFields($status = FALSE) {
1683 if (!self
::$_importableFields) {
1684 if (!self
::$_importableFields) {
1685 self
::$_importableFields = array();
1688 $fields = array('' => array('title' => ts('- do not import -')));
1691 $fields = array('' => array('title' => ts('- Activity Fields -')));
1694 $tmpFields = CRM_Activity_DAO_Activity
::import();
1695 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1697 // Using new Dedupe rule.
1698 $ruleParams = array(
1699 'contact_type' => 'Individual',
1700 'used' => 'Unsupervised',
1702 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1704 $tmpConatctField = array();
1705 if (is_array($fieldsArray)) {
1706 foreach ($fieldsArray as $value) {
1707 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1712 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1713 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1714 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1717 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1718 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1719 $fields = array_merge($fields, $tmpConatctField);
1720 $fields = array_merge($fields, $tmpFields);
1721 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1722 self
::$_importableFields = $fields;
1724 return self
::$_importableFields;
1728 * To get the Activities of a target contact
1730 * @param $contactId Integer ContactId of the contact whose activities
1733 * @return array array of activity fields
1736 static function getContactActivity($contactId) {
1737 $activities = array();
1738 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1739 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1740 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1741 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1744 // First look for activities where contactId is one of the targets
1746 SELECT activity_id, record_type_id
1747 FROM civicrm_activity_contact
1748 WHERE contact_id = $contactId
1750 $dao = CRM_Core_DAO
::executeQuery($query);
1751 while ($dao->fetch()) {
1752 if ($dao->record_type_id
== $targetID ) {
1753 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1755 else if ($dao->record_type_id
== $assigneeID) {
1756 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1759 // do source stuff here
1760 $activities[$dao->activity_id
]['source_contact_id'] = $contactId;
1764 $activityIds = array_keys($activities);
1765 if (count($activityIds) < 1) {
1769 $activityIds = implode(',', $activityIds);
1771 SELECT activity.id as activity_id,
1773 subject, location, activity_date_time, details, status_id
1774 FROM civicrm_activity activity
1775 WHERE activity.id IN ($activityIds)";
1777 $dao = CRM_Core_DAO
::executeQuery($query);
1779 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1780 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1782 while ($dao->fetch()) {
1783 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1784 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1785 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1786 $activities[$dao->activity_id
]['location'] = $dao->location
;
1787 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1788 $activities[$dao->activity_id
]['details'] = $dao->details
;
1789 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1790 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1791 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1793 // set to null if not set
1794 if (!isset($activities[$dao->activity_id
]['source_contact_id'])) {
1795 $activities[$dao->activity_id
]['source_contact_id'] = NULL;
1802 * Function to add activity for Membership/Event/Contribution
1804 * @param object $activity (reference) particular component object
1805 * @param string $activityType for Membership Signup or Renewal
1808 * @param null $targetContactID
1814 static function addActivity(&$activity,
1815 $activityType = 'Membership Signup',
1816 $targetContactID = NULL
1818 if ($activity->__table
== 'civicrm_membership') {
1819 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1821 if (!$membershipType) {
1822 $membershipType = ts('Membership');
1825 $subject = "{$membershipType}";
1827 if (!empty($activity->source
) && $activity->source
!= 'null') {
1828 $subject .= " - {$activity->source}";
1831 if ($activity->owner_membership_id
) {
1834 FROM civicrm_contact, civicrm_membership
1835 WHERE civicrm_contact.id = civicrm_membership.contact_id
1836 AND civicrm_membership.id = $activity->owner_membership_id
1838 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1839 $subject .= " (by {$displayName})";
1842 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1843 // CRM-72097 changed from start date to today
1844 $date = date('YmdHis');
1845 $component = 'Membership';
1847 elseif ($activity->__table
== 'civicrm_participant') {
1848 $event = CRM_Event_BAO_Event
::getEvents(1, $activity->event_id
, TRUE, FALSE);
1850 $roles = CRM_Event_PseudoConstant
::participantRole();
1851 $status = CRM_Event_PseudoConstant
::participantStatus();
1853 $subject = $event[$activity->event_id
];
1854 if (!empty($roles[$activity->role_id
])) {
1855 $subject .= ' - ' . $roles[$activity->role_id
];
1857 if (!empty($status[$activity->status_id
])) {
1858 $subject .= ' - ' . $status[$activity->status_id
];
1860 $date = date('YmdHis');
1861 if ($activityType != 'Email') {
1862 $activityType = 'Event Registration';
1864 $component = 'Event';
1866 elseif ($activity->__table
== 'civicrm_contribution') {
1867 //create activity record only for Completed Contributions
1868 if ($activity->contribution_status_id
!= 1) {
1874 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1875 if (!empty($activity->source
) && $activity->source
!= 'null') {
1876 $subject .= " - {$activity->source}";
1878 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1879 $activityType = $component = 'Contribution';
1881 $activityParams = array(
1882 'source_contact_id' => $activity->contact_id
,
1883 'source_record_id' => $activity->id
,
1884 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1888 'subject' => $subject,
1889 'activity_date_time' => $date,
1890 'is_test' => $activity->is_test
,
1891 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1895 'skipRecentView' => TRUE,
1896 'campaign_id' => $activity->campaign_id
,
1899 // create activity with target contacts
1900 $session = CRM_Core_Session
::singleton();
1901 $id = $session->get('userID');
1903 $activityParams['source_contact_id'] = $id;
1904 $activityParams['target_contact_id'][] = $activity->contact_id
;
1908 if (property_exists($activity, 'details')) {
1909 $activityParams['details'] = $activity->details
;
1912 if ($targetContactID) {
1913 $activityParams['target_contact_id'][] = $targetContactID;
1915 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1916 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1922 * Function to get Parent activity for currently viewed activity
1924 * @param int $activityId current activity id
1926 * @return int $parentId Id of parent activity otherwise false.
1929 static function getParentActivity($activityId) {
1930 static $parentActivities = array();
1932 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1934 if (!array_key_exists($activityId, $parentActivities)) {
1935 $parentActivities[$activityId] = array();
1937 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1942 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1945 return $parentActivities[$activityId];
1949 * Function to get total count of prior revision of currently viewd activity
1951 * @param $activityID
1953 * @internal param int $activityId current activity id
1955 * @return int $params count of prior activities otherwise false.
1958 static function getPriorCount($activityID) {
1959 static $priorCounts = array();
1961 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1963 if (!array_key_exists($activityID, $priorCounts)) {
1964 $priorCounts[$activityID] = array();
1965 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1972 SELECT count( id ) AS cnt
1973 FROM civicrm_activity
1974 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1975 AND is_current_revision = 0
1976 AND id < {$activityID}
1978 $params = array(1 => array($originalID, 'Integer'));
1979 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1981 $priorCounts[$activityID] = $count ?
$count : 0;
1984 return $priorCounts[$activityID];
1988 * Function to get all prior activities of currently viewe
1991 * @param $activityID
1992 * @param bool $onlyPriorRevisions
1994 * @internal param int $activityId current activity id
1996 * @return array $result prior activities info.
1999 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
2000 static $priorActivities = array();
2002 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2003 $index = $activityID . '_' . (int) $onlyPriorRevisions;
2005 if (!array_key_exists($index, $priorActivities)) {
2006 $priorActivities[$index] = array();
2008 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2014 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2015 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2016 WHERE (ca.id = %1 OR ca.original_id = %1)
2017 AND cl.entity_table = 'civicrm_activity'
2018 AND cl.entity_id = ca.id
2019 AND cl.modified_id = c.id
2021 if ($onlyPriorRevisions) {
2022 $query .= " AND ca.id < {$activityID}";
2024 $query .= " ORDER BY ca.id DESC";
2026 $params = array(1 => array($originalID, 'Integer'));
2027 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2029 while ($dao->fetch()) {
2030 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
2031 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
2032 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
2037 return $priorActivities[$index];
2041 * Function to find the latest revision of a given activity
2043 * @param $activityID
2045 * @internal param int $activityId prior activity id
2047 * @return int $params current activity id.
2050 static function getLatestActivityId($activityID) {
2051 static $latestActivityIds = array();
2053 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2055 if (!array_key_exists($activityID, $latestActivityIds)) {
2056 $latestActivityIds[$activityID] = array();
2058 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2063 $activityID = $originalID;
2065 $params = array(1 => array($activityID, 'Integer'));
2066 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2068 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2071 return $latestActivityIds[$activityID];
2075 * Function to create a follow up a given activity
2077 * @activityId int activity id of parent activity
2079 * @param $activityId
2082 * @return $this|null|object
2083 * @internal param array $activity details
2087 static function createFollowupActivity($activityId, $params) {
2092 $session = CRM_Core_Session
::singleton();
2094 $followupParams = array();
2095 $followupParams['parent_id'] = $activityId;
2096 $followupParams['source_contact_id'] = $session->get('userID');
2097 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2099 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2100 // Get Subject of Follow-up Activiity, CRM-4491
2101 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2102 $followupParams['assignee_contact_id'] = CRM_Utils_Array
::value('followup_assignee_contact_id', $params);
2104 //create target contact for followup
2105 if (!empty($params['target_contact_id'])) {
2106 $followupParams['target_contact_id'] = $params['target_contact_id'];
2109 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2110 $params['followup_date_time']
2112 $followupActivity = self
::create($followupParams);
2114 return $followupActivity;
2118 * Function to get Activity specific File according activity type Id.
2120 * @param int $activityTypeId activity id
2122 * @param string $crmDir
2124 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2128 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2129 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2131 if ($activityTypes[$activityTypeId]['name']) {
2132 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2138 global $civicrm_root;
2139 $config = CRM_Core_Config
::singleton();
2140 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2141 if (empty($config->customPHPPathDir
)) {
2144 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2149 return $activityTypeFile;
2153 * Function to restore the activity
2155 * @param array $params associated array
2161 public static function restoreActivity(&$params) {
2162 $activity = new CRM_Activity_DAO_Activity();
2163 $activity->copyValues($params);
2165 $activity->is_deleted
= 0;
2166 $result = $activity->save();
2172 * Get the exportable fields for Activities
2174 * @param string $name if it is called by case $name = Case else $name = Activity
2176 * @return array array of exportable Fields
2180 static function &exportableFields($name = 'Activity') {
2181 if (!isset(self
::$_exportableFields[$name])) {
2182 self
::$_exportableFields[$name] = array();
2184 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2185 // my case hence we have defined fields as case_*
2186 if ($name == 'Activity') {
2187 $exportableFields = CRM_Activity_DAO_Activity
::export();
2188 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2189 $exportableFields['source_contact'] = array(
2190 'title' => ts('Source Contact'),
2191 'type' => CRM_Utils_Type
::T_STRING
,
2195 $Activityfields = array(
2196 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2197 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2199 $fields = array_merge($Activityfields, $exportableFields);
2202 //set title to activity fields
2204 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2205 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2206 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2207 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2208 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2209 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2210 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2211 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2212 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2213 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2216 // add custom data for cases
2217 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2220 // add custom data for case activities
2221 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2223 self
::$_exportableFields[$name] = $fields;
2225 return self
::$_exportableFields[$name];
2229 * Get the allowed profile fields for Activities
2231 * @return array array of activity profile Fields
2234 static function getProfileFields() {
2235 $exportableFields = self
::exportableFields('Activity');
2236 $skipFields = array(
2239 'source_contact_id',
2241 'activity_campaign',
2243 'is_current_revision',
2244 'activity_is_deleted',
2246 $config = CRM_Core_Config
::singleton();
2247 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2248 $skipFields[] = 'activity_engagement_level';
2251 foreach ($skipFields as $field) {
2252 if (isset($exportableFields[$field])) {
2253 unset($exportableFields[$field]);
2257 // hack to use 'activity_type_id' instead of 'activity_type'
2258 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2259 unset($exportableFields['activity_status']);
2261 return $exportableFields;
2265 * This function deletes the activity record related to contact record,
2266 * when there are no target and assignee record w/ other contact.
2268 * @param int $contactId contactId
2273 public static function cleanupActivity($contactId) {
2278 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2279 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2281 $transaction = new CRM_Core_Transaction();
2283 // delete activity if there is no record in civicrm_activity_contact
2284 // pointing to any other contact record
2285 $activityContact = new CRM_Activity_DAO_ActivityContact();
2286 $activityContact->contact_id
= $contactId;
2287 $activityContact->record_type_id
= $sourceID;
2288 $activityContact->find();
2290 while ($activityContact->fetch()) {
2291 // delete activity_contact record for the deleted contact
2292 $activityContact->delete();
2294 $activityContactOther = new CRM_Activity_DAO_ActivityContact();
2295 $activityContactOther->activity_id
= $activityContact->activity_id
;
2297 // delete activity only if no other contacts connected
2298 if ( ! $activityContactOther->find(TRUE) ) {
2299 $activityParams = array('id' => $activityContact->activity_id
);
2300 $result = self
::deleteActivity($activityParams);
2303 $activityContactOther->free();
2306 $activityContact->free();
2307 $transaction->commit();
2313 * Does user has sufficient permission for view/edit activity record.
2315 * @param int $activityId activity record id.
2316 * @param int $action edit/view
2318 * @return boolean $allow true/false
2321 public static function checkPermission($activityId, $action) {
2324 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2329 $activity = new CRM_Activity_DAO_Activity();
2330 $activity->id
= $activityId;
2331 if (!$activity->find(TRUE)) {
2335 //component related permissions.
2336 $compPermissions = array(
2337 'CiviCase' => array('administer CiviCase',
2338 'access my cases and activities',
2339 'access all cases and activities',
2341 'CiviMail' => array('access CiviMail'),
2342 'CiviEvent' => array('access CiviEvent'),
2343 'CiviGrant' => array('access CiviGrant'),
2344 'CiviPledge' => array('access CiviPledge'),
2345 'CiviMember' => array('access CiviMember'),
2346 'CiviReport' => array('access CiviReport'),
2347 'CiviContribute' => array('access CiviContribute'),
2348 'CiviCampaign' => array('administer CiviCampaign'),
2351 //return early when it is case activity.
2352 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2353 //check for civicase related permission.
2354 if ($isCaseActivity) {
2356 foreach ($compPermissions['CiviCase'] as $per) {
2357 if (CRM_Core_Permission
::check($per)) {
2363 //check for case specific permissions.
2366 if ($action == CRM_Core_Action
::UPDATE
) {
2369 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2371 $activity->activity_type_id
2378 //first check the component permission.
2381 FROM civicrm_option_value val
2382 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2383 WHERE val.value = %2";
2384 $params = array(1 => array('activity_type', 'String'),
2385 2 => array($activity->activity_type_id
, 'Integer'),
2387 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2390 $componentName = CRM_Core_Component
::getComponentName($componentId);
2391 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2393 //here we are interesting in any single permission.
2394 if (is_array($compPermission)) {
2395 foreach ($compPermission as $per) {
2396 if (CRM_Core_Permission
::check($per)) {
2404 //check for this permission related to contact.
2405 $permission = CRM_Core_Permission
::VIEW
;
2406 if ($action == CRM_Core_Action
::UPDATE
) {
2407 $permission = CRM_Core_Permission
::EDIT
;
2410 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2411 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2412 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2413 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2415 //check for source contact.
2416 if (!$componentId ||
$allow) {
2417 $sourceContactId = self
::getActivityContact($activity->id
, $sourceID);
2418 //account for possibility of activity not having a source contact (as it may have been deleted)
2419 if ( $sourceContactId ) {
2420 $allow = CRM_Contact_BAO_Contact_Permission
::allow($sourceContactId, $permission);
2424 //check for target and assignee contacts.
2426 //first check for supper permission.
2427 $supPermission = 'view all contacts';
2428 if ($action == CRM_Core_Action
::UPDATE
) {
2429 $supPermission = 'edit all contacts';
2431 $allow = CRM_Core_Permission
::check($supPermission);
2433 //user might have sufficient permission, through acls.
2436 //get the target contacts.
2437 $targetContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $targetID);
2438 foreach ($targetContacts as $cnt => $contactId) {
2439 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2445 //get the assignee contacts.
2447 $assigneeContacts = CRM_Activity_BAO_ActivityContact
::retrieveContactIdsByActivityId($activity->id
, $assigneeID);
2448 foreach ($assigneeContacts as $cnt => $contactId) {
2449 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2462 * This function is a wrapper for ajax activity selector
2464 * @param array $params associated array for params record id.
2466 * @return array $contactActivities associated array of contact activities
2469 public static function getContactActivitySelector(&$params) {
2470 // format the params
2471 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2472 $params['rowCount'] = $params['rp'];
2473 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2474 $params['caseId'] = NULL;
2475 $context = CRM_Utils_Array
::value('context', $params);
2477 // get contact activities
2478 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2481 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2483 // format params and add links
2484 $contactActivities = array();
2486 if (!empty($activities)) {
2487 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2489 // check logged in user for permission
2490 $page = new CRM_Core_Page();
2491 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2492 $permissions = array($page->_permission
);
2493 if (CRM_Core_Permission
::check('delete activities')) {
2494 $permissions[] = CRM_Core_Permission
::DELETE
;
2497 $mask = CRM_Core_Action
::mask($permissions);
2499 foreach ($activities as $activityId => $values) {
2500 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2501 $contactActivities[$activityId]['subject'] = $values['subject'];
2502 if ($params['contact_id'] == $values['source_contact_id']) {
2503 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2505 elseif ($values['source_contact_id']) {
2506 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'],
2507 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2510 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2513 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2514 $contactActivities[$activityId]['target_contact'] = CRM_Utils_System
::href($values['recipients'],
2515 'civicrm/mailing/report/event',
2516 "mid={$values['source_record_id']}&reset=1&event=queue&cid={$params['contact_id']}&context=activitySelector");
2518 elseif (!empty($values['recipients'])) {
2519 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2521 elseif (isset($values['target_contact_counter']) && $values['target_contact_counter']) {
2522 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2523 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName,
2524 'civicrm/contact/view', "reset=1&cid={$tcID}");
2527 if ($extraCount = $values['target_contact_counter'] - 1) {
2528 $contactActivities[$activityId]['target_contact'] .= ";<br />" . "(" . ts('%1 more', array(1 => $extraCount)) . ")";
2531 elseif (!$values['target_contact_name']) {
2532 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2535 if (empty($values['assignee_contact_name'])) {
2536 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2538 elseif (!empty($values['assignee_contact_name'])) {
2540 $contactActivities[$activityId]['assignee_contact'] = '';
2541 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2542 if ($acID && $count < 5) {
2543 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2546 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2550 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2557 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2558 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2560 // add class to this row if overdue
2561 $contactActivities[$activityId]['class'] = '';
2562 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2563 && CRM_Utils_Array
::value('status_id', $values) == 1
2565 $contactActivities[$activityId]['class'] = 'status-overdue';
2568 $contactActivities[$activityId]['class'] = 'status-ontime';
2572 $contactActivities[$activityId]['links'] = '';
2573 $accessMailingReport = FALSE;
2574 if (!empty($values['mailingId'])) {
2575 $accessMailingReport = TRUE;
2578 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2579 CRM_Utils_Array
::value('activity_type_id', $values),
2580 CRM_Utils_Array
::value('source_record_id', $values),
2581 $accessMailingReport,
2582 CRM_Utils_Array
::value('activity_id', $values)
2585 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2587 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2590 'id' => $values['activity_id'],
2591 'cid' => $params['contact_id'],
2593 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2599 $values['activity_id']
2604 return $contactActivities;
2608 * Used to copy custom fields and attachments from an existing activity to another.
2609 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2614 static function copyExtendedActivityData($params) {
2615 // attach custom data to the new activity
2616 $customParams = $htmlType = array();
2617 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2619 if (!empty($customValues)) {
2620 $fieldIds = implode(', ', array_keys($customValues));
2621 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2622 $result = CRM_Core_DAO
::executeQuery($sql);
2624 while ($result->fetch()) {
2625 $htmlType[] = $result->id
;
2628 foreach ($customValues as $key => $value) {
2629 if ($value !== NULL) { // CRM-10542
2630 if (in_array($key, $htmlType)) {
2631 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2632 $customParams["custom_{$key}_-1"] = array(
2633 'name' => $fileValues[0],
2634 'path' => $fileValues[1],
2638 $customParams["custom_{$key}_-1"] = $value;
2642 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2643 $params['mainActivityId'], 'Activity'
2647 // copy activity attachments ( if any )
2648 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);
2652 * @param $activityId
2653 * @param null $recordTypeID
2654 * @param string $column
2658 public static function getActivityContact($activityId, $recordTypeID = NULL, $column = 'contact_id') {
2659 $activityContact = new CRM_Activity_BAO_ActivityContact();
2660 $activityContact->activity_id
= $activityId;
2661 if ($recordTypeID) {
2662 $activityContact->record_type_id
= $recordTypeID;
2664 if ($activityContact->find(TRUE)) {
2665 return $activityContact->$column;
2671 * @param $activityId
2675 public static function getSourceContactID($activityId) {
2676 static $sourceID = NULL;
2678 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2679 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2682 return self
::getActivityContact($activityId, $sourceID);
2688 function setApiFilter(&$params) {
2689 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2691 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2692 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2693 $obj = new CRM_Activity_BAO_ActivityContact();
2694 $params['return.target_contact_id'] = 1;
2695 $this->joinAdd($obj, 'LEFT');
2696 $this->selectAdd('civicrm_activity.*');
2697 $this->whereAdd(" civicrm_activity_contact.contact_id = {$params['target_contact_id']} AND civicrm_activity_contact.record_type_id = {$targetID}");