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(
202 'CRM_Activity_DAO_Activity',
206 if ($sourceContactId) {
207 $msgs[] = " source={$sourceContactId}";
209 //get target contacts.
210 $targetContactIds = CRM_Activity_BAO_ActivityTarget
::getTargetNames($activity->id
);
211 if (!empty($targetContactIds)) {
212 $msgs[] = " target =" . implode(',', array_keys($targetContactIds));
214 //get assignee contacts.
215 $assigneeContactIds = CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames($activity->id
);
216 if (!empty($assigneeContactIds)) {
217 $msgs[] = " assignee =" . implode(',', array_keys($assigneeContactIds));
220 $logMsg .= implode(', ', $msgs);
222 self
::logActivityAction($activity, $logMsg);
225 // delete the recently created Activity
227 $activityRecent = array(
228 'id' => $activity->id
,
229 'type' => 'Activity',
231 CRM_Utils_Recent
::del($activityRecent);
234 $transaction->commit();
235 if (isset($activity)) {
237 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
238 CRM_Utils_Hook
::post('delete', 'Activity', $activity->id
, $activity);
245 * Delete activity assignment record
247 * @param int $id activity id
252 public static function deleteActivityContact($activityId, $recordType = NULL) {
253 $activityContact = new CRM_Activity_BAO_ActivityContact();
254 $activityContact->activity_id
= $activityId;
256 $activityContact->record_type
= $recordType;
258 $activityContact->delete();
262 * Function to process the activities
264 * @param object $form form object
265 * @param array $params associated array of the submitted values
266 * @param array $ids array of ids
267 * @param string $activityType activity Type
268 * @param boolean $record true if it is Record Activity
273 public static function create(&$params) {
274 // check required params
275 if (!self
::dataExists($params)) {
276 CRM_Core_Error
::fatal('Not enough data to create activity object,');
279 $activity = new CRM_Activity_DAO_Activity();
281 if (isset($params['id']) && empty($params['id'])) {
282 unset($params['id']);
285 if (!CRM_Utils_Array
::value('status_id', $params) &&
286 !CRM_Utils_Array
::value('activity_status_id', $params) &&
287 !CRM_Utils_Array
::value('id', $params)
289 if (isset($params['activity_date_time']) &&
290 strcmp($params['activity_date_time'], CRM_Utils_Date
::processDate(date('Ymd')) == -1)
292 $params['status_id'] = 2;
295 $params['status_id'] = 1;
299 //set priority to Normal for Auto-populated activities (for Cases)
300 if (CRM_Utils_Array
::value('priority_id', $params) === NULL &&
301 // if not set and not 0
302 !CRM_Utils_Array
::value('id', $params)
304 $priority = CRM_Core_PseudoConstant
::priority();
305 $params['priority_id'] = array_search('Normal', $priority);
308 if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
309 $params['target_contact_id'] = array_unique($params['target_contact_id']);
311 if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
312 $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
316 if (CRM_Utils_Array
::value('id', $params)) {
317 CRM_Utils_Hook
::pre('edit', 'Activity', $activity->id
, $params);
320 CRM_Utils_Hook
::pre('create', 'Activity', NULL, $params);
323 $activity->copyValues($params);
324 if (isset($params['case_id'])) {
325 // CRM-8708, preserve case ID even though it's not part of the SQL model
326 $activity->case_id
= $params['case_id'];
328 elseif (is_numeric($activity->id
)) {
329 // CRM-8708, preserve case ID even though it's not part of the SQL model
330 $activity->case_id
= CRM_Case_BAO_Case
::getCaseIdByActivityId($activity->id
);
334 $transaction = new CRM_Core_Transaction();
336 $result = $activity->save();
338 if (is_a($result, 'CRM_Core_Error')) {
339 $transaction->rollback();
343 $activityId = $activity->id
;
345 if (isset($params['source_contact_id'])) {
347 'activity_id' => $activityId,
348 'contact_id' => $params['source_contact_id'],
349 'record_type' => 'Source'
351 CRM_Activity_BAO_ActivityContact
::create($acParams);
354 // check and attach and files as needed
355 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_activity', $activityId);
358 // attempt to save activity assignment
359 $resultAssignment = NULL;
360 if (CRM_Utils_Array
::value('assignee_contact_id', $params)) {
362 $assignmentParams = array('activity_id' => $activityId);
364 if (is_array($params['assignee_contact_id'])) {
365 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
366 // first delete existing assignments if any
367 self
::deleteActivityContact($activityId, 'Assignee');
371 foreach ($params['assignee_contact_id'] as $acID) {
373 $values[] = "( $activityId, $acID, 'Assignee' )";
376 while (!empty($values)) {
377 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
378 $str = implode(',', $input);
379 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type ) VALUES $str;";
380 CRM_Core_DAO
::executeQuery($sql);
384 $assignmentParams['assignee_contact_id'] = $params['assignee_contact_id'];
386 if (CRM_Utils_Array
::value('id', $params)) {
387 $assignment = new CRM_Activity_BAO_ActivityAssignment();
388 $assignment->activity_id
= $activityId;
389 $assignment->find(TRUE);
391 if ($assignment->assignee_contact_id
!= $params['assignee_contact_id']) {
392 $assignmentParams['id'] = $assignment->id
;
393 $resultAssignment = CRM_Activity_BAO_ActivityAssignment
::create($assignmentParams);
397 $resultAssignment = CRM_Activity_BAO_ActivityAssignment
::create($assignmentParams);
402 if (CRM_Utils_Array
::value('deleteActivityAssignment', $params, TRUE)) {
403 self
::deleteActivityContact($activityId, 'Assignee');
407 if (is_a($resultAssignment, 'CRM_Core_Error')) {
408 $transaction->rollback();
409 return $resultAssignment;
412 // attempt to save activity targets
413 $resultTarget = NULL;
414 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
416 $targetParams = array('activity_id' => $activityId);
417 $resultTarget = array();
418 if (is_array($params['target_contact_id'])) {
419 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
420 // first delete existing targets if any
421 self
::deleteActivityContact($activityId, 'Target');
425 foreach ($params['target_contact_id'] as $tid) {
427 $values[] = "( $activityId, $tid, 'Target' )";
431 while (!empty($values)) {
432 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
433 $str = implode(',', $input);
434 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type ) VALUES $str;";
435 CRM_Core_DAO
::executeQuery($sql);
439 $targetParams['target_contact_id'] = $params['target_contact_id'];
441 if (CRM_Utils_Array
::value('id', $params)) {
442 $target = new CRM_Activity_BAO_ActivityTarget();
443 $target->activity_id
= $activityId;
446 if ($target->target_contact_id
!= $params['target_contact_id']) {
447 $targetParams['id'] = $target->id
;
448 $resultTarget = CRM_Activity_BAO_ActivityTarget
::create($targetParams);
452 $resultTarget = CRM_Activity_BAO_ActivityTarget
::create($targetParams);
457 if (CRM_Utils_Array
::value('deleteActivityTarget', $params, TRUE)) {
458 self
::deleteActivityContact($activityId, 'Target');
462 // write to changelog before transation is committed/rolled
463 // back (and prepare status to display)
464 if (CRM_Utils_Array
::value('id', $params)) {
465 $logMsg = "Activity (id: {$result->id} ) updated with ";
468 $logMsg = "Activity created for ";
472 if (isset($params['source_contact_id'])) {
473 $msgs[] = "source={$params['source_contact_id']}";
476 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
477 if (is_array($params['target_contact_id']) && !CRM_Utils_array
::crmIsEmptyArray($params['target_contact_id'])) {
478 $msgs[] = "target=" . implode(',', $params['target_contact_id']);
479 // take only first target
480 // will be used for recently viewed display
481 $t = array_slice($params['target_contact_id'], 0, 1);
482 $recentContactId = $t[0];
484 elseif (isset($params['target_contact_id'])) {
485 $msgs[] = "target={$params['target_contact_id']}";
486 // will be used for recently viewed display
487 $recentContactId = $params['target_contact_id'];
491 // at worst, take source for recently viewed display
492 $recentContactId = CRM_Utils_Array
::value('source_contact_id',$params);
495 if (isset($params['assignee_contact_id'])) {
496 if (is_array($params['assignee_contact_id'])) {
497 $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
500 $msgs[] = "assignee={$params['assignee_contact_id']}";
503 $logMsg .= implode(', ', $msgs);
505 self
::logActivityAction($result, $logMsg);
507 if (CRM_Utils_Array
::value('custom', $params) &&
508 is_array($params['custom'])
510 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_activity', $result->id
);
513 $transaction->commit();
514 if (!CRM_Utils_Array
::value('skipRecentView', $params)) {
515 $recentOther = array();
516 if (CRM_Utils_Array
::value('case_id', $params)) {
517 $caseContactID = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
518 $url = CRM_Utils_System
::url('civicrm/case/activity/view',
519 "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home"
523 $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home";
524 if ($activity->activity_type_id
!= CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name')) {
525 $url = CRM_Utils_System
::url('civicrm/activity', $q);
526 if ($activity->activity_type_id
== CRM_Core_OptionGroup
::getValue('activity_type', 'Print PDF Letter', 'name')) {
527 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/pdf/add',
528 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
532 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/activity/add',
533 "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
537 if (CRM_Core_Permission
::check("delete activities")) {
538 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
539 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
544 $url = CRM_Utils_System
::url('civicrm/activity/view', $q);
545 if (CRM_Core_Permission
::check('delete activities')) {
546 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/activity',
547 "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$activity->source_contact_id}&context=home"
553 if (!isset($activity->parent_id
)) {
554 $recentContactDisplay = CRM_Contact_BAO_Contact
::displayName($recentContactId);
555 // add the recently created Activity
556 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
557 $activitySubject = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activity->id
, 'subject');
560 if (isset($activitySubject)) {
561 $title = $activitySubject . ' - ';
564 $title = $title . $recentContactDisplay;
565 if (CRM_Utils_Array
::value($activity->activity_type_id
, $activityTypes)) {
566 $title .= ' (' . $activityTypes[$activity->activity_type_id
] . ')';
569 CRM_Utils_Recent
::add($title,
574 $recentContactDisplay,
580 // reset the group contact cache since smart groups might be affected due to this
581 CRM_Contact_BAO_GroupContactCache
::remove();
583 if (CRM_Utils_Array
::value('id', $params)) {
584 CRM_Utils_Hook
::post('edit', 'Activity', $activity->id
, $activity);
587 CRM_Utils_Hook
::post('create', 'Activity', $activity->id
, $activity);
590 // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
592 if (preg_match('/\[case #([0-9a-h]{7})\]/', CRM_Utils_Array
::value('subject', $params), $matches)) {
593 $key = CRM_Core_DAO
::escapeString(CIVICRM_SITE_KEY
);
595 $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = '$hash'";
597 'activity_id' => $activity->id
,
598 'case_id' => CRM_Core_DAO
::singleValueQuery($query),
600 if ($caseParams['case_id']) {
601 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
604 self
::logActivityAction($activity, "unknown case hash encountered: $hash");
611 public static function logActivityAction($activity, $logMessage = NULL) {
612 $session = CRM_Core_Session
::singleton();
613 $id = $session->get('userID');
615 $id = $activity->source_contact_id
;
618 'entity_table' => 'civicrm_activity',
619 'entity_id' => $activity->id
,
620 'modified_id' => $id,
621 'modified_date' => date('YmdHis'),
622 'data' => $logMessage,
624 CRM_Core_BAO_Log
::add($logParams);
629 * function to get the list Actvities
631 * @param array $input array of parameters
633 * - contact_id int contact_id whose activties we want to retrieve
634 * - offset int which row to start from ?
635 * - rowCount int how many rows to fetch
636 * - sort object|array object or array describing sort order for sql query.
637 * - admin boolean if contact is admin
638 * - caseId int case ID
639 * - context string page on which selector is build
640 * - activity_type_id int|string the activitiy types we want to restrict by
642 * @return array (reference) $values the relevant data object values of open activitie
647 static function &getActivities($input) {
648 //step 1: Get the basic activity data
649 $bulkActivityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
654 $config = CRM_Core_Config
::singleton();
656 $randomNum = md5(uniqid());
657 $activityTempTable = "civicrm_temp_activity_details_{$randomNum}";
659 $tableFields = array(
660 'activity_id' => 'int unsigned',
661 'activity_date_time' => 'datetime',
662 'status_id' => 'int unsigned',
663 'subject' => 'varchar(255)',
664 'source_record_id' => 'int unsigned',
665 'activity_type_id' => 'int unsigned',
666 'activity_type' => 'varchar(128)',
667 'case_id' => 'int unsigned',
668 'case_subject' => 'varchar(255)',
669 'campaign_id' => 'int unsigned',
672 $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( ";
673 $insertValueSQL = array();
674 foreach ($tableFields as $name => $desc) {
675 $sql .= "$name $desc,\n";
676 $insertValueSQL[] = $name;
680 PRIMARY KEY ( activity_id )
681 ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
684 CRM_Core_DAO
::executeQuery($sql);
686 $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) ";
688 $order = $limit = $groupBy = '';
690 if (!empty($input['sort'])) {
691 if (is_a($input['sort'], 'CRM_Utils_Sort')) {
692 $orderBy = $input['sort']->orderBy();
693 if (!empty($orderBy)) {
694 $order = " ORDER BY $orderBy";
697 elseif (trim($input['sort'])) {
698 $order = " ORDER BY {$input['sort']}";
703 $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 ";
706 if (!empty($input['rowCount']) &&
707 $input['rowCount'] > 0
709 $limit = " LIMIT {$input['offset']}, {$input['rowCount']} ";
712 $input['count'] = FALSE;
713 list($sqlClause, $params) = self
::getActivitySQLClause($input);
715 $query = "{$insertSQL}
716 SELECT DISTINCT tbl.* from ( {$sqlClause} )
719 //filter case activities - CRM-5761
720 $components = self
::activityComponents();
721 if (!in_array('CiviCase', $components)) {
723 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
724 WHERE civicrm_case_activity.id IS NULL";
727 $query = $query . $groupBy . $order . $limit;
729 $dao = CRM_Core_DAO
::executeQuery($query, $params);
731 $notbulkActivityClause = '';
732 if ($bulkActivityTypeID) {
733 $notbulkActivityClause = " AND {$activityTempTable}.activity_type_id <> {$bulkActivityTypeID} ";
736 // step 2: Get target and assignee contacts for above activities
737 // create temp table for target contacts
738 $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}";
739 $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (
740 activity_id int unsigned, contact_id int unsigned, record_type varchar(16), contact_name varchar(255) )
741 ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
743 CRM_Core_DAO
::executeQuery($query);
745 // note that we ignore bulk email for targets, since we don't show it in selector
747 INSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type, contact_name )
748 SELECT ac.activity_id,
752 FROM civicrm_activity_contact ac
753 INNER JOIN {$activityTempTable} ON ( ac.activity_id = {$activityTempTable}.activity_id
754 INNER JOIN civicrm_contact c ON c.id = at.contact_id
755 WHERE c.is_deleted = 0
756 {$notbulkActivityClause} )
758 CRM_Core_DAO
::executeQuery($query);
760 CRM_Core_DAO
::executeQuery($query);
762 // step 3: Combine all temp tables to get final query for activity selector
764 SELECT {$activityTempTable}.*,
765 {$activityContactTempTable}.contact_id,
766 {$activityContactTempTable}.record_type,
767 {$activityContactTempTable}.contact_name,
768 FROM {$activityTempTable}
769 INNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id
773 $dao = CRM_Core_DAO
::executeQuery($query);
775 //CRM-3553, need to check user has access to target groups.
776 $mailingIDs = CRM_Mailing_BAO_Mailing
::mailingACLIDs();
778 (CRM_Core_Permission
::check('access CiviMail')) ||
779 (CRM_Mailing_Info
::workflowEnabled() &&
780 CRM_Core_Permission
::check('create mailings'))
784 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
787 while ($dao->fetch()) {
788 $activityID = $dao->activity_id
;
789 $values[$activityID]['activity_id'] = $dao->activity_id
;
790 $values[$activityID]['source_record_id'] = $dao->source_record_id
;
791 $values[$activityID]['activity_type_id'] = $dao->activity_type_id
;
792 $values[$activityID]['activity_type'] = $dao->activity_type
;
793 $values[$activityID]['activity_date_time'] = $dao->activity_date_time
;
794 $values[$activityID]['status_id'] = $dao->status_id
;
795 $values[$activityID]['subject'] = $dao->subject
;
796 $values[$activityID]['campaign_id'] = $dao->campaign_id
;
798 if ($dao->campaign_id
) {
799 $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id
];
802 if (!CRM_Utils_Array
::value('assignee_contact_name', $values[$activityID])) {
803 $values[$activityID]['assignee_contact_name'] = array();
806 if (!CRM_Utils_Array
::value('target_contact_name', $values[$activityID])) {
807 $values[$activityID]['target_contact_name'] = array();
810 if ($dao->record_type
== 'Source' && $dao->contact_id
) {
811 $values[$activityID]['source_contact_id'] = $dao->contact_id
;
812 $values[$activityID]['source_contact_name'] = $dao->contact_name
;
815 if (!$bulkActivityTypeID ||
($bulkActivityTypeID != $dao->activity_type_id
)) {
816 // build array of target / assignee names
817 if ($dao->record_type
== 'Target' && $dao->contact_id
) {
818 $values[$activityID]['target_contact_name'][$dao->contact_id
] = $dao->contact_name
;
820 if ($dao->record_type
== 'Assignee' && $dao->contact_id
) {
821 $values[$activityID]['assignee_contact_name'][$dao->contact_id
] = $dao->contact_name
;
824 // case related fields
825 $values[$activityID]['case_id'] = $dao->case_id
;
826 $values[$activityID]['case_subject'] = $dao->case_subject
;
829 $values[$activityID]['recipients'] = ts('(recipients)');
830 $values[$activityID]['mailingId'] = '';
833 ($mailingIDs === TRUE ||
in_array($dao->source_record_id
, $mailingIDs))
835 $values[$activityID]['mailingId'] = CRM_Utils_System
::url('civicrm/mailing/report',
836 "mid={$dao->source_record_id}&reset=1&cid={$dao->source_contact_id}&context=activitySelector"
842 // add info on whether the related contacts are deleted (CRM-5673)
843 // FIXME: ideally this should be tied to ACLs
845 // grab all the related contact ids
847 foreach ($values as $value) {
848 $cids[] = $value['source_contact_id'];
850 $cids = array_filter(array_unique($cids));
852 // see which of the cids are of deleted contacts
854 $sql = 'SELECT id FROM civicrm_contact WHERE id IN (' . implode(', ', $cids) . ') AND is_deleted = 1';
855 $dao = CRM_Core_DAO
::executeQuery($sql);
857 while ($dao->fetch()) {
861 // hide the deleted contacts
862 foreach ($values as & $value) {
863 if (in_array($value['source_contact_id'], $dels)) {
864 unset($value['source_contact_id'], $value['source_contact_name']);
873 * Get the component id and name those are enabled and logged in
874 * user has permission. To decide whether we are going to include
875 * component related activities w/ core activity retrieve process.
877 * return an array of component id and name.
880 static function activityComponents() {
881 $components = array();
882 $compInfo = CRM_Core_Component
::getEnabledComponents();
883 foreach ($compInfo as $compObj) {
884 if (CRM_Utils_Array
::value('showActivitiesInCore', $compObj->info
)) {
885 if ($compObj->info
['name'] == 'CiviCampaign') {
886 $componentPermission = "administer {$compObj->name}";
889 $componentPermission = "access {$compObj->name}";
891 if ($compObj->info
['name'] == 'CiviCase') {
892 if (CRM_Case_BAO_Case
::accessCiviCase()) {
893 $components[$compObj->componentID
] = $compObj->info
['name'];
896 elseif (CRM_Core_Permission
::check($componentPermission)) {
897 $components[$compObj->componentID
] = $compObj->info
['name'];
906 * function to get the activity Count
908 * @param array $input array of parameters
910 * - contact_id int contact_id whose activties we want to retrieve
911 * - admin boolean if contact is admin
912 * - caseId int case ID
913 * - context string page on which selector is build
914 * - activity_type_id int|string the activitiy types we want to restrict by
916 * @return int count of activities
921 static function &getActivitiesCount($input) {
922 $input['count'] = TRUE;
923 list($sqlClause, $params) = self
::getActivitySQLClause($input);
925 //filter case activities - CRM-5761
926 $components = self
::activityComponents();
927 if (!in_array('CiviCase', $components)) {
929 SELECT COUNT(DISTINCT(tbl.activity_id)) as count
930 FROM ( {$sqlClause} ) as tbl
931 LEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )
932 WHERE civicrm_case_activity.id IS NULL";
935 $query = "SELECT COUNT(DISTINCT(activity_id)) as count from ( {$sqlClause} ) as tbl";
938 return CRM_Core_DAO
::singleValueQuery($query, $params);
942 * function to get the activity sql clause to pick activities
944 * @param array $input array of parameters
946 * - contact_id int contact_id whose activties we want to retrieve
947 * - admin boolean if contact is admin
948 * - caseId int case ID
949 * - context string page on which selector is build
950 * - count boolean are we interested in the count clause only?
951 * - activity_type_id int|string the activitiy types we want to restrict by
953 * @return int count of activities
958 static function getActivitySQLClause($input) {
960 $sourceWhere = $targetWhere = $assigneeWhere = $caseWhere = 1;
962 $config = CRM_Core_Config
::singleton();
963 if (!CRM_Utils_Array
::value('admin', $input, FALSE)) {
964 $sourceWhere = ' ac.contact_id = %1 ';
965 $caseWhere = ' civicrm_case_contact.contact_id = %1 ';
967 $params = array(1 => array($input['contact_id'], 'Integer'));
970 $commonClauses = array(
971 "civicrm_option_group.name = 'activity_type'",
972 "civicrm_activity.is_deleted = 0",
973 "civicrm_activity.is_current_revision = 1",
974 "civicrm_activity.is_test = 0",
977 if ($input['context'] != 'activity') {
978 $commonClauses[] = "civicrm_activity.status_id = 1";
981 //Filter on component IDs.
982 $components = self
::activityComponents();
983 if (!empty($components)) {
984 $componentsIn = implode(',', array_keys($components));
985 $commonClauses[] = "( civicrm_option_value.component_id IS NULL OR civicrm_option_value.component_id IN ( $componentsIn ) )";
988 $commonClauses[] = "civicrm_option_value.component_id IS NULL";
991 // activity type ID clause
992 if (!empty($input['activity_type_id'])) {
993 if (is_array($input['activity_type_id'])) {
994 foreach ($input['activity_type_id'] as $idx => $value) {
995 $input['activity_type_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
997 $commonClauses[] = "civicrm_activity.activity_type_id IN ( " . implode(",", $input['activity_type_id']) . " ) ";
1000 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_id'], 'Positive');
1001 $commonClauses[] = "civicrm_activity.activity_type_id = $activityTypeID";
1005 // exclude by activity type clause
1006 if (!empty($input['activity_type_exclude_id'])) {
1007 if (is_array($input['activity_type_exclude_id'])) {
1008 foreach ($input['activity_type_exclude_id'] as $idx => $value) {
1009 $input['activity_type_exclude_id'][$idx] = CRM_Utils_Type
::escape($value, 'Positive');
1011 $commonClauses[] = "civicrm_activity.activity_type_id NOT IN ( " . implode(",", $input['activity_type_exclude_id']) . " ) ";
1014 $activityTypeID = CRM_Utils_Type
::escape($input['activity_type_exclude_id'], 'Positive');
1015 $commonClauses[] = "civicrm_activity.activity_type_id != $activityTypeID";
1019 $commonClause = implode(' AND ', $commonClauses);
1021 $includeCaseActivities = FALSE;
1022 if (in_array('CiviCase', $components)) {
1023 $includeCaseActivities = TRUE;
1027 // build main activity table select clause
1031 if (!$input['count']) {
1033 civicrm_activity.activity_date_time,
1034 civicrm_activity.status_id,
1035 civicrm_activity.subject,
1036 civicrm_activity.source_record_id,
1037 sourceContact.sort_name as source_contact_name,
1038 civicrm_option_value.value as activity_type_id,
1039 civicrm_option_value.label as activity_type,
1040 null as case_id, null as case_subject,
1041 civicrm_activity.campaign_id as campaign_id,
1042 activityContact.contact_id as contact_id,
1043 activityContact.record_type as record_type,
1044 contact.sort_name as sort_name
1048 INNER JOIN civicrm_activity_contact activityContact ON activityContact.activity_id = civicrm_activity.id
1049 INNER JOIN civicrm_contact contact ON activityContact.contact_id = contact.id
1054 SELECT civicrm_activity.id as activity_id
1056 from civicrm_activity
1057 left join civicrm_option_value on
1058 civicrm_activity.activity_type_id = civicrm_option_value.value
1059 left join civicrm_option_group on
1060 civicrm_option_group.id = civicrm_option_value.option_group_id
1067 // Build case clause
1068 // or else exclude Inbound Emails that have been filed on a case.
1071 if ($includeCaseActivities) {
1073 if (!$input['count']) {
1075 civicrm_activity.activity_date_time,
1076 civicrm_activity.status_id,
1077 civicrm_activity.subject,
1078 civicrm_activity.source_contact_id,
1079 civicrm_activity.source_record_id,
1080 sourceContact.sort_name as source_contact_name,
1081 civicrm_option_value.value as activity_type_id,
1082 civicrm_option_value.label as activity_type,
1083 null as case_id, null as case_subject,
1084 civicrm_activity.campaign_id as campaign_id';
1090 SELECT civicrm_activity.id as activity_id
1092 from civicrm_activity
1093 inner join civicrm_case_activity on
1094 civicrm_case_activity.activity_id = civicrm_activity.id
1095 inner join civicrm_case on
1096 civicrm_case_activity.case_id = civicrm_case.id
1097 inner join civicrm_case_contact on
1098 civicrm_case_contact.case_id = civicrm_case.id and {$caseWhere}
1099 left join civicrm_option_value on
1100 civicrm_activity.activity_type_id = civicrm_option_value.value
1101 left join civicrm_option_group on
1102 civicrm_option_group.id = civicrm_option_value.option_group_id
1107 and ( ( civicrm_case_activity.case_id IS NULL ) OR
1108 ( civicrm_option_value.name <> 'Inbound Email' AND
1109 civicrm_option_value.name <> 'Email' AND civicrm_case_activity.case_id
1115 $returnClause = " {$sourceClause} union all {$caseClause} ";
1117 return array($returnClause, $params);
1121 * send the message to all the contacts and also insert a
1122 * contact activity in each contacts record
1124 * @param array $contactDetails the array of contact details to send the email
1125 * @param string $subject the subject of the message
1126 * @param string $message the message contents
1127 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1128 * @param int $userID use this userID if set
1129 * @param string $from
1130 * @param array $attachments the array of attachments if any
1131 * @param string $cc cc recepient
1132 * @param string $bcc bcc recepient
1133 * @param array $contactIds contact ids
1135 * @return array ( sent, activityId) if any email is sent and activityId
1139 static function sendEmail(
1147 $attachments = NULL,
1150 $contactIds // FIXME a param with no default shouldn't be last
1152 // get the contact details of logged in contact, which we set as from email
1153 if ($userID == NULL) {
1154 $session = CRM_Core_Session
::singleton();
1155 $userID = $session->get('userID');
1158 list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($userID);
1160 return array(count($contactDetails), 0, count($contactDetails));
1162 if (!trim($fromDisplayName)) {
1163 $fromDisplayName = $fromEmail;
1167 // token replacement of addressee/email/postal greetings
1168 // get the tokens added in subject and message
1169 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1170 $messageToken = CRM_Utils_Token
::getTokens($text);
1171 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1174 $from = "$fromDisplayName <$fromEmail>";
1177 //create the meta level record first ( email activity )
1178 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1183 // CRM-6265: save both text and HTML parts in details (if present)
1184 if ($html and $text) {
1185 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1188 $details = $html ?
$html : $text;
1191 $activityParams = array(
1192 'source_contact_id' => $userID,
1193 'activity_type_id' => $activityTypeID,
1194 'activity_date_time' => date('YmdHis'),
1195 'subject' => $subject,
1196 'details' => $details,
1197 // FIXME: check for name Completed and get ID from that lookup
1201 // CRM-5916: strip [case #…] before saving the activity (if present in subject)
1202 $activityParams['subject'] = preg_replace('/\[case #([0-9a-h]{7})\] /', '', $activityParams['subject']);
1204 // add the attachments to activity params here
1206 // first process them
1207 $activityParams = array_merge($activityParams,
1212 $activity = self
::create($activityParams);
1214 // get the set of attachments from where they are stored
1215 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
1218 $returnProperties = array();
1219 if (isset($messageToken['contact'])) {
1220 foreach ($messageToken['contact'] as $key => $value) {
1221 $returnProperties[$value] = 1;
1225 if (isset($subjectToken['contact'])) {
1226 foreach ($subjectToken['contact'] as $key => $value) {
1227 if (!isset($returnProperties[$value])) {
1228 $returnProperties[$value] = 1;
1234 // get token details for contacts, call only if tokens are used
1236 if (!empty($returnProperties)) {
1237 list($details) = CRM_Utils_Token
::getTokenDetails(
1242 'CRM_Activity_BAO_Activity'
1248 CRM_Utils_Hook
::tokens($tokens);
1249 $categories = array_keys($tokens);
1251 $escapeSmarty = FALSE;
1252 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1253 $smarty = CRM_Core_Smarty
::singleton();
1254 $escapeSmarty = TRUE;
1257 $sent = $notSent = array();
1258 foreach ($contactDetails as $values) {
1259 $contactId = $values['contact_id'];
1260 $emailAddress = $values['email'];
1262 if (!empty($details) && is_array($details["{$contactId}"])) {
1263 // unset email from details since it always returns primary email address
1264 unset($details["{$contactId}"]['email']);
1265 unset($details["{$contactId}"]['email_id']);
1266 $values = array_merge($values, $details["{$contactId}"]);
1269 $tokenSubject = CRM_Utils_Token
::replaceContactTokens($subject, $values, FALSE, $subjectToken, FALSE, $escapeSmarty);
1270 $tokenSubject = CRM_Utils_Token
::replaceHookTokens($tokenSubject, $values, $categories, FALSE, $escapeSmarty);
1273 if ($values['preferred_mail_format'] == 'Text' ||
$values['preferred_mail_format'] == 'Both') {
1274 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1275 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1281 if ($values['preferred_mail_format'] == 'HTML' ||
$values['preferred_mail_format'] == 'Both') {
1282 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1283 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1289 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
1290 // also add the contact tokens to the template
1291 $smarty->assign_by_ref('contact', $values);
1293 $tokenSubject = $smarty->fetch("string:$tokenSubject");
1294 $tokenText = $smarty->fetch("string:$tokenText");
1295 $tokenHtml = $smarty->fetch("string:$tokenHtml");
1299 if (self
::sendMessage(
1316 return array($sent, $activity->id
);
1319 static function sendSMS(&$contactDetails,
1321 &$smsParams = array(),
1325 if ($userID == NULL) {
1326 $session = CRM_Core_Session
::singleton();
1327 $userID = $session->get('userID');
1330 $text = &$activityParams['text_message'];
1331 $html = &$activityParams['html_message'];
1334 // token replacement of addressee/email/postal greetings
1335 // get the tokens added in subject and message
1336 $messageToken = CRM_Utils_Token
::getTokens($text);
1337 $messageToken = array_merge($messageToken,
1338 CRM_Utils_Token
::getTokens($html)
1341 //create the meta level record first ( sms activity )
1342 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1347 // CRM-6265: save both text and HTML parts in details (if present)
1348 if ($html and $text) {
1349 $details = "-ALTERNATIVE ITEM 0-\n$html\n-ALTERNATIVE ITEM 1-\n$text\n-ALTERNATIVE END-\n";
1352 $details = $html ?
$html : $text;
1355 $activitySubject = $activityParams['activity_subject'];
1356 $activityParams = array(
1357 'source_contact_id' => $userID,
1358 'activity_type_id' => $activityTypeID,
1359 'activity_date_time' => date('YmdHis'),
1360 'subject' => $activitySubject,
1361 'details' => $details,
1362 // FIXME: check for name Completed and get ID from that lookup
1366 $activity = self
::create($activityParams);
1367 $activityID = $activity->id
;
1369 $returnProperties = array();
1371 if (isset($messageToken['contact'])) {
1372 foreach ($messageToken['contact'] as $key => $value) {
1373 $returnProperties[$value] = 1;
1379 CRM_Utils_Hook
::tokens($tokens);
1380 $categories = array_keys($tokens);
1382 // get token details for contacts, call only if tokens are used
1384 if (!empty($returnProperties) ||
!empty($tokens)) {
1385 list($details) = CRM_Utils_Token
::getTokenDetails($contactIds,
1389 'CRM_Activity_BAO_Activity'
1393 $escapeSmarty = $sent = FALSE;
1394 foreach ($contactDetails as $values) {
1395 $contactId = $values['contact_id'];
1397 if (!empty($details) && is_array($details["{$contactId}"])) {
1398 // unset email from details since it always returns primary email address
1399 unset($details["{$contactId}"]['email']);
1400 unset($details["{$contactId}"]['email_id']);
1401 $values = array_merge($values, $details["{$contactId}"]);
1404 $tokenText = CRM_Utils_Token
::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty);
1405 $tokenText = CRM_Utils_Token
::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty);
1407 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty);
1408 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty);
1410 // Only send if the phone is of type mobile
1411 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
1412 if ($values['phone_type_id'] == CRM_Utils_Array
::value('Mobile', $phoneTypes)) {
1413 $smsParams['To'] = $values['phone'];
1416 $smsParams['To'] = '';
1419 if (self
::sendSMSMessage(
1426 // even a single successful delivery should set this falg to true
1431 return array($sent, $activity->id
);
1435 * send the sms message to a specific contact
1437 * @param int $toID the contact id of the recipient
1438 * @param int $activityID the activity ID that tracks the message
1439 * @param array $smsParams the params used for sending sms
1441 * @return boolean true if successfull else false.
1445 static function sendSMSMessage($toID,
1448 $smsParams = array(),
1452 $toPhoneNumber = "";
1454 if ($smsParams['To']) {
1455 $toPhoneNumber = trim($smsParams['To']);
1458 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
1459 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($toID, FALSE, 'Mobile', $filters);
1460 //to get primary mobile ph,if not get a first mobile ph
1461 if (!empty($toPhoneNumbers)) {
1462 $toPhoneNumerDetails = reset($toPhoneNumbers);
1463 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumerDetails);
1464 //contact allows to send sms
1469 // make sure both phone are valid
1470 // and that the recipient wants to receive sms
1471 if (empty($toPhoneNumber) or $toDoNotSms) {
1475 $message = $tokenHtml ?
$tokenHtml : $tokenText;
1476 $recipient = $smsParams['To'];
1477 $smsParams['contact_id'] = $toID;
1478 $smsParams['parent_activity_id'] = $activityID;
1480 $providerObj = CRM_SMS_Provider
::singleton(array('provider_id' => $smsParams['provider_id']));
1481 if (!$providerObj->send($recipient, $smsParams, $message, NULL)) {
1485 // add activity target record for every sms that is send
1486 $activityTargetParams = array(
1487 'activity_id' => $activityID,
1488 'contact_id' => $toID,
1489 'record_type' => 'Target'
1491 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1497 * send the message to a specific contact
1499 * @param string $from the name and email of the sender
1500 * @param int $toID the contact id of the recipient
1501 * @param string $subject the subject of the message
1502 * @param string $message the message contents
1503 * @param string $emailAddress use this 'to' email address instead of the default Primary address
1504 * @param int $activityID the activity ID that tracks the message
1506 * @return boolean true if successfull else false.
1510 static function sendMessage($from,
1518 $attachments = NULL,
1522 list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact
::getContactDetails($toID);
1523 if ($emailAddress) {
1524 $toEmail = trim($emailAddress);
1527 // make sure both email addresses are valid
1528 // and that the recipient wants to receive email
1529 if (empty($toEmail) or $toDoNotEmail) {
1532 if (!trim($toDisplayName)) {
1533 $toDisplayName = $toEmail;
1536 // create the params array
1537 $mailParams = array(
1538 'groupName' => 'Activity Email Sender',
1540 'toName' => $toDisplayName,
1541 'toEmail' => $toEmail,
1542 'subject' => $subject,
1545 'text' => $text_message,
1546 'html' => $html_message,
1547 'attachments' => $attachments,
1550 if (!CRM_Utils_Mail
::send($mailParams)) {
1554 // add activity target record for every mail that is send
1555 $activityTargetParams = array(
1556 'activity_id' => $activityID,
1557 'contact_id' => $toID,
1558 'record_type' => 'Target'
1560 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
1565 * combine all the importable fields from the lower levels object
1567 * The ordering is important, since currently we do not have a weight
1568 * scheme. Adding weight is super important and should be done in the
1569 * next week or so, before this can be called complete.
1573 * @return array array of importable Fields
1577 static function &importableFields($status = FALSE) {
1578 if (!self
::$_importableFields) {
1579 if (!self
::$_importableFields) {
1580 self
::$_importableFields = array();
1583 $fields = array('' => array('title' => ts('- do not import -')));
1586 $fields = array('' => array('title' => ts('- Activity Fields -')));
1589 $tmpFields = CRM_Activity_DAO_Activity
::import();
1590 $contactFields = CRM_Contact_BAO_Contact
::importableFields('Individual', NULL);
1592 // Using new Dedupe rule.
1593 $ruleParams = array(
1594 'contact_type' => 'Individual',
1595 'used' => 'Unsupervised',
1597 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1599 $tmpConatctField = array();
1600 if (is_array($fieldsArray)) {
1601 foreach ($fieldsArray as $value) {
1602 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1607 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1608 $tmpConatctField[trim($value)] = $contactFields[trim($value)];
1609 $tmpConatctField[trim($value)]['title'] = $tmpConatctField[trim($value)]['title'] . " (match to contact)";
1612 $tmpConatctField['external_identifier'] = $contactFields['external_identifier'];
1613 $tmpConatctField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " (match to contact)";
1614 $fields = array_merge($fields, $tmpConatctField);
1615 $fields = array_merge($fields, $tmpFields);
1616 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
1617 self
::$_importableFields = $fields;
1619 return self
::$_importableFields;
1623 * To get the Activities of a target contact
1625 * @param $contactId Integer ContactId of the contact whose activities
1628 * @return array array of activity fields
1631 static function getContactActivity($contactId) {
1632 $activities = array();
1634 // First look for activities where contactId is one of the targets
1637 FROM civicrm_activity_contact
1638 WHERE contact_id = $contactId
1640 $dao = CRM_Core_DAO
::executeQuery($query);
1641 while ($dao->fetch()) {
1642 if ($dao->record_type
== 'Target') {
1643 $activities[$dao->activity_id
]['targets'][$contactId] = $contactId;
1645 else if ($dao->record_type
== 'Assignee') {
1646 $activities[$dao->activity_id
]['asignees'][$contactId] = $contactId;
1649 // do source stuff here
1650 $activities[$dao->activity_id
]['source_contact_id'][] = $contactId;
1654 $activityIds = array_keys($activities);
1655 if (count($activityIds) < 1) {
1659 $activityIds = implode(',', $activityIds);
1661 SELECT activity.id as activity_id,
1663 subject, location, activity_date_time, details, status_id
1664 FROM civicrm_activity activity
1665 WHERE activity.id IN ($activityIds)";
1667 $dao = CRM_Core_DAO
::executeQuery($query);
1669 $activityTypes = CRM_Core_OptionGroup
::values('activity_type');
1670 $activityStatuses = CRM_Core_OptionGroup
::values('activity_status');
1672 while ($dao->fetch()) {
1673 $activities[$dao->activity_id
]['source_contact_id'] = $dao->source_contact_id
;
1674 $activities[$dao->activity_id
]['id'] = $dao->activity_id
;
1675 $activities[$dao->activity_id
]['activity_type_id'] = $dao->activity_type_id
;
1676 $activities[$dao->activity_id
]['subject'] = $dao->subject
;
1677 $activities[$dao->activity_id
]['location'] = $dao->location
;
1678 $activities[$dao->activity_id
]['activity_date_time'] = $dao->activity_date_time
;
1679 $activities[$dao->activity_id
]['details'] = $dao->details
;
1680 $activities[$dao->activity_id
]['status_id'] = $dao->status_id
;
1681 $activities[$dao->activity_id
]['activity_name'] = $activityTypes[$dao->activity_type_id
];
1682 $activities[$dao->activity_id
]['status'] = $activityStatuses[$dao->status_id
];
1688 * Function to add activity for Membership/Event/Contribution
1690 * @param object $activity (reference) perticular component object
1691 * @param string $activityType for Membership Signup or Renewal
1697 static function addActivity(&$activity,
1698 $activityType = 'Membership Signup',
1699 $targetContactID = NULL
1701 if ($activity->__table
== 'civicrm_membership') {
1702 $membershipType = CRM_Member_PseudoConstant
::membershipType($activity->membership_type_id
);
1704 if (!$membershipType) {
1705 $membershipType = ts('Membership');
1708 $subject = "{$membershipType}";
1710 if (!empty($activity->source
) && $activity->source
!= 'null') {
1711 $subject .= " - {$activity->source}";
1714 if ($activity->owner_membership_id
) {
1717 FROM civicrm_contact, civicrm_membership
1718 WHERE civicrm_contact.id = civicrm_membership.contact_id
1719 AND civicrm_membership.id = $activity->owner_membership_id
1721 $displayName = CRM_Core_DAO
::singleValueQuery($query);
1722 $subject .= " (by {$displayName})";
1725 $subject .= " - Status: " . CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id
);
1726 // CRM-72097 changed from start date to today
1727 $date = date('YmdHis');
1728 $component = 'Membership';
1730 elseif ($activity->__table
== 'civicrm_participant') {
1731 $event = CRM_Event_BAO_Event
::getEvents(TRUE, $activity->event_id
, TRUE, FALSE);
1733 $roles = CRM_Event_PseudoConstant
::participantRole();
1734 $status = CRM_Event_PseudoConstant
::participantStatus();
1736 $subject = $event[$activity->event_id
];
1737 if (CRM_Utils_Array
::value($activity->role_id
, $roles)) {
1738 $subject .= ' - ' . $roles[$activity->role_id
];
1740 if (CRM_Utils_Array
::value($activity->status_id
, $status)) {
1741 $subject .= ' - ' . $status[$activity->status_id
];
1743 $date = date('YmdHis');
1744 if ($activityType != 'Email') {
1745 $activityType = 'Event Registration';
1747 $component = 'Event';
1749 elseif ($activity->__table
== 'civicrm_contribution') {
1750 //create activity record only for Completed Contributions
1751 if ($activity->contribution_status_id
!= 1) {
1757 $subject .= CRM_Utils_Money
::format($activity->total_amount
, $activity->currency
);
1758 if (!empty($activity->source
) && $activity->source
!= 'null') {
1759 $subject .= " - {$activity->source}";
1761 $date = CRM_Utils_Date
::isoToMysql($activity->receive_date
);
1762 $activityType = $component = 'Contribution';
1764 $activityParams = array(
1765 'source_contact_id' => $activity->contact_id
,
1766 'source_record_id' => $activity->id
,
1767 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
1771 'subject' => $subject,
1772 'activity_date_time' => $date,
1773 'is_test' => $activity->is_test
,
1774 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
1778 'skipRecentView' => TRUE,
1779 'campaign_id' => $activity->campaign_id
,
1782 // create activity with target contacts
1783 $session = CRM_Core_Session
::singleton();
1784 $id = $session->get('userID');
1786 $activityParams['source_contact_id'] = $id;
1787 $activityParams['target_contact_id'][] = $activity->contact_id
;
1791 if ($targetContactID) {
1792 $activityParams['target_contact_id'][] = $targetContactID;
1794 if (is_a(self
::create($activityParams), 'CRM_Core_Error')) {
1795 CRM_Core_Error
::fatal("Failed creating Activity for $component of id {$activity->id}");
1801 * Function to get Parent activity for currently viewd activity
1803 * @param int $activityId current activity id
1805 * @return int $parentId Id of parent acyivity otherwise false.
1808 static function getParentActivity($activityId) {
1809 static $parentActivities = array();
1811 $activityId = CRM_Utils_Type
::escape($activityId, 'Integer');
1813 if (!array_key_exists($activityId, $parentActivities)) {
1814 $parentActivities[$activityId] = array();
1816 $parentId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1821 $parentActivities[$activityId] = $parentId ?
$parentId : FALSE;
1824 return $parentActivities[$activityId];
1828 * Function to get total count of prior revision of currently viewd activity
1830 * @param int $activityId current activity id
1832 * @return int $params count of prior acyivities otherwise false.
1835 static function getPriorCount($activityID) {
1836 static $priorCounts = array();
1838 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1840 if (!array_key_exists($activityID, $priorCounts)) {
1841 $priorCounts[$activityID] = array();
1842 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1849 SELECT count( id ) AS cnt
1850 FROM civicrm_activity
1851 WHERE ( id = {$originalID} OR original_id = {$originalID} )
1852 AND is_current_revision = 0
1853 AND id < {$activityID}
1855 $params = array(1 => array($originalID, 'Integer'));
1856 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1858 $priorCounts[$activityID] = $count ?
$count : 0;
1861 return $priorCounts[$activityID];
1865 * Function to get all prior activities of currently viewd activity
1867 * @param int $activityId current activity id
1869 * @return array $result prior acyivities info.
1872 static function getPriorAcitivities($activityID, $onlyPriorRevisions = FALSE) {
1873 static $priorActivities = array();
1875 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1876 $index = $activityID . '_' . (int) $onlyPriorRevisions;
1878 if (!array_key_exists($index, $priorActivities)) {
1879 $priorActivities[$index] = array();
1881 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1887 SELECT c.display_name as name, cl.modified_date as date, ca.id as activityID
1888 FROM civicrm_log cl, civicrm_contact c, civicrm_activity ca
1889 WHERE (ca.id = %1 OR ca.original_id = %1)
1890 AND cl.entity_table = 'civicrm_activity'
1891 AND cl.entity_id = ca.id
1892 AND cl.modified_id = c.id
1894 if ($onlyPriorRevisions) {
1895 $query .= " AND ca.id < {$activityID}";
1897 $query .= " ORDER BY ca.id DESC";
1899 $params = array(1 => array($originalID, 'Integer'));
1900 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1902 while ($dao->fetch()) {
1903 $priorActivities[$index][$dao->activityID
]['id'] = $dao->activityID
;
1904 $priorActivities[$index][$dao->activityID
]['name'] = $dao->name
;
1905 $priorActivities[$index][$dao->activityID
]['date'] = $dao->date
;
1906 $priorActivities[$index][$dao->activityID
]['link'] = 'javascript:viewActivity( $dao->activityID );';
1911 return $priorActivities[$index];
1915 * Function to find the latest revision of a given activity
1917 * @param int $activityId prior activity id
1919 * @return int $params current activity id.
1922 static function getLatestActivityId($activityID) {
1923 static $latestActivityIds = array();
1925 $activityID = CRM_Utils_Type
::escape($activityID, 'Integer');
1927 if (!array_key_exists($activityID, $latestActivityIds)) {
1928 $latestActivityIds[$activityID] = array();
1930 $originalID = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity',
1935 $activityID = $originalID;
1937 $params = array(1 => array($activityID, 'Integer'));
1938 $query = "SELECT id from civicrm_activity where original_id = %1 and is_current_revision = 1";
1940 $latestActivityIds[$activityID] = CRM_Core_DAO
::singleValueQuery($query, $params);
1943 return $latestActivityIds[$activityID];
1947 * Function to create a follow up a given activity
1949 * @activityId int activity id of parent activity
1951 * @param array $activity details
1955 static function createFollowupActivity($activityId, $params) {
1960 $session = CRM_Core_Session
::singleton();
1962 $followupParams = array();
1963 $followupParams['parent_id'] = $activityId;
1964 $followupParams['source_contact_id'] = $session->get('userID');
1965 $followupParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
1967 $followupParams['activity_type_id'] = $params['followup_activity_type_id'];
1968 // Get Subject of Follow-up Activiity, CRM-4491
1969 $followupParams['subject'] = CRM_Utils_Array
::value('followup_activity_subject', $params);
1971 //create target contact for followup
1972 if (CRM_Utils_Array
::value('target_contact_id', $params)) {
1973 $followupParams['target_contact_id'] = $params['target_contact_id'];
1976 $followupParams['activity_date_time'] = CRM_Utils_Date
::processDate($params['followup_date'],
1977 $params['followup_date_time']
1979 $followupActivity = self
::create($followupParams);
1981 return $followupActivity;
1985 * Function to get Activity specific File according activity type Id.
1987 * @param int $activityTypeId activity id
1989 * @return if file exists returns $activityTypeFile activity filename otherwise false.
1993 static function getFileForActivityTypeId($activityTypeId, $crmDir = 'Activity') {
1994 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1996 if ($activityTypes[$activityTypeId]['name']) {
1997 $activityTypeFile = CRM_Utils_String
::munge(ucwords($activityTypes[$activityTypeId]['name']), '', 0);
2003 global $civicrm_root;
2004 $config = CRM_Core_Config
::singleton();
2005 if (!file_exists(rtrim($civicrm_root, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2006 if (empty($config->customPHPPathDir
)) {
2009 elseif (!file_exists(rtrim($config->customPHPPathDir
, '/') . "/CRM/{$crmDir}/Form/Activity/{$activityTypeFile}.php")) {
2014 return $activityTypeFile;
2018 * Function to restore the activity
2020 * @param array $params associated array
2026 public static function restoreActivity(&$params) {
2027 $activity = new CRM_Activity_DAO_Activity();
2028 $activity->copyValues($params);
2030 $activity->is_deleted
= 0;
2031 $result = $activity->save();
2037 * Get the exportable fields for Activities
2039 * @param string $name if it is called by case $name = Case else $name = Activity
2041 * @return array array of exportable Fields
2045 static function &exportableFields($name = 'Activity') {
2046 if (!isset(self
::$_exportableFields[$name])) {
2047 self
::$_exportableFields[$name] = array();
2049 // TO DO, ideally we should retrieve all fields from xml, in this case since activity processing is done
2050 // my case hence we have defined fields as case_*
2051 if ($name == 'Activity') {
2052 $exportableFields = CRM_Activity_DAO_Activity
::export();
2053 if (isset($exportableFields['activity_campaign_id'])) {
2054 $exportableFields['activity_campaign'] = array('title' => ts('Campaign Title'));
2056 $exportableFields['source_contact_id']['title'] = ts('Source Contact ID');
2057 $exportableFields['source_contact'] = array(
2058 'title' => ts('Source Contact'),
2059 'type' => CRM_Utils_Type
::T_STRING
,
2063 $Activityfields = array(
2064 'activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2065 'activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2067 $fields = array_merge($Activityfields, $exportableFields);
2070 //set title to activity fields
2072 'case_activity_subject' => array('title' => ts('Activity Subject'), 'type' => CRM_Utils_Type
::T_STRING
),
2073 'case_source_contact_id' => array('title' => ts('Activity Reporter'), 'type' => CRM_Utils_Type
::T_STRING
),
2074 'case_recent_activity_date' => array('title' => ts('Activity Actual Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2075 'case_scheduled_activity_date' => array('title' => ts('Activity Scheduled Date'), 'type' => CRM_Utils_Type
::T_DATE
),
2076 'case_recent_activity_type' => array('title' => ts('Activity Type'), 'type' => CRM_Utils_Type
::T_STRING
),
2077 'case_activity_status' => array('title' => ts('Activity Status'), 'type' => CRM_Utils_Type
::T_STRING
),
2078 'case_activity_duration' => array('title' => ts('Activity Duration'), 'type' => CRM_Utils_Type
::T_INT
),
2079 'case_activity_medium_id' => array('title' => ts('Activity Medium'), 'type' => CRM_Utils_Type
::T_INT
),
2080 'case_activity_details' => array('title' => ts('Activity Details'), 'type' => CRM_Utils_Type
::T_TEXT
),
2081 'case_activity_is_auto' => array('title' => ts('Activity Auto-generated?'), 'type' => CRM_Utils_Type
::T_BOOLEAN
),
2084 // add custom data for cases
2085 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
2088 // add custom data for case activities
2089 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Activity'));
2091 self
::$_exportableFields[$name] = $fields;
2093 return self
::$_exportableFields[$name];
2097 * Get the allowed profile fields for Activities
2099 * @return array array of activity profile Fields
2102 static function getProfileFields() {
2103 $exportableFields = self
::exportableFields('Activity');
2104 $skipFields = array('activity_id', 'activity_type', 'source_contact_id', 'activity_campaign', 'activity_is_test', 'is_current_revision', 'activity_is_deleted',);
2105 $config = CRM_Core_Config
::singleton();
2106 if (!in_array('CiviCampaign', $config->enableComponents
)) {
2107 $skipFields[] = 'activity_engagement_level';
2110 foreach ($skipFields as $field) {
2111 if (isset($exportableFields[$field])) {
2112 unset($exportableFields[$field]);
2116 // hack to use 'activity_type_id' instead of 'activity_type'
2117 $exportableFields['activity_status_id'] = $exportableFields['activity_status'];
2118 unset($exportableFields['activity_status']);
2120 return $exportableFields;
2124 * This function delete activity record related to contact record,
2125 * when there are no target and assignee record w/ other contact.
2127 * @param int $contactId contactId
2132 public static function cleanupActivity($contactId) {
2138 $transaction = new CRM_Core_Transaction();
2140 // delete activity if there is no record in
2141 // civicrm_activity_contact
2142 // pointing to any other contact record.
2143 $activity = new CRM_Activity_DAO_Activity();
2144 $activity->source_contact_id
= $contactId;
2147 while ($activity->fetch()) {
2152 FROM civicrm_activity_contact
2153 WHERE activity_id = %1
2154 AND contact_id <> %2
2157 1 => array($activity->id
, 'Integer'),
2158 2 => array($contactId, 'Integer')
2161 // finally delete activity.
2162 if (CRM_Core_DAO
::singleValueQuery($sql)) {
2163 $activityParams = array('id' => $activity->id
);
2164 $result = self
::deleteActivity($activityParams);
2169 $transaction->commit();
2175 * Does user has sufficient permission for view/edit activity record.
2177 * @param int $activityId activity record id.
2178 * @param int $action edit/view
2180 * @return boolean $allow true/false
2183 public static function checkPermission($activityId, $action) {
2186 !in_array($action, array(CRM_Core_Action
::UPDATE
, CRM_Core_Action
::VIEW
))
2191 $activity = new CRM_Activity_DAO_Activity();
2192 $activity->id
= $activityId;
2193 if (!$activity->find(TRUE)) {
2197 //component related permissions.
2198 $compPermissions = array(
2199 'CiviCase' => array('administer CiviCase',
2200 'access my cases and activities',
2201 'access all cases and activities',
2203 'CiviMail' => array('access CiviMail'),
2204 'CiviEvent' => array('access CiviEvent'),
2205 'CiviGrant' => array('access CiviGrant'),
2206 'CiviPledge' => array('access CiviPledge'),
2207 'CiviMember' => array('access CiviMember'),
2208 'CiviReport' => array('access CiviReport'),
2209 'CiviContribute' => array('access CiviContribute'),
2210 'CiviCampaign' => array('administer CiviCampaign'),
2213 //return early when it is case activity.
2214 $isCaseActivity = CRM_Case_BAO_Case
::isCaseActivity($activityId);
2215 //check for civicase related permission.
2216 if ($isCaseActivity) {
2218 foreach ($compPermissions['CiviCase'] as $per) {
2219 if (CRM_Core_Permission
::check($per)) {
2225 //check for case specific permissions.
2228 if ($action == CRM_Core_Action
::UPDATE
) {
2231 $allow = CRM_Case_BAO_Case
::checkPermission($activityId,
2233 $activity->activity_type_id
2241 //first check the component permission.
2244 FROM civicrm_option_value val
2245 INNER JOIN civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )
2246 WHERE val.value = %2";
2247 $params = array(1 => array('activity_type', 'String'),
2248 2 => array($activity->activity_type_id
, 'Integer'),
2250 $componentId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2253 $componentName = CRM_Core_Component
::getComponentName($componentId);
2254 $compPermission = CRM_Utils_Array
::value($componentName, $compPermissions);
2256 //here we are interesting in any single permission.
2257 if (is_array($compPermission)) {
2258 foreach ($compPermission as $per) {
2259 if (CRM_Core_Permission
::check($per)) {
2267 //check for this permission related to contact.
2268 $permission = CRM_Core_Permission
::VIEW
;
2269 if ($action == CRM_Core_Action
::UPDATE
) {
2270 $permission = CRM_Core_Permission
::EDIT
;
2273 //check for source contact.
2274 if (!$componentId ||
$allow) {
2275 $allow = CRM_Contact_BAO_Contact_Permission
::allow($activity->source_contact_id
, $permission);
2278 //check for target and assignee contacts.
2280 //first check for supper permission.
2281 $supPermission = 'view all contacts';
2282 if ($action == CRM_Core_Action
::UPDATE
) {
2283 $supPermission = 'edit all contacts';
2285 $allow = CRM_Core_Permission
::check($supPermission);
2287 //user might have sufficient permission, through acls.
2290 //get the target contacts.
2291 $targetContacts = CRM_Activity_BAO_ActivityTarget
::retrieveTargetIdsByActivityId($activity->id
);
2292 foreach ($targetContacts as $cnt => $contactId) {
2293 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2299 //get the assignee contacts.
2301 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment
::retrieveAssigneeIdsByActivityId($activity->id
);
2302 foreach ($assigneeContacts as $cnt => $contactId) {
2303 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactId, $permission)) {
2316 * This function is a wrapper for ajax activity selector
2318 * @param array $params associated array for params record id.
2320 * @return array $contactActivities associated array of contact activities
2323 public static function getContactActivitySelector(&$params) {
2324 // format the params
2325 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2326 $params['rowCount'] = $params['rp'];
2327 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2328 $params['caseId'] = NULL;
2329 $context = CRM_Utils_Array
::value('context', $params);
2331 // get contact activities
2332 $activities = CRM_Activity_BAO_Activity
::getActivities($params);
2335 $params['total'] = CRM_Activity_BAO_Activity
::getActivitiesCount($params);
2337 // format params and add links
2338 $contactActivities = array();
2340 if (!empty($activities)) {
2341 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
2343 // check logged in user for permission
2344 $page = new CRM_Core_Page();
2345 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2346 $permissions = array($page->_permission
);
2347 if (CRM_Core_Permission
::check('delete activities')) {
2348 $permissions[] = CRM_Core_Permission
::DELETE
;
2351 $mask = CRM_Core_Action
::mask($permissions);
2353 foreach ($activities as $activityId => $values) {
2354 $contactActivities[$activityId]['activity_type'] = $values['activity_type'];
2355 $contactActivities[$activityId]['subject'] = $values['subject'];
2356 if ($params['contact_id'] == $values['source_contact_id']) {
2357 $contactActivities[$activityId]['source_contact'] = $values['source_contact_name'];
2359 elseif ($values['source_contact_id']) {
2360 $contactActivities[$activityId]['source_contact'] = CRM_Utils_System
::href($values['source_contact_name'], 'civicrm/contact/view', "reset=1&cid={$values['source_contact_id']}");
2363 $contactActivities[$activityId]['source_contact'] = '<em>n/a</em>';
2366 if (isset($values['mailingId']) && !empty($values['mailingId'])) {
2367 $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");
2369 elseif (CRM_Utils_Array
::value('recipients', $values)) {
2370 $contactActivities[$activityId]['target_contact'] = $values['recipients'];
2372 elseif (!$values['target_contact_name']) {
2373 $contactActivities[$activityId]['target_contact'] = '<em>n/a</em>';
2375 elseif (!empty($values['target_contact_name'])) {
2377 $contactActivities[$activityId]['target_contact'] = '';
2378 foreach ($values['target_contact_name'] as $tcID => $tcName) {
2379 if ($tcID && $count < 5) {
2380 $contactActivities[$activityId]['target_contact'] .= CRM_Utils_System
::href($tcName, 'civicrm/contact/view', "reset=1&cid={$tcID}");
2383 $contactActivities[$activityId]['target_contact'] .= "; ";
2387 $contactActivities[$activityId]['target_contact'] .= "(" . ts('more') . ")";
2394 if (empty($values['assignee_contact_name'])) {
2395 $contactActivities[$activityId]['assignee_contact'] = '<em>n/a</em>';
2397 elseif (!empty($values['assignee_contact_name'])) {
2399 $contactActivities[$activityId]['assignee_contact'] = '';
2400 foreach ($values['assignee_contact_name'] as $acID => $acName) {
2401 if ($acID && $count < 5) {
2402 $contactActivities[$activityId]['assignee_contact'] .= CRM_Utils_System
::href($acName, 'civicrm/contact/view', "reset=1&cid={$acID}");
2405 $contactActivities[$activityId]['assignee_contact'] .= "; ";
2409 $contactActivities[$activityId]['assignee_contact'] .= "(" . ts('more') . ")";
2415 if ( $values['activity_type'] == 'Bulk Email'){
2416 $contactActivities[$activityId]['openstats'] = "Opens: ".
2417 count(CRM_Mailing_Event_BAO_Opened
::getRows(
2418 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, $params['contact_id']
2421 count(CRM_Mailing_Event_BAO_TrackableURLOpen
::getRows(
2422 CRM_Utils_Array
::value('source_record_id', $values), NULL, FALSE, NULL, NULL, NULL, NULL, $params['contact_id']
2425 $contactActivities[$activityId]['openstats'] = '';
2428 $contactActivities[$activityId]['activity_date'] = CRM_Utils_Date
::customFormat($values['activity_date_time']);
2429 $contactActivities[$activityId]['status'] = $activityStatus[$values['status_id']];
2431 // add class to this row if overdue
2432 $contactActivities[$activityId]['class'] = '';
2433 if (CRM_Utils_Date
::overdue(CRM_Utils_Array
::value('activity_date_time', $values))
2434 && CRM_Utils_Array
::value('status_id', $values) == 1
2436 $contactActivities[$activityId]['class'] = 'status-overdue';
2439 $contactActivities[$activityId]['class'] = 'status-ontime';
2443 $contactActivities[$activityId]['links'] = '';
2444 $accessMailingReport = FALSE;
2445 if (CRM_Utils_Array
::value('mailingId', $values)) {
2446 $accessMailingReport = TRUE;
2449 $actionLinks = CRM_Activity_Selector_Activity
::actionLinks(
2450 CRM_Utils_Array
::value('activity_type_id', $values),
2451 CRM_Utils_Array
::value('source_record_id', $values),
2452 $accessMailingReport,
2453 CRM_Utils_Array
::value('activity_id', $values)
2456 $actionMask = array_sum(array_keys($actionLinks)) & $mask;
2458 $contactActivities[$activityId]['links'] = CRM_Core_Action
::formLink($actionLinks,
2461 'id' => $values['activity_id'],
2462 'cid' => $params['contact_id'],
2464 'caseid' => CRM_Utils_Array
::value('case_id', $values),
2470 return $contactActivities;
2474 * Used to copy custom fields and attachments from an existing activity to another.
2475 * see CRM_Case_Page_AJAX::_convertToCaseActivity() for example
2477 static function copyExtendedActivityData($params) {
2478 // attach custom data to the new activity
2479 $customParams = $htmlType = array();
2480 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($params['activityID'], 'Activity');
2482 if (!empty($customValues)) {
2483 $fieldIds = implode(', ', array_keys($customValues));
2484 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2485 $result = CRM_Core_DAO
::executeQuery($sql);
2487 while ($result->fetch()) {
2488 $htmlType[] = $result->id
;
2491 foreach ($customValues as $key => $value) {
2492 if ($value !== NULL) { // CRM-10542
2493 if (in_array($key, $htmlType)) {
2494 $fileValues = CRM_Core_BAO_File
::path($value, $params['activityID']);
2495 $customParams["custom_{$key}_-1"] = array(
2496 'name' => $fileValues[0],
2497 'path' => $fileValues[1],
2501 $customParams["custom_{$key}_-1"] = $value;
2505 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, CRM_Core_DAO
::$_nullArray, 'civicrm_activity',
2506 $params['mainActivityId'], 'Activity'
2510 // copy activity attachments ( if any )
2511 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $params['activityID'], 'civicrm_activity', $params['mainActivityId']);