3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class is for activity functions
40 class CRM_Activity_BAO_Activity
extends CRM_Activity_DAO_Activity
{
43 * static field for all the activity information that we can potentially export
48 static $_exportableFields = NULL;
51 * static field for all the activity information that we can potentially import
56 static $_importableFields = NULL;
59 * Check if there is absolute minimum of data to add the object
61 * @param array $params (reference ) an assoc array of name/value pairs
66 public static function dataExists(&$params) {
67 if (CRM_Utils_Array
::value('source_contact_id', $params) ||
68 CRM_Utils_Array
::value('id', $params)
76 * Takes a bunch of params that are needed to match certain criteria and
77 * retrieves the relevant objects. Typically the valid params are only
78 * contact_id. We'll tweak this function to be more full featured over a period
79 * of time. This is the inverse function of create. It also stores all the retrieved
80 * values in the default array
82 * @param array $params (reference ) an assoc array of name/value pairs
83 * @param array $defaults (reference ) an assoc array to hold the flattened values
84 * @param string $activityType activity type
86 * @return object CRM_Core_BAO_Meeting object
89 public static function retrieve(&$params, &$defaults) {
90 $activity = new CRM_Activity_DAO_Activity();
91 $activity->copyValues($params);
93 if ($activity->find(TRUE)) {
94 // TODO: at some stage we'll have to deal
95 // TODO: with multiple values for assignees and targets, but
96 // TODO: for now, let's just fetch first row
97 $defaults['assignee_contact'] = CRM_Activity_BAO_ActivityAssignment
::retrieveAssigneeIdsByActivityId($activity->id
);
98 $assignee_contact_names = CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames($activity->id
);
100 $defaults['assignee_contact_value'] = implode('; ', $assignee_contact_names);
102 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Bulk Email', 'name')) {
103 $defaults['target_contact'] = CRM_Activity_BAO_ActivityTarget
::retrieveTargetIdsByActivityId($activity->id
);
104 $target_contact_names = CRM_Activity_BAO_ActivityTarget
::getTargetNames($activity->id
);
106 $defaults['target_contact_value'] = implode('; ', $target_contact_names);
108 elseif (CRM_Core_Permission
::check('access CiviMail') ||
109 (CRM_Mailing_Info
::workflowEnabled() &&
110 CRM_Core_Permission
::check('create mailings')
113 $defaults['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
114 "mid={$activity->source_record_id}&reset=1&atype={$activity->activity_type_id}&aid={$activity->id}&cid={$activity->source_contact_id}&context=activity"
118 $defaults['target_contact_value'] = ts('(recipients)');
121 if ($activity->source_contact_id
&&
122 !CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
123 $activity->source_contact_id
,
127 $defaults['source_contact'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
128 $activity->source_contact_id
,
134 $defaults['case_subject'] = CRM_Case_BAO_Case
::getCaseSubject($activity->id
);
136 CRM_Core_DAO
::storeValues($activity, $defaults);
144 * Function to delete the activity
146 * @param array $params associated array
152 public static function deleteActivity(&$params, $moveToTrash = FALSE) {
154 if (CRM_Utils_Array
::value('id', $params) && !is_array($params['id'])) {
155 CRM_Utils_Hook
::pre('delete', 'Activity', $params['id'], $params);
158 CRM_Utils_Hook
::pre('delete', 'Activity', NULL, $params);
161 $transaction = new CRM_Core_Transaction();
162 if (is_array(CRM_Utils_Array
::value('source_record_id', $params))) {
163 $sourceRecordIds = implode(',', $params['source_record_id']);
166 $sourceRecordIds = CRM_Utils_Array
::value('source_record_id', $params);
171 if (!isset($params['id'])) {
172 if (is_array($params['activity_type_id'])) {
173 $activityTypes = implode(',', $params['activity_type_id']);
176 $activityTypes = $params['activity_type_id'];
179 $query = "DELETE FROM civicrm_activity WHERE source_record_id IN ({$sourceRecordIds}) AND activity_type_id IN ( {$activityTypes} )";
180 $dao = CRM_Core_DAO
::executeQuery($query);
183 $activity = new CRM_Activity_DAO_Activity();
184 $activity->copyValues($params);
185 $result = $activity->delete();
188 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
192 $activity = new CRM_Activity_DAO_Activity();
193 $activity->copyValues($params);
195 $activity->is_deleted
= 1;
196 $result = $activity->save();
198 //log activty delete.CRM-4525.
199 $logMsg = 'Case Activity deleted for';
201 $sourceContactId = CRM_Core_DAO
::getfieldValue('CRM_Activity_DAO_Activity',
202 $activity->id
, 'source_contact_id'
204 if ($sourceContactId) {
205 $msgs[] = " source={$sourceContactId}";
207 //get target contacts.
208 $targetContactIds = CRM_Activity_BAO_ActivityTarget
::getTargetNames($activity->id
);
209 if (!empty($targetContactIds)) {
210 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
212 //get assignee contacts.
213 $assigneeContactIds = CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames($activity->id
);
214 if (!empty($assigneeContactIds)) {
215 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
218 $logMsg .= implode(', ', $msgs);
220 self
::logActivityAction($activity, $logMsg);
223 // delete the recently created Activity
225 $activityRecent = array(
226 'id' => $activity->id
,
227 'type' => 'Activity',
229 CRM_Utils_Recent
::del($activityRecent);
232 $transaction->commit();
233 if (isset($activity)) {
235 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
236 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
243 * Delete activity assignment record
245 * @param int $id activity id
250 public static function deleteActivityAssignment($activityId) {
251 $assignment = new CRM_Activity_BAO_ActivityAssignment();
252 $assignment->activity_id
= $activityId;
253 $assignment->delete();
257 * Delete activity target record
259 * @param int $id activity id
264 public static function deleteActivityTarget($activityId) {
265 $target = new CRM_Activity_BAO_ActivityTarget();
266 $target->activity_id
= $activityId;
271 * Create activity target record
273 * @param array activity_id, target_contact_id
278 static function createActivityTarget($params) {
279 if (!$params['target_contact_id']) {
283 $target = new CRM_Activity_BAO_ActivityTarget();
284 $target->activity_id
= $params['activity_id'];
285 $target->target_contact_id
= $params['target_contact_id'];
286 // avoid duplicate entries, CRM-7484
287 // happens if sending email to the same contact with different email addresses
288 if (!$target->find(TRUE)) {
294 * Create activity assignment record
296 * @param array activity_id, assignee_contact_id
301 static function createActivityAssignment($params) {
302 if (!$params['assignee_contact_id']) {
305 $assignee = new CRM_Activity_BAO_ActivityAssignment();
306 $assignee->activity_id
= $params['activity_id'];
307 $assignee->assignee_contact_id
= $params['assignee_contact_id'];
312 * Function to process the activities
314 * @param object $form form object
315 * @param array $params associated array of the submitted values
316 * @param array $ids array of ids
317 * @param string $activityType activity Type
318 * @param boolean $record true if it is Record Activity
323 public static function create(&$params) {
324 // check required params
325 if (!self
::dataExists($params)) {
326 CRM_Core_Error
::fatal('Not enough data to create activity object,');
329 $activity = new CRM_Activity_DAO_Activity();
331 if (isset($params['id']) && empty($params['id'])) {
332 unset($params['id']);
335 if (!CRM_Utils_Array
::value('status_id', $params) &&
336 !CRM_Utils_Array
::value('activity_status_id', $params) &&
337 !CRM_Utils_Array
::value('id', $params)
339 if (isset($params['activity_date_time']) &&
340 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
342 $params['status_id'] = 2;
345 $params['status_id'] = 1;
349 //set priority to Normal for Auto-populated activities (for Cases)
350 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
351 // if not set and not 0
352 !CRM_Utils_Array
::value('id', $params)
354 $priority = CRM_Core_PseudoConstant
::priority();
355 $params['priority_id'] = array_search('Normal', $priority);
358 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
359 $params['target_contact_id'] = array_unique($params['target_contact_id']);
361 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
362 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
366 if (CRM_Utils_Array
::value('id', $params)) {
367 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
370 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
373 $activity->copyValues($params);
374 if (isset($params['case_id'])) {
375 // CRM-8708, preserve case ID even though it's not part of the SQL model
376 $activity->case_id
= $params['case_id'];
378 elseif (is_numeric($activity->id
)) {
379 // CRM-8708, preserve case ID even though it's not part of the SQL model
380 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
384 $transaction = new CRM_Core_Transaction();
386 $result = $activity->save();
388 if (is_a($result, 'CRM_Core_Error')) {
389 $transaction->rollback();
393 $activityId = $activity->id
;
395 // check and attach and files as needed
396 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
398 // attempt to save activity assignment
399 $resultAssignment = NULL;
400 if (CRM_Utils_Array
::value('assignee_contact_id', $params)) {
402 $assignmentParams = array('activity_id' => $activityId);
404 if (is_array($params['assignee_contact_id'])) {
405 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
406 // first delete existing assignments if any
407 self
::deleteActivityAssignment($activityId);
411 foreach ($params['assignee_contact_id'] as $acID) {
413 $values[] = "( $activityId, $acID )";
416 while (!empty($values)) {
417 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
418 $str = implode(',', $input);
419 $sql = "INSERT IGNORE INTO civicrm_activity_assignment ( activity_id, assignee_contact_id ) VALUES $str;";
420 CRM_Core_DAO
::executeQuery($sql);
424 $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
426 if (CRM_Utils_Array
::value('id', $params)) {
427 $assignment = new CRM_Activity_BAO_ActivityAssignment();
428 $assignment->activity_id
= $activityId;
429 $assignment->find(TRUE);
431 if ($assignment->assignee_contact_id
!= $params['assignee_contact_id']) {
432 $assignmentParams['id'] = $assignment->id
;
433 $resultAssignment = CRM_Activity_BAO_ActivityAssignment
::create($assignmentParams);
437 $resultAssignment = CRM_Activity_BAO_ActivityAssignment
::create($assignmentParams);
442 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
443 self
::deleteActivityAssignment($activityId);
447 if (is_a($resultAssignment, 'CRM_Core_Error')) {
448 $transaction->rollback();
449 return $resultAssignment;
452 // attempt to save activity targets
453 $resultTarget = NULL;
454 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
456 $targetParams = array('activity_id' => $activityId);
457 $resultTarget = array();
458 if (is_array($params['target_contact_id'])) {
459 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
460 // first delete existing targets if any
461 self
::deleteActivityTarget($activityId);
465 foreach ($params['target_contact_id'] as $tid) {
467 $values[] = "( $activityId, $tid )";
471 while (!empty($values)) {
472 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
473 $str = implode(',', $input);
474 $sql = "INSERT IGNORE INTO civicrm_activity_target ( activity_id, target_contact_id ) VALUES $str;";
475 CRM_Core_DAO
::executeQuery($sql);
479 $targetParams['target_contact_id'] = $params['target_contact_id'];
481 if (CRM_Utils_Array
::value('id', $params)) {
482 $target = new CRM_Activity_BAO_ActivityTarget();
483 $target->activity_id
= $activityId;
486 if ($target->target_contact_id
!= $params['target_contact_id']) {
487 $targetParams['id'] = $target->id
;
488 $resultTarget = CRM_Activity_BAO_ActivityTarget
::create($targetParams);
492 $resultTarget = CRM_Activity_BAO_ActivityTarget
::create($targetParams);
497 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
498 self
::deleteActivityTarget($activityId);
502 // write to changelog before transation is committed/rolled
503 // back (and prepare status to display)
504 if (CRM_Utils_Array
::value('id', $params)) {
505 $logMsg = "Activity (id: {$result->id} ) updated with ";
508 $logMsg = "Activity created for ";
512 if (isset($params['source_contact_id'])) {
513 $msgs[] = "source={$params['source_contact_id']}";
516 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
517 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
518 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
519 // take only first target
520 // will be used for recently viewed display
521 $t = array_slice($params['target_contact_id'], 0, 1);
522 $recentContactId = $t[0];
524 elseif (isset($params['target_contact_id'])) {
525 $msgs[] = "target={$params['target_contact_id']}";
526 // will be used for recently viewed display
527 $recentContactId = $params['target_contact_id'];
531 // at worst, take source for recently viewed display
532 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
535 if (isset($params['assignee_contact_id'])) {
536 if (is_array($params['assignee_contact_id'])) {
537 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
540 $msgs[] = "assignee={$params['assignee_contact_id']}";
543 $logMsg .= implode(', ', $msgs);
545 self
::logActivityAction($result, $logMsg);
547 if (CRM_Utils_Array
::value('custom', $params) &&
548 is_array($params['custom'])
550 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
553 $transaction->commit();
554 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
555 $recentOther = array();
556 if (CRM_Utils_Array
::value('case_id', $params)) {
557 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
558 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
559 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
563 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
564 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
565 $url = CRM_Utils_System
::url('civicrm/activity', $q);
566 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
567 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
568 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
572 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
573 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
577 if (CRM_Core_Permission
::check("delete activities")) {
578 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
579 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
584 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
585 if (CRM_Core_Permission
::check('delete activities')) {
586 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
587 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
593 if (!isset($activity->parent_id
)) {
594 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
595 // add the recently created Activity
596 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
597 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
600 if (isset($activitySubject)) {
601 $title = $activitySubject . ' - ';
604 $title = $title . $recentContactDisplay;
605 if (CRM_Utils_Array
::value($activity->activity_type_id
, $activityTypes)) {
606 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
609 CRM_Utils_Recent
::add($title,
614 $recentContactDisplay,
620 // reset the group contact cache since smart groups might be affected due to this
621 CRM_Contact_BAO_GroupContactCache
::remove();
623 if (CRM_Utils_Array
::value('id', $params)) {
624 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
627 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
630 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
632 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
633 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
635 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
637 'activity_id' => $activity->id
,
638 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
640 if ($caseParams['case_id']) {
641 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
644 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
651 public static function logActivityAction($activity, $logMessage = NULL) {
652 $session = CRM_Core_Session
::singleton();
653 $id = $session->get('userID');
655 $id = $activity->source_contact_id
;
658 'entity_table' => 'civicrm_activity',
659 'entity_id' => $activity->id
,
660 'modified_id' => $id,
661 'modified_date' => date('YmdHis'),
662 'data' => $logMessage,
664 CRM_Core_BAO_Log
::add($logParams);
669 * function to get the list Actvities
671 * @param array $input array of parameters
673 * - contact_id int contact_id whose activties we want to retrieve
674 * - offset int which row to start from ?
675 * - rowCount int how many rows to fetch
676 * - sort object|array object or array describing sort order for sql query.
677 * - admin boolean if contact is admin
678 * - caseId int case ID
679 * - context string page on which selector is build
680 * - activity_type_id int|string the activitiy types we want to restrict by
682 * @return array (reference) $values the relevant data object values of open activitie
687 static function &getActivities($input) {
688 //step 1: Get the basic activity data
689 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
694 $config = CRM_Core_Config
::singleton();
696 $randomNum = md5(uniqid());
697 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
699 $tableFields = array(
700 'activity_id' => 'int unsigned',
701 'activity_date_time' => 'datetime',
702 'status_id' => 'int unsigned',
703 'subject' => 'varchar(255)',
704 'source_contact_id' => 'int unsigned',
705 'source_record_id' => 'int unsigned',
706 'source_contact_name' => 'varchar(255)',
707 'activity_type_id' => 'int unsigned',
708 'activity_type' => 'varchar(128)',
709 'case_id' => 'int unsigned',
710 'case_subject' => 'varchar(255)',
711 'campaign_id' => 'int unsigned',
714 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
715 $insertValueSQL = array();
716 foreach ($tableFields as $name => $desc) {
717 $sql .= "$name $desc,\n";
718 $insertValueSQL[] = $name;
722 PRIMARY KEY ( activity_id )
723 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
726 CRM_Core_DAO
::executeQuery($sql);
728 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
730 $order = $limit = $groupBy = '';
731 //$groupBy = " GROUP BY tbl.activity_id";
733 if (!empty($input['sort'])) {
734 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
735 $orderBy = $input['sort']->orderBy();
736 if (!empty($orderBy)) {
737 $order = " ORDER BY $orderBy";
740 elseif (trim($input['sort'])) {
741 $order = " ORDER BY {$input['sort']}";
746 $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 ";
749 if (!empty($input['rowCount']) &&
750 $input['rowCount'] > 0
752 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
755 $input['count'] = FALSE;
756 list($sqlClause, $params) = self
::getActivitySQLClause($input);
758 $query = "{$insertSQL}
759 SELECT DISTINCT tbl.* from ( {$sqlClause} )
762 //filter case activities - CRM-5761
763 $components = self
::activityComponents();
764 if (!in_array('CiviCase', $components)) {
766 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
767 WHERE civicrm_case_activity.id IS NULL";
770 $query = $query . $groupBy . $order . $limit;
772 $dao = CRM_Core_DAO
::executeQuery($query, $params);
774 $notbulkActivityClause = '';
775 if ($bulkActivityTypeID) {
776 $notbulkActivityClause = " AND {$activityTempTable}.activity_type_id <> {$bulkActivityTypeID} ";
779 // step 2: Get target and assignee contacts for above activities
780 // create temp table for target contacts
781 $activityTargetContactTempTable = "civicrm_temp_target_contact_{$randomNum}";
782 $query = "CREATE TEMPORARY TABLE {$activityTargetContactTempTable} (
783 activity_id int unsigned, target_contact_id int unsigned, target_contact_name varchar(255) )
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
789 $query = "INSERT INTO {$activityTargetContactTempTable} ( activity_id, target_contact_id, target_contact_name )
790 SELECT at.activity_id,
791 at.target_contact_id ,
793 FROM civicrm_activity_target at
794 INNER JOIN {$activityTempTable} ON ( at.activity_id = {$activityTempTable}.activity_id
795 {$notbulkActivityClause} )
796 INNER JOIN civicrm_contact c ON c.id = at.target_contact_id
797 WHERE c.is_deleted = 0";
799 CRM_Core_DAO
::executeQuery($query);
801 // create temp table for assignee contacts
802 $activityAssigneetContactTempTable = "civicrm_temp_assignee_contact_{$randomNum}";
803 $query = "CREATE TEMPORARY TABLE {$activityAssigneetContactTempTable} (
804 activity_id int unsigned, assignee_contact_id int unsigned, assignee_contact_name varchar(255) )
805 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
807 CRM_Core_DAO
::executeQuery($query);
809 // note that we ignore bulk email for assignee, since we don't show it in selector
810 $query = "INSERT INTO {$activityAssigneetContactTempTable} ( activity_id, assignee_contact_id, assignee_contact_name )
811 SELECT DISTINCT ( aa.activity_id ) ,
812 aa.assignee_contact_id,
814 FROM civicrm_activity_assignment aa
815 INNER JOIN {$activityTempTable} ON ( aa.activity_id = {$activityTempTable}.activity_id
816 {$notbulkActivityClause} )
817 INNER JOIN civicrm_contact c ON c.id = aa.assignee_contact_id
818 WHERE c.is_deleted = 0";
820 CRM_Core_DAO
::executeQuery($query);
822 // step 3: Combine all temp tables to get final query for activity selector
824 SELECT {$activityTempTable}.*,
825 {$activityTargetContactTempTable}.target_contact_id,{$activityTargetContactTempTable}.target_contact_name,
826 {$activityAssigneetContactTempTable}.assignee_contact_id, {$activityAssigneetContactTempTable}.assignee_contact_name
827 FROM {$activityTempTable}
828 LEFT JOIN {$activityTargetContactTempTable} on {$activityTempTable}.activity_id = {$activityTargetContactTempTable}.activity_id
829 LEFT JOIN {$activityAssigneetContactTempTable} on {$activityTempTable}.activity_id = {$activityAssigneetContactTempTable}.activity_id
833 $dao = CRM_Core_DAO
::executeQuery($query);
835 //CRM-3553, need to check user has access to target groups.
836 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
838 (CRM_Core_Permission
::check('access CiviMail')) ||
839 (CRM_Mailing_Info
::workflowEnabled() &&
840 CRM_Core_Permission
::check('create mailings'))
844 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
847 while ($dao->fetch()) {
848 $activityID = $dao->activity_id
;
849 $values[$activityID]['activity_id'] = $dao->activity_id
;
850 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
851 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
852 $values[$activityID]['activity_type'] = $dao->activity_type
;
853 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
854 $values[$activityID]['status_id'] = $dao->status_id
;
855 $values[$activityID]['subject'] = $dao->subject
;
856 $values[$activityID]['source_contact_name'] = $dao->source_contact_name
;
857 $values[$activityID]['source_contact_id'] = $dao->source_contact_id
;
858 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
860 if ($dao->campaign_id
) {
861 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
864 if (!CRM_Utils_Array
::value('assignee_contact_name', $values[$activityID])) {
865 $values[$activityID]['assignee_contact_name'] = array();
868 if (!CRM_Utils_Array
::value('target_contact_name', $values[$activityID])) {
869 $values[$activityID]['target_contact_name'] = array();
872 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
873 // build array of target / assignee names
874 if ($dao->target_contact_id
) {
875 $values[$activityID]['target_contact_name'][$dao->target_contact_id
] = $dao->target_contact_name
;
877 if ($dao->assignee_contact_id
) {
878 $values[$activityID]['assignee_contact_name'][$dao->assignee_contact_id
] = $dao->assignee_contact_name
;
881 // case related fields
882 $values[$activityID]['case_id'] = $dao->case_id
;
883 $values[$activityID]['case_subject'] = $dao->case_subject
;
886 $values[$activityID]['recipients'] = ts('(recipients)');
887 $values[$activityID]['mailingId'] = '';
890 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
892 $values[$activityID]['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
893 "mid={$dao->source_record_id}&reset=1&cid={$dao->source_contact_id}&context=activitySelector"
899 // add info on whether the related contacts are deleted (CRM-5673)
900 // FIXME: ideally this should be tied to ACLs
902 // grab all the related contact ids
904 foreach ($values as $value) {
905 $cids[] = $value['source_contact_id'];
907 $cids = array_filter(array_unique($cids));
909 // see which of the cids are of deleted contacts
911 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
912 $dao = CRM_Core_DAO
::executeQuery($sql);
914 while ($dao->fetch()) {
918 // hide the deleted contacts
919 foreach ($values as & $value) {
920 if (in_array($value['source_contact_id'], $dels)) {
921 unset($value['source_contact_id'], $value['source_contact_name']);
930 * Get the component id and name those are enabled and logged in
931 * user has permission. To decide whether we are going to include
932 * component related activities w/ core activity retrieve process.
934 * return an array of component id and name.
937 static function activityComponents() {
938 $components = array();
939 $compInfo = CRM_Core_Component
::getEnabledComponents();
940 foreach ($compInfo as $compObj) {
941 if (CRM_Utils_Array
::value('showActivitiesInCore', $compObj->info
)) {
942 if ($compObj->info
['name'] == 'CiviCampaign') {
943 $componentPermission = "administer {$compObj->name}";
946 $componentPermission = "access {$compObj->name}";
948 if ($compObj->info
['name'] == 'CiviCase') {
949 if (CRM_Case_BAO_Case
::accessCiviCase()) {
950 $components[$compObj->componentID
] = $compObj->info
['name'];
953 elseif (CRM_Core_Permission
::check($componentPermission)) {
954 $components[$compObj->componentID
] = $compObj->info
['name'];
963 * function to get the activity Count
965 * @param array $input array of parameters
967 * - contact_id int contact_id whose activties we want to retrieve
968 * - admin boolean if contact is admin
969 * - caseId int case ID
970 * - context string page on which selector is build
971 * - activity_type_id int|string the activitiy types we want to restrict by
973 * @return int count of activities
978 static function &getActivitiesCount($input) {
979 $input['count'] = TRUE;
980 list($sqlClause, $params) = self
::getActivitySQLClause($input);
982 //filter case activities - CRM-5761
983 $components = self
::activityComponents();
984 if (!in_array('CiviCase', $components)) {
986 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
987 FROM ( {$sqlClause} ) as tbl
988 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
989 WHERE civicrm_case_activity.id IS NULL";
992 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
995 return CRM_Core_DAO
::singleValueQuery($query, $params);
999 * function to get the activity sql clause to pick activities
1001 * @param array $input array of parameters
1003 * - contact_id int contact_id whose activties we want to retrieve
1004 * - admin boolean if contact is admin
1005 * - caseId int case ID
1006 * - context string page on which selector is build
1007 * - count boolean are we interested in the count clause only?
1008 * - activity_type_id int|string the activitiy types we want to restrict by
1010 * @return int count of activities
1015 static function getActivitySQLClause($input) {
1017 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
1019 $config = CRM_Core_Config
::singleton();
1020 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
1021 $sourceWhere = ' source_contact_id = %1 ';
1022 $targetWhere = ' at.target_contact_id = %1 ';
1023 $assigneeWhere = ' aa.assignee_contact_id = %1 ';
1024 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
1026 $params = array(1 => array($input['contact_id'], 'Integer'));
1029 $commonClauses = array(
1030 "civicrm_option_group.name = 'activity_type'",
1031 "civicrm_activity.is_deleted = 0",
1032 "civicrm_activity.is_current_revision = 1",
1033 "civicrm_activity.is_test = 0",
1036 if ($input['context'] != 'activity') {
1037 $commonClauses[] = "civicrm_activity.status_id = 1";
1040 //Filter on component IDs.
1041 $components = self
::activityComponents();
1042 if (!empty($components)) {
1043 $componentsIn = implode(',', array_keys($components));
1044 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
1047 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
1050 // activity type ID clause
1051 if (!empty($input['activity_type_id'])) {
1052 if (is_array($input['activity_type_id'])) {
1053 foreach ($input['activity_type_id'] as $idx => $value) {
1054 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1056 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1059 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1060 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1064 // exclude by activity type clause
1065 if (!empty($input['activity_type_exclude_id'])) {
1066 if (is_array($input['activity_type_exclude_id'])) {
1067 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1068 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1070 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1073 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1074 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1078 $commonClause = implode(' AND ', $commonClauses);
1080 $includeCaseActivities = FALSE;
1081 if (in_array('CiviCase', $components)) {
1082 $includeCaseActivities = TRUE;
1086 // build main activity table select clause
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
1105 left join civicrm_contact sourceContact on
1106 source_contact_id = sourceContact.id ';
1110 SELECT civicrm_activity.id as activity_id
1112 from civicrm_activity
1113 left join civicrm_option_value on
1114 civicrm_activity.activity_type_id = civicrm_option_value.value
1115 left join civicrm_option_group on
1116 civicrm_option_group.id = civicrm_option_value.option_group_id
1123 // build target activity table select clause
1124 $targetAssigneeSelect = '';
1126 if (!$input['count']) {
1127 $targetAssigneeSelect = ',
1128 civicrm_activity.activity_date_time,
1129 civicrm_activity.status_id,
1130 civicrm_activity.subject,
1131 civicrm_activity.source_contact_id,
1132 civicrm_activity.source_record_id,
1133 sourceContact.sort_name as source_contact_name,
1134 civicrm_option_value.value as activity_type_id,
1135 civicrm_option_value.label as activity_type,
1136 null as case_id, null as case_subject,
1137 civicrm_activity.campaign_id as campaign_id
1142 SELECT civicrm_activity.id as activity_id
1143 {$targetAssigneeSelect}
1144 from civicrm_activity
1145 inner join civicrm_activity_target at on
1146 civicrm_activity.id = at.activity_id and {$targetWhere}
1147 left join civicrm_option_value on
1148 civicrm_activity.activity_type_id = civicrm_option_value.value
1149 left join civicrm_option_group on
1150 civicrm_option_group.id = civicrm_option_value.option_group_id
1157 // build assignee activity table select clause
1159 SELECT civicrm_activity.id as activity_id
1160 {$targetAssigneeSelect}
1161 from civicrm_activity
1162 inner join civicrm_activity_assignment aa on
1163 civicrm_activity.id = aa.activity_id and {$assigneeWhere}
1164 left join civicrm_option_value on
1165 civicrm_activity.activity_type_id = civicrm_option_value.value
1166 left join civicrm_option_group on
1167 civicrm_option_group.id = civicrm_option_value.option_group_id
1175 // Build case clause
1176 // or else exclude Inbound Emails that have been filed on a case.
1179 if ($includeCaseActivities) {
1181 if (!$input['count']) {
1183 civicrm_activity.activity_date_time,
1184 civicrm_activity.status_id,
1185 civicrm_activity.subject,
1186 civicrm_activity.source_contact_id,
1187 civicrm_activity.source_record_id,
1188 sourceContact.sort_name as source_contact_name,
1189 civicrm_option_value.value as activity_type_id,
1190 civicrm_option_value.label as activity_type,
1191 null as case_id, null as case_subject,
1192 civicrm_activity.campaign_id as campaign_id';
1198 SELECT civicrm_activity.id as activity_id
1200 from civicrm_activity
1201 inner join civicrm_case_activity on
1202 civicrm_case_activity.activity_id = civicrm_activity.id
1203 inner join civicrm_case on
1204 civicrm_case_activity.case_id = civicrm_case.id
1205 inner join civicrm_case_contact on
1206 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1207 left join civicrm_option_value on
1208 civicrm_activity.activity_type_id = civicrm_option_value.value
1209 left join civicrm_option_group on
1210 civicrm_option_group.id = civicrm_option_value.option_group_id
1215 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1216 ( civicrm_option_value.name <> 'Inbound Email' AND
1217 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1223 $returnClause = " {$sourceClause} union all {$targetClause} union all {$assigneeClause} {$caseClause} ";
1225 return array($returnClause, $params);
1229 * send the message to all the contacts and also insert a
1230 * contact activity in each contacts record
1232 * @param array $contactDetails the array of contact details to send the email
1233 * @param string $subject the subject of the message
1234 * @param string $message the message contents
1235 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1236 * @param int $userID use this userID if set
1237 * @param string $from
1238 * @param array $attachments the array of attachments if any
1239 * @param string $cc cc recepient
1240 * @param string $bcc bcc recepient
1241 * @param array $contactIds contact ids
1243 * @return array ( sent, activityId) if any email is sent and activityId
1247 static function sendEmail(
1255 $attachments = NULL,
1258 $contactIds // FIXME a param with no default shouldn't be last
1260 // get the contact details of logged in contact, which we set as from email
1261 if ($userID == NULL) {
1262 $session = CRM_Core_Session
::singleton();
1263 $userID = $session->get('userID');
1266 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1268 return array(count($contactDetails), 0, count($contactDetails));
1270 if (!trim($fromDisplayName)) {
1271 $fromDisplayName = $fromEmail;
1275 // token replacement of addressee/email/postal greetings
1276 // get the tokens added in subject and message
1277 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1278 $messageToken = CRM_Utils_Token
::getTokens($text);
1279 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1282 $from = "$fromDisplayName <$fromEmail>";
1285 //create the meta level record first ( email activity )
1286 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1291 // CRM-6265: save both text and HTML parts in details (if present)
1292 if ($html and $text) {
1293 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1296 $details = $html ?
$html : $text;
1299 $activityParams = array(
1300 'source_contact_id' => $userID,
1301 'activity_type_id' => $activityTypeID,
1302 'activity_date_time' => date('YmdHis'),
1303 'subject' => $subject,
1304 'details' => $details,
1305 // FIXME: check for name Completed and get ID from that lookup
1309 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1310 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1312 // add the attachments to activity params here
1314 // first process them
1315 $activityParams = array_merge($activityParams,
1320 $activity = self
::create($activityParams);
1322 // get the set of attachments from where they are stored
1323 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1326 $returnProperties = array();
1327 if (isset($messageToken['contact'])) {
1328 foreach ($messageToken['contact'] as $key => $value) {
1329 $returnProperties[$value] = 1;
1333 if (isset($subjectToken['contact'])) {
1334 foreach ($subjectToken['contact'] as $key => $value) {
1335 if (!isset($returnProperties[$value])) {
1336 $returnProperties[$value] = 1;
1342 // get token details for contacts, call only if tokens are used
1344 if (!empty($returnProperties)) {
1345 list($details) = CRM_Utils_Token
::getTokenDetails(
1350 'CRM_Activity_BAO_Activity'
1356 CRM_Utils_Hook
::tokens($tokens);
1357 $categories = array_keys($tokens);
1359 $escapeSmarty = FALSE;
1360 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1361 $smarty = CRM_Core_Smarty
::singleton();
1362 $escapeSmarty = TRUE;
1365 $sent = $notSent = array();
1366 foreach ($contactDetails as $values) {
1367 $contactId = $values['contact_id'];
1368 $emailAddress = $values['email'];
1370 if (!empty($details) && is_array($details["{$contactId}"])) {
1371 // unset email from details since it always returns primary email address
1372 unset($details["{$contactId}"]['email']);
1373 unset($details["{$contactId}"]['email_id']);
1374 $values = array_merge($values, $details["{$contactId}"]);
1377 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1378 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1381 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1382 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1383 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1389 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1390 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1391 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1397 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1398 // also add the contact tokens to the template
1399 $smarty->assign_by_ref('contact', $values);
1401 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1402 $tokenText = $smarty->fetch("string:$tokenText");
1403 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1407 if (self
::sendMessage(
1424 return array($sent, $activity->id
);
1427 static function sendSMS(&$contactDetails,
1429 &$smsParams = array(),
1433 if ($userID == NULL) {
1434 $session = CRM_Core_Session
::singleton();
1435 $userID = $session->get('userID');
1438 $text = &$activityParams['text_message'];
1439 $html = &$activityParams['html_message'];
1442 // token replacement of addressee/email/postal greetings
1443 // get the tokens added in subject and message
1444 $messageToken = CRM_Utils_Token
::getTokens($text);
1445 $messageToken = array_merge($messageToken,
1446 CRM_Utils_Token
::getTokens($html)
1449 //create the meta level record first ( sms activity )
1450 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1455 // CRM-6265: save both text and HTML parts in details (if present)
1456 if ($html and $text) {
1457 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1460 $details = $html ?
$html : $text;
1463 $activitySubject = $activityParams['activity_subject'];
1464 $activityParams = array(
1465 'source_contact_id' => $userID,
1466 'activity_type_id' => $activityTypeID,
1467 'activity_date_time' => date('YmdHis'),
1468 'subject' => $activitySubject,
1469 'details' => $details,
1470 // FIXME: check for name Completed and get ID from that lookup
1474 $activity = self
::create($activityParams);
1475 $activityID = $activity->id
;
1477 $returnProperties = array();
1479 if (isset($messageToken['contact'])) {
1480 foreach ($messageToken['contact'] as $key => $value) {
1481 $returnProperties[$value] = 1;
1487 CRM_Utils_Hook
::tokens($tokens);
1488 $categories = array_keys($tokens);
1490 // get token details for contacts, call only if tokens are used
1492 if (!empty($returnProperties) ||
!empty($tokens)) {
1493 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1497 'CRM_Activity_BAO_Activity'
1501 $escapeSmarty = $sent = FALSE;
1502 foreach ($contactDetails as $values) {
1503 $contactId = $values['contact_id'];
1505 if (!empty($details) && is_array($details["{$contactId}"])) {
1506 // unset email from details since it always returns primary email address
1507 unset($details["{$contactId}"]['email']);
1508 unset($details["{$contactId}"]['email_id']);
1509 $values = array_merge($values, $details["{$contactId}"]);
1512 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1513 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1515 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1516 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1518 // Only send if the phone is of type mobile
1519 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1520 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1521 $smsParams['To'] = $values['phone'];
1523 $smsParams['To'] = '';
1526 if (self
::sendSMSMessage($contactId,
1532 // even a single successful delivery should set this falg to true
1537 return array($sent, $activity->id
);
1541 * send the sms message to a specific contact
1543 * @param int $toID the contact id of the recipient
1544 * @param int $activityID the activity ID that tracks the message
1545 * @param array $smsParams the params used for sending sms
1547 * @return boolean true if successfull else false.
1551 static function sendSMSMessage($toID,
1554 $smsParams = array(),
1558 $toPhoneNumber = "";
1560 if ($smsParams['To']) {
1561 $toPhoneNumber = trim($smsParams['To']);
1564 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1565 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1566 //to get primary mobile ph,if not get a first mobile ph
1567 if (!empty($toPhoneNumbers)) {
1568 $toPhoneNumerDetails = reset($toPhoneNumbers);
1569 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1570 //contact allows to send sms
1575 // make sure both phone are valid
1576 // and that the recipient wants to receive sms
1577 if (empty($toPhoneNumber) or $toDoNotSms) {
1581 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1582 $recipient = $smsParams['To'];
1583 $smsParams['contact_id'] = $toID;
1584 $smsParams['parent_activity_id'] = $activityID;
1586 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1587 if (!$providerObj->send($recipient, $smsParams, $message, NULL)) {
1591 // add activity target record for every sms that is send
1592 $activityTargetParams = array(
1593 'activity_id' => $activityID,
1594 'target_contact_id' => $toID,
1596 self
::createActivityTarget($activityTargetParams);
1602 * send the message to a specific contact
1604 * @param string $from the name and email of the sender
1605 * @param int $toID the contact id of the recipient
1606 * @param string $subject the subject of the message
1607 * @param string $message the message contents
1608 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1609 * @param int $activityID the activity ID that tracks the message
1611 * @return boolean true if successfull else false.
1615 static function sendMessage($from,
1623 $attachments = NULL,
1627 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1628 if ($emailAddress) {
1629 $toEmail = trim($emailAddress);
1632 // make sure both email addresses are valid
1633 // and that the recipient wants to receive email
1634 if (empty($toEmail) or $toDoNotEmail) {
1637 if (!trim($toDisplayName)) {
1638 $toDisplayName = $toEmail;
1641 // create the params array
1642 $mailParams = array(
1643 'groupName' => 'Activity Email Sender',
1645 'toName' => $toDisplayName,
1646 'toEmail' => $toEmail,
1647 'subject' => $subject,
1650 'text' => $text_message,
1651 'html' => $html_message,
1652 'attachments' => $attachments,
1655 if (!CRM_Utils_Mail
::send($mailParams)) {
1659 // add activity target record for every mail that is send
1660 $activityTargetParams = array(
1661 'activity_id' => $activityID,
1662 'target_contact_id' => $toID,
1664 self
::createActivityTarget($activityTargetParams);
1669 * combine all the importable fields from the lower levels object
1671 * The ordering is important, since currently we do not have a weight
1672 * scheme. Adding weight is super important and should be done in the
1673 * next week or so, before this can be called complete.
1677 * @return array array of importable Fields
1681 static function &importableFields($status = FALSE) {
1682 if (!self
::$_importableFields) {
1683 if (!self
::$_importableFields) {
1684 self
::$_importableFields = array();
1687 $fields = array('' => array('title' => ts('- do not import -')));
1690 $fields = array('' => array('title' => ts('- Activity Fields -')));
1693 $tmpFields = CRM_Activity_DAO_Activity
::import();
1694 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1696 // Using new Dedupe rule.
1697 $ruleParams = array(
1698 'contact_type' => 'Individual',
1699 'used' => 'Unsupervised',
1701 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1703 $tmpConatctField = array();
1704 if (is_array($fieldsArray)) {
1705 foreach ($fieldsArray as $value) {
1706 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1711 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1712 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1713 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1716 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1717 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1718 $fields = array_merge($fields, $tmpConatctField);
1719 $fields = array_merge($fields, $tmpFields);
1720 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1721 self
::$_importableFields = $fields;
1723 return self
::$_importableFields;
1727 * To get the Activities of a target contact
1729 * @param $contactId Integer ContactId of the contact whose activities
1732 * @return array array of activity fields
1735 static function getContactActivity($contactId) {
1736 $activities = array();
1738 // First look for activities where contactId is one of the targets
1739 $query = "SELECT activity_id FROM civicrm_activity_target
1740 WHERE target_contact_id = $contactId";
1741 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1742 while ($dao->fetch()) {
1743 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1746 // Then get activities where contactId is an asignee
1747 $query = "SELECT activity_id FROM civicrm_activity_assignment
1748 WHERE assignee_contact_id = $contactId";
1749 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1750 while ($dao->fetch()) {
1751 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1754 // Then get activities that contactId created
1755 $query = "SELECT id AS activity_id FROM civicrm_activity
1756 WHERE source_contact_id = $contactId";
1757 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1758 while ($dao->fetch()) {
1759 $activities[$dao->activity_id
]['source_contact_id'][] = $contactId;
1761 $activityIds = array();
1762 // Then look up the activity details for each activity_id we saw above
1763 foreach ($activities as $activityId => $dummy) {
1764 $activityIds[] = $activityId;
1766 if (count($activityIds) < 1) {
1769 $activityIds = implode(',', $activityIds);
1770 $query = "SELECT activity.id as activity_id, source_contact_id, target_contact_id, assignee_contact_id, activity_type_id,
1771 subject, location, activity_date_time, details, status_id
1772 FROM civicrm_activity activity
1773 LEFT JOIN civicrm_activity_target target ON activity.id = target.activity_id
1774 LEFT JOIN civicrm_activity_assignment assignment ON activity.id = assignment.activity_id
1775 WHERE activity.id IN ($activityIds)";
1777 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
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
]['source_contact_id'] = $dao->source_contact_id
;
1784 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1785 if ($dao->target_contact_id
) {
1786 $activities[$dao->activity_id
]['targets'][$dao->target_contact_id
] = $dao->target_contact_id
;
1788 if (isset($dao->assignee_contact_id
)) {
1789 $activities[$dao->activity_id
]['asignees'][$dao->assignee_contact_id
] = $dao->assignee_contact_id
;
1791 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1792 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1793 $activities[$dao->activity_id
]['location'] = $dao->location
;
1794 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1795 $activities[$dao->activity_id
]['details'] = $dao->details
;
1796 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1797 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1798 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1804 * Function to add activity for Membership/Event/Contribution
1806 * @param object $activity (reference) perticular component object
1807 * @param string $activityType for Membership Signup or Renewal
1813 static function addActivity(&$activity,
1814 $activityType = 'Membership Signup',
1815 $targetContactID = NULL
1817 if ($activity->__table
== 'civicrm_membership') {
1818 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1820 if (!$membershipType) {
1821 $membershipType = ts('Membership');
1824 $subject = "{$membershipType}";
1826 if (!empty($activity->source
) && $activity->source
!= 'null') {
1827 $subject .= " - {$activity->source}";
1830 if ($activity->owner_membership_id
) {
1833 FROM civicrm_contact, civicrm_membership
1834 WHERE civicrm_contact.id = civicrm_membership.contact_id
1835 AND civicrm_membership.id = $activity->owner_membership_id
1837 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1838 $subject .= " (by {$displayName})";
1841 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1842 // CRM-72097 changed from start date to today
1843 $date = date('YmdHis');
1844 $component = 'Membership';
1846 elseif ($activity->__table
== 'civicrm_participant') {
1847 $event = CRM_Event_BAO_Event
::getEvents(TRUE, $activity->event_id
, TRUE, FALSE);
1849 $roles = CRM_Event_PseudoConstant
::participantRole();
1850 $status = CRM_Event_PseudoConstant
::participantStatus();
1852 $subject = $event[$activity->event_id
];
1853 if (CRM_Utils_Array
::value($activity->role_id
, $roles)) {
1854 $subject .= ' - ' . $roles[$activity->role_id
];
1856 if (CRM_Utils_Array
::value($activity->status_id
, $status)) {
1857 $subject .= ' - ' . $status[$activity->status_id
];
1859 $date = date('YmdHis');
1860 if ($activityType != 'Email') {
1861 $activityType = 'Event Registration';
1863 $component = 'Event';
1865 elseif ($activity->__table
== 'civicrm_contribution') {
1866 //create activity record only for Completed Contributions
1867 if ($activity->contribution_status_id
!= 1) {
1873 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1874 if (!empty($activity->source
) && $activity->source
!= 'null') {
1875 $subject .= " - {$activity->source}";
1877 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1878 $activityType = $component = 'Contribution';
1880 $activityParams = array(
1881 'source_contact_id' => $activity->contact_id
,
1882 'source_record_id' => $activity->id
,
1883 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1887 'subject' => $subject,
1888 'activity_date_time' => $date,
1889 'is_test' => $activity->is_test
,
1890 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1894 'skipRecentView' => TRUE,
1895 'campaign_id' => $activity->campaign_id
,
1898 // create activity with target contacts
1899 $session = CRM_Core_Session
::singleton();
1900 $id = $session->get('userID');
1902 $activityParams['source_contact_id'] = $id;
1903 $activityParams['target_contact_id'][] = $activity->contact_id
;
1907 if ($targetContactID) {
1908 $activityParams['target_contact_id'][] = $targetContactID;
1910 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1911 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1917 * Function to get Parent activity for currently viewd activity
1919 * @param int $activityId current activity id
1921 * @return int $parentId Id of parent acyivity otherwise false.
1924 static function getParentActivity($activityId) {
1925 static $parentActivities = array();
1927 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1929 if (!array_key_exists($activityId, $parentActivities)) {
1930 $parentActivities[$activityId] = array();
1932 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1937 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1940 return $parentActivities[$activityId];
1944 * Function to get total count of prior revision of currently viewd activity
1946 * @param int $activityId current activity id
1948 * @return int $params count of prior acyivities otherwise false.
1951 static function getPriorCount($activityID) {
1952 static $priorCounts = array();
1954 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1956 if (!array_key_exists($activityID, $priorCounts)) {
1957 $priorCounts[$activityID] = array();
1958 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1965 SELECT count( id ) AS cnt
1966 FROM civicrm_activity
1967 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1968 AND is_current_revision = 0
1969 AND id < {$activityID}
1971 $params = array(1 => array($originalID, 'Integer'));
1972 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1974 $priorCounts[$activityID] = $count ?
$count : 0;
1977 return $priorCounts[$activityID];
1981 * Function to get all prior activities of currently viewd activity
1983 * @param int $activityId current activity id
1985 * @return array $result prior acyivities info.
1988 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1989 static $priorActivities = array();
1991 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1992 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1994 if (!array_key_exists($index, $priorActivities)) {
1995 $priorActivities[$index] = array();
1997 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2003 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
2004 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
2005 WHERE (ca.id = %1 OR ca.original_id = %1)
2006 AND cl.entity_table = 'civicrm_activity'
2007 AND cl.entity_id = ca.id
2008 AND cl.modified_id = c.id
2010 if ($onlyPriorRevisions) {
2011 $query .= " AND ca.id < {$activityID}";
2013 $query .= " ORDER BY ca.id DESC";
2015 $params = array(1 => array($originalID, 'Integer'));
2016 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2018 while ($dao->fetch()) {
2019 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
2020 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
2021 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
2022 $priorActivities[$index][$dao->activityID
]['link'] = 'javascript:viewActivity( $dao->activityID );';
2027 return $priorActivities[$index];
2031 * Function to find the latest revision of a given activity
2033 * @param int $activityId prior activity id
2035 * @return int $params current activity id.
2038 static function getLatestActivityId($activityID) {
2039 static $latestActivityIds = array();
2041 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
2043 if (!array_key_exists($activityID, $latestActivityIds)) {
2044 $latestActivityIds[$activityID] = array();
2046 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
2051 $activityID = $originalID;
2053 $params = array(1 => array($activityID, 'Integer'));
2054 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
2056 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2059 return $latestActivityIds[$activityID];
2063 * Function to create a follow up a given activity
2065 * @activityId int activity id of parent activity
2067 * @param array $activity details
2071 static function createFollowupActivity($activityId, $params) {
2076 $session = CRM_Core_Session
::singleton();
2078 $followupParams = array();
2079 $followupParams['parent_id'] = $activityId;
2080 $followupParams['source_contact_id'] = $session->get('userID');
2081 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2083 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
2084 // Get Subject of Follow-up Activiity, CRM-4491
2085 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
2087 //create target contact for followup
2088 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
2089 $followupParams['target_contact_id'] = $params['target_contact_id'];
2092 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
2093 $params['followup_date_time']
2095 $followupActivity = self
::create($followupParams);
2097 return $followupActivity;
2101 * Function to get Activity specific File according activity type Id.
2103 * @param int $activityTypeId activity id
2105 * @return if file exists returns $activityTypeFile activity filename otherwise false.
2109 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
2110 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
2112 if ($activityTypes[$activityTypeId]['name']) {
2113 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2119 global $civicrm_root;
2120 $config = CRM_Core_Config
::singleton();
2121 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2122 if (empty($config->customPHPPathDir
)) {
2125 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2130 return $activityTypeFile;
2134 * Function to restore the activity
2136 * @param array $params associated array
2142 public static function restoreActivity(&$params) {
2143 $activity = new CRM_Activity_DAO_Activity();
2144 $activity->copyValues($params);
2146 $activity->is_deleted
= 0;
2147 $result = $activity->save();
2153 * Get the exportable fields for Activities
2155 * @param string $name if it is called by case $name = Case else $name = Activity
2157 * @return array array of exportable Fields
2161 static function &exportableFields($name = 'Activity') {
2162 if (!isset(self
::$_exportableFields[$name])) {
2163 self
::$_exportableFields[$name] = array();
2165 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2166 // my case hence we have defined fields as case_*
2167 if ($name == 'Activity') {
2168 $exportableFields = CRM_Activity_DAO_Activity
::export();
2169 if (isset($exportableFields['activity_campaign_id'])) {
2170 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2172 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2173 $exportableFields['source_contact'] = array(
2174 'title' => ts('Source Contact'),
2175 'type' => CRM_Utils_Type
::T_STRING
,
2179 $Activityfields = array(
2180 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2181 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2183 $fields = array_merge($Activityfields, $exportableFields);
2186 //set title to activity fields
2188 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2189 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2190 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2191 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2192 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2193 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2194 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2195 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2196 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2197 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2200 // add custom data for cases
2201 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2204 // add custom data for case activities
2205 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2207 self
::$_exportableFields[$name] = $fields;
2209 return self
::$_exportableFields[$name];
2213 * Get the allowed profile fields for Activities
2215 * @return array array of activity profile Fields
2218 static function getProfileFields() {
2219 $exportableFields = self
::exportableFields('Activity');
2220 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2221 $config = CRM_Core_Config
::singleton();
2222 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2223 $skipFields[] = 'activity_engagement_level';
2226 foreach ($skipFields as $field) {
2227 if (isset($exportableFields[$field])) {
2228 unset($exportableFields[$field]);
2232 // hack to use 'activity_type_id' instead of 'activity_type'
2233 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2234 unset($exportableFields['activity_status']);
2236 return $exportableFields;
2240 * This function delete activity record related to contact record,
2241 * when there are no target and assignee record w/ other contact.
2243 * @param int $contactId contactId
2248 public static function cleanupActivity($contactId) {
2254 $transaction = new CRM_Core_Transaction();
2256 // delete activity if there are no record in
2257 // civicrm_activity_assignment or civicrm_activity_target
2258 // pointing to any other contact record.
2261 $activity = new CRM_Activity_DAO_Activity();
2262 $activity->source_contact_id
= $contactId;
2265 while ($activity->fetch()) {
2266 $noTarget = $noAssignee = TRUE;
2268 // check for target activity record.
2269 $target = new CRM_Activity_DAO_ActivityTarget();
2270 $target->activity_id
= $activity->id
;
2272 while ($target->fetch()) {
2273 if ($target->target_contact_id
!= $contactId) {
2280 // check for assignee activity record.
2281 $assignee = new CRM_Activity_DAO_ActivityAssignment();
2282 $assignee->activity_id
= $activity->id
;
2284 while ($assignee->fetch()) {
2285 if ($assignee->assignee_contact_id
!= $contactId) {
2286 $noAssignee = FALSE;
2292 // finally delete activity.
2293 if ($noTarget && $noAssignee) {
2294 $activityParams = array('id' => $activity->id
);
2295 $result = self
::deleteActivity($activityParams);
2300 $transaction->commit();
2306 * Does user has sufficient permission for view/edit activity record.
2308 * @param int $activityId activity record id.
2309 * @param int $action edit/view
2311 * @return boolean $allow true/false
2314 public static function checkPermission($activityId, $action) {
2317 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2322 $activity = new CRM_Activity_DAO_Activity();
2323 $activity->id
= $activityId;
2324 if (!$activity->find(TRUE)) {
2328 //component related permissions.
2329 $compPermissions = array(
2330 'CiviCase' => array('administer CiviCase',
2331 'access my cases and activities',
2332 'access all cases and activities',
2334 'CiviMail' => array('access CiviMail'),
2335 'CiviEvent' => array('access CiviEvent'),
2336 'CiviGrant' => array('access CiviGrant'),
2337 'CiviPledge' => array('access CiviPledge'),
2338 'CiviMember' => array('access CiviMember'),
2339 'CiviReport' => array('access CiviReport'),
2340 'CiviContribute' => array('access CiviContribute'),
2341 'CiviCampaign' => array('administer CiviCampaign'),
2344 //return early when it is case activity.
2345 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2346 //check for civicase related permission.
2347 if ($isCaseActivity) {
2349 foreach ($compPermissions['CiviCase'] as $per) {
2350 if (CRM_Core_Permission
::check($per)) {
2356 //check for case specific permissions.
2359 if ($action == CRM_Core_Action
::UPDATE
) {
2362 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2364 $activity->activity_type_id
2372 //first check the component permission.
2375 FROM civicrm_option_value val
2376 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2377 WHERE val.value = %2";
2378 $params = array(1 => array('activity_type', 'String'),
2379 2 => array($activity->activity_type_id
, 'Integer'),
2381 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2384 $componentName = CRM_Core_Component
::getComponentName($componentId);
2385 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2387 //here we are interesting in any single permission.
2388 if (is_array($compPermission)) {
2389 foreach ($compPermission as $per) {
2390 if (CRM_Core_Permission
::check($per)) {
2398 //check for this permission related to contact.
2399 $permission = CRM_Core_Permission
::VIEW
;
2400 if ($action == CRM_Core_Action
::UPDATE
) {
2401 $permission = CRM_Core_Permission
::EDIT
;
2404 //check for source contact.
2405 if (!$componentId ||
$allow) {
2406 $allow = CRM_Contact_BAO_Contact_Permission
::allow($activity->source_contact_id
, $permission);
2409 //check for target and assignee contacts.
2411 //first check for supper permission.
2412 $supPermission = 'view all contacts';
2413 if ($action == CRM_Core_Action
::UPDATE
) {
2414 $supPermission = 'edit all contacts';
2416 $allow = CRM_Core_Permission
::check($supPermission);
2418 //user might have sufficient permission, through acls.
2421 //get the target contacts.
2422 $targetContacts = CRM_Activity_BAO_ActivityTarget
::retrieveTargetIdsByActivityId($activity->id
);
2423 foreach ($targetContacts as $cnt => $contactId) {
2424 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2430 //get the assignee contacts.
2432 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment
::retrieveAssigneeIdsByActivityId($activity->id
);
2433 foreach ($assigneeContacts as $cnt => $contactId) {
2434 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2447 * This function is a wrapper for ajax activity selector
2449 * @param array $params associated array for params record id.
2451 * @return array $contactActivities associated array of contact activities
2454 public static function getContactActivitySelector(&$params) {
2455 // format the params
2456 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2457 $params['rowCount'] = $params['rp'];
2458 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2459 $params['caseId'] = NULL;
2460 $context = CRM_Utils_Array
::value('context', $params);
2462 // get contact activities
2463 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2466 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2468 // format params and add links
2469 $contactActivities = array();
2471 if (!empty($activities)) {
2472 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2474 // check logged in user for permission
2475 $page = new CRM_Core_Page();
2476 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2477 $permissions = array($page->_permission
);
2478 if (CRM_Core_Permission
::check('delete activities')) {
2479 $permissions[] = CRM_Core_Permission
::DELETE
;
2482 $mask = CRM_Core_Action
::mask($permissions);
2484 foreach ($activities as $activityId => $values) {
2485 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2486 $contactActivities[$activityId]['subject'] = $values['subject'];
2487 if ($params['contact_id'] == $values['source_contact_id']) {
2488 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2490 elseif ($values['source_contact_id']) {
2491 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2494 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2497 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2498 $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");
2500 elseif (CRM_Utils_Array
::value('recipients', $values)) {
2501 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2503 elseif (!$values['target_contact_name']) {
2504 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2506 elseif (!empty($values['target_contact_name'])) {
2508 $contactActivities[$activityId]['target_contact'] = '';
2509 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2510 if ($tcID && $count < 5) {
2511 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2514 $contactActivities[$activityId]['target_contact'] .= "; ";
2518 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2525 if (empty($values['assignee_contact_name'])) {
2526 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2528 elseif (!empty($values['assignee_contact_name'])) {
2530 $contactActivities[$activityId]['assignee_contact'] = '';
2531 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2532 if ($acID && $count < 5) {
2533 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2536 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2540 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2546 if ( $values['activity_type'] == 'Bulk Email'){
2547 $contactActivities[$activityId]['openstats'] = "Opens: ".
2548 count(CRM_Mailing_Event_BAO_Opened
::getRows(
2549 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2552 count(CRM_Mailing_Event_BAO_TrackableURLOpen
::getRows(
2553 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2556 $contactActivities[$activityId]['openstats'] = '';
2559 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2560 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2562 // add class to this row if overdue
2563 $contactActivities[$activityId]['class'] = '';
2564 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2565 && CRM_Utils_Array
::value('status_id', $values) == 1
2567 $contactActivities[$activityId]['class'] = 'status-overdue';
2570 $contactActivities[$activityId]['class'] = 'status-ontime';
2574 $contactActivities[$activityId]['links'] = '';
2575 $accessMailingReport = FALSE;
2576 if (CRM_Utils_Array
::value('mailingId', $values)) {
2577 $accessMailingReport = TRUE;
2580 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2581 CRM_Utils_Array
::value('activity_type_id', $values),
2582 CRM_Utils_Array
::value('source_record_id', $values),
2583 $accessMailingReport,
2584 CRM_Utils_Array
::value('activity_id', $values)
2587 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2589 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2592 'id' => $values['activity_id'],
2593 'cid' => $params['contact_id'],
2595 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2601 return $contactActivities;
2605 * Used to copy custom fields and attachments from an existing activity to another.
2606 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2608 static function copyExtendedActivityData($params) {
2609 // attach custom data to the new activity
2610 $customParams = $htmlType = array();
2611 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2613 if (!empty($customValues)) {
2614 $fieldIds = implode(', ', array_keys($customValues));
2615 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2616 $result = CRM_Core_DAO
::executeQuery($sql);
2618 while ($result->fetch()) {
2619 $htmlType[] = $result->id
;
2622 foreach ($customValues as $key => $value) {
2623 if ($value !== NULL) { // CRM-10542
2624 if (in_array($key, $htmlType)) {
2625 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2626 $customParams["custom_{$key}_-1"] = array(
2627 'name' => $fileValues[0],
2628 'path' => $fileValues[1],
2632 $customParams["custom_{$key}_-1"] = $value;
2636 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2637 $params['mainActivityId'], 'Activity'
2641 // copy activity attachments ( if any )
2642 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);