3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
37 * This class contains the functions for Case Management.
40 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
43 * Static field for all the case information that we can potentially export.
47 static $_exportableFields = NULL;
52 public function __construct() {
53 parent
::__construct();
57 * Is CiviCase enabled?
61 public static function enabled() {
62 $config = CRM_Core_Config
::singleton();
63 return in_array('CiviCase', $config->enableComponents
);
67 * Create a case object.
69 * The function extracts all the params it needs to initialize the create a
70 * case object. the params array could contain additional unused name/value
73 * @param array $params
74 * (reference ) an assoc array of name/value pairs.
76 * @return CRM_Case_BAO_Case
78 public static function add(&$params) {
79 $caseDAO = new CRM_Case_DAO_Case();
80 $caseDAO->copyValues($params);
81 return $caseDAO->save();
85 * Given the list of params in the params array, fetch the object
86 * and store the values in the values array.
88 * @param array $params
89 * Input parameters to find object.
90 * @param array $values
91 * Output values of the object.
93 * The array that holds all the db ids.
95 * @return CRM_Case_BAO_Case|null
96 * The found object or null
98 public static function &getValues(&$params, &$values, &$ids) {
99 $case = new CRM_Case_BAO_Case();
101 $case->copyValues($params);
103 if ($case->find(TRUE)) {
104 $ids['case'] = $case->id
;
105 CRM_Core_DAO
::storeValues($case, $values);
112 * Takes an associative array and creates a case object.
114 * @param array $params
115 * (reference) an assoc array of name/value pairs.
117 * @return CRM_Case_BAO_Case
119 public static function &create(&$params) {
120 $transaction = new CRM_Core_Transaction();
122 if (!empty($params['id'])) {
123 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
126 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
129 $case = self
::add($params);
131 if (!empty($params['custom']) &&
132 is_array($params['custom'])
134 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
137 if (is_a($case, 'CRM_Core_Error')) {
138 $transaction->rollback();
142 if (!empty($params['id'])) {
143 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
146 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
148 $transaction->commit();
150 //we are not creating log for case
151 //since case log can be tracked using log for activity.
156 * Create case contact record.
158 * @param array $params
159 * case_id, contact_id
163 public static function addCaseToContact($params) {
164 $caseContact = new CRM_Case_DAO_CaseContact();
165 $caseContact->case_id
= $params['case_id'];
166 $caseContact->contact_id
= $params['contact_id'];
167 $caseContact->find(TRUE);
168 $caseContact->save();
170 // add to recently viewed
171 $caseType = CRM_Case_BAO_Case
::getCaseType($caseContact->case_id
);
172 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
173 "action=view&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
176 $title = CRM_Contact_BAO_Contact
::displayName($caseContact->contact_id
) . ' - ' . $caseType;
178 $recentOther = array();
179 if (CRM_Core_Permission
::checkActionPermission('CiviCase', CRM_Core_Action
::DELETE
)) {
180 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/case',
181 "action=delete&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
185 // add the recently created case
186 CRM_Utils_Recent
::add($title,
188 $caseContact->case_id
,
190 $params['contact_id'],
199 * Delete case contact record.
203 public static function deleteCaseContact($caseID) {
204 $caseContact = new CRM_Case_DAO_CaseContact();
205 $caseContact->case_id
= $caseID;
206 $caseContact->delete();
208 // delete the recently created Case
213 CRM_Utils_Recent
::del($caseRecent);
217 * Convert associative array names to values and vice-versa.
219 * This function is used by both the web form layer and the api. Note that
220 * the api needs the name => value conversion, also the view layer typically
221 * requires value => name conversion
223 * @param array $defaults
224 * @param string $property
225 * @param array $lookup
226 * @param bool $reverse
230 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
231 $id = $property . '_id';
233 $src = $reverse ?
$property : $id;
234 $dst = $reverse ?
$id : $property;
236 if (!array_key_exists($src, $defaults)) {
240 $look = $reverse ?
array_flip($lookup) : $lookup;
242 if (is_array($look)) {
243 if (!array_key_exists($defaults[$src], $look)) {
247 $defaults[$dst] = $look[$defaults[$src]];
252 * Retrieve DB object based on input parameters.
254 * It also stores all the retrieved values in the default array.
256 * @param array $params
257 * (reference ) an assoc array of name/value pairs.
258 * @param array $defaults
259 * (reference ) an assoc array to hold the name / value pairs.
260 * in a hierarchical manner
262 * (reference) the array that holds all the db ids.
264 * @return CRM_Case_BAO_Case
266 public static function retrieve(&$params, &$defaults, &$ids) {
267 $case = CRM_Case_BAO_Case
::getValues($params, $defaults, $ids);
272 * Process case activity add/delete
273 * takes an associative array and
275 * @param array $params
276 * (reference ) an assoc array of name/value pairs.
279 public static function processCaseActivity(&$params) {
280 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
281 $caseActivityDAO->activity_id
= $params['activity_id'];
282 $caseActivityDAO->case_id
= $params['case_id'];
284 $caseActivityDAO->find(TRUE);
285 $caseActivityDAO->save();
289 * Get the case subject for Activity.
291 * @param int $activityId
294 * @return string|null
296 public static function getCaseSubject($activityId) {
297 $caseActivity = new CRM_Case_DAO_CaseActivity();
298 $caseActivity->activity_id
= $activityId;
299 if ($caseActivity->find(TRUE)) {
300 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
309 * @param string $colName
314 public static function getCaseType($caseId, $colName = 'title') {
316 SELECT civicrm_case_type.{$colName} FROM civicrm_case
317 LEFT JOIN civicrm_case_type ON
318 civicrm_case.case_type_id = civicrm_case_type.id
319 WHERE civicrm_case.id = %1";
321 $queryParams = array(1 => array($caseId, 'Integer'));
323 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
327 * Delete the record that are associated with this case.
328 * record are deleted from case
331 * Id of the case to delete.
333 * @param bool $moveToTrash
338 public static function deleteCase($caseId, $moveToTrash = FALSE) {
339 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
342 $activities = self
::getCaseActivityDates($caseId);
344 foreach ($activities as $value) {
345 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
350 $transaction = new CRM_Core_Transaction();
352 $case = new CRM_Case_DAO_Case();
355 $result = $case->delete();
356 $transaction->commit();
359 $result = $case->is_deleted
= 1;
364 // CRM-7364, disable relationships
365 self
::enableDisableCaseRelationships($caseId, FALSE);
367 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
369 // remove case from recent items.
374 CRM_Utils_Recent
::del($caseRecent);
382 * Enable disable case related relationships.
386 * @param bool $enable
391 public static function enableDisableCaseRelationships($caseId, $enable) {
392 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
393 if (!empty($contactIds)) {
394 foreach ($contactIds as $cid) {
395 $roles = self
::getCaseRoles($cid, $caseId);
396 if (!empty($roles)) {
397 $relationshipIds = implode(',', array_keys($roles));
398 $enable = (int) $enable;
399 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
400 WHERE id IN ( {$relationshipIds} )";
401 CRM_Core_DAO
::executeQuery($query);
408 * Delete the activities related to case.
410 * @param int $activityId
411 * Id of the activity.
415 public static function deleteCaseActivity($activityId) {
416 $case = new CRM_Case_DAO_CaseActivity();
417 $case->activity_id
= $activityId;
422 * Retrieve contact_id by case_id.
427 * @param int $contactID
431 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
432 $caseContact = new CRM_Case_DAO_CaseContact();
433 $caseContact->case_id
= $caseId;
434 $caseContact->find();
435 $contactArray = array();
437 while ($caseContact->fetch()) {
438 if ($contactID != $caseContact->contact_id
) {
439 $contactArray[$count] = $caseContact->contact_id
;
444 return $contactArray;
448 * Look up a case using an activity ID.
450 * @param int $activityId
452 * @return int, case ID
454 public static function getCaseIdByActivityId($activityId) {
455 $originalId = CRM_Core_DAO
::singleValueQuery(
456 'SELECT original_id FROM civicrm_activity WHERE id = %1',
457 array('1' => array($activityId, 'Integer'))
459 $caseId = CRM_Core_DAO
::singleValueQuery(
460 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
462 '1' => array($activityId, 'Integer'),
463 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
470 * Retrieve contact names by caseId.
477 public static function getContactNames($caseId) {
478 $contactNames = array();
480 return $contactNames;
484 SELECT contact_a.sort_name name,
485 contact_a.display_name as display_name,
487 contact_a.birth_date as birth_date,
490 FROM civicrm_contact contact_a
491 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
492 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
493 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
494 WHERE civicrm_case_contact.case_id = %1";
496 $dao = CRM_Core_DAO
::executeQuery($query,
497 array(1 => array($caseId, 'Integer'))
499 while ($dao->fetch()) {
500 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
501 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
502 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
503 $contactNames[$dao->cid
]['email'] = $dao->email
;
504 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
505 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
506 $contactNames[$dao->cid
]['role'] = ts('Client');
509 return $contactNames;
513 * Retrieve case_id by contact_id.
515 * @param int $contactID
516 * @param bool $includeDeleted
517 * Include the deleted cases in result.
518 * @param null $caseType
522 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
525 FROM civicrm_case_contact cc
526 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
528 if (isset($caseType)) {
530 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
531 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
533 if (!isset($caseType)) {
534 $query .= "WHERE cc.contact_id = %1";
536 if (!$includeDeleted) {
537 $query .= " AND ca.is_deleted = 0";
540 $params = array(1 => array($contactID, 'Integer'));
541 $dao = CRM_Core_DAO
::executeQuery($query, $params);
543 $caseArray = array();
544 while ($dao->fetch()) {
545 $caseArray[] = $dao->id
;
553 * @param string $type
555 * @param null $condition
556 * @param int $isDeleted
560 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL, $isDeleted = 0) {
562 $session = CRM_Core_Session
::singleton();
563 $userID = $session->get('userID');
566 $actStatus = array_flip(CRM_Core_PseudoConstant
::activityStatus('name'));
567 $scheduledStatusId = $actStatus['Scheduled'];
570 civicrm_case.id as case_id,
571 civicrm_case.subject as case_subject,
572 civicrm_contact.id as contact_id,
573 civicrm_contact.sort_name as sort_name,
574 civicrm_phone.phone as phone,
575 civicrm_contact.contact_type as contact_type,
576 civicrm_contact.contact_sub_type as contact_sub_type,
577 t_act.activity_type_id,
578 c_type.title as case_type,
579 civicrm_case.case_type_id as case_type_id,
580 cov_status.label as case_status,
581 cov_status.label as case_status_name,
583 civicrm_case.start_date as case_start_date,
584 case_relation_type.label_b_a as case_role, ";
586 if ($type == 'upcoming') {
588 t_act.desired_date as case_scheduled_activity_date,
589 t_act.id as case_scheduled_activity_id,
590 t_act.act_type_name as case_scheduled_activity_type_name,
591 t_act.act_type AS case_scheduled_activity_type ";
593 elseif ($type == 'recent') {
595 t_act.desired_date as case_recent_activity_date,
596 t_act.id as case_recent_activity_id,
597 t_act.act_type_name as case_recent_activity_type_name,
598 t_act.act_type AS case_recent_activity_type ";
600 elseif ($type == 'any') {
602 t_act.desired_date as case_activity_date,
603 t_act.id as case_activity_id,
604 t_act.act_type_name as case_activity_type_name,
605 t_act.act_type AS case_activity_type ";
608 $query .= " FROM civicrm_case
609 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
610 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
612 if ($type == 'upcoming') {
613 // This gets the earliest activity per case that's scheduled within 14 days from now.
614 // Note we have an inner select to get the min activity id in order to remove duplicates in case there are two with the same datetime.
615 // In this case we don't really care which one, so min(id) works.
616 // optimized in CRM-11837
617 $query .= " INNER JOIN
619 SELECT case_id, act.id, activity_date_time AS desired_date, activity_type_id, status_id, aov.name AS act_type_name, aov.label AS act_type
624 FROM civicrm_view_case_activity_upcoming
625 ORDER BY activity_date_time ASC, id ASC
629 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
630 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
634 elseif ($type == 'recent') {
635 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
636 //improve query performance - CRM-10598
637 $query .= " INNER JOIN
639 SELECT case_id, act.id, activity_date_time AS desired_date, activity_type_id, status_id, aov.name AS act_type_name, aov.label AS act_type
644 FROM civicrm_view_case_activity_recent
645 ORDER BY activity_date_time DESC, id ASC
649 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
650 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
653 elseif ($type == 'any') {
654 $query .= " LEFT JOIN
656 SELECT ca4.case_id, act4.id AS id, act4.activity_date_time AS desired_date, act4.activity_type_id, act4.status_id, aov.name AS act_type_name, aov.label AS act_type
657 FROM civicrm_activity act4
658 LEFT JOIN civicrm_case_activity ca4
659 ON ca4.activity_id = act4.id
660 AND act4.is_current_revision = 1
661 LEFT JOIN civicrm_option_group aog
662 ON aog.name='activity_type'
663 LEFT JOIN civicrm_option_value aov
664 ON aov.option_group_id = aog.id
665 AND aov.value = act4.activity_type_id
670 ON t_act.case_id = civicrm_case.id
671 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
672 LEFT JOIN civicrm_relationship case_relationship
673 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
674 AND case_relationship.case_id = civicrm_case.id )
676 LEFT JOIN civicrm_relationship_type case_relation_type
677 ON ( case_relation_type.id = case_relationship.relationship_type_id
678 AND case_relation_type.id = case_relationship.relationship_type_id )
680 LEFT JOIN civicrm_case_type c_type
681 ON civicrm_case.case_type_id = c_type.id
683 LEFT JOIN civicrm_option_group cog_status
684 ON cog_status.name = 'case_status'
686 LEFT JOIN civicrm_option_value cov_status
687 ON ( civicrm_case.status_id = cov_status.value
688 AND cog_status.id = cov_status.option_group_id )
692 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
693 $query .= " WHERE (1) $condition ";
696 if ($type == 'upcoming') {
697 $query .= " ORDER BY case_scheduled_activity_date ASC ";
699 elseif ($type == 'recent') {
700 $query .= " ORDER BY case_recent_activity_date ASC ";
702 elseif ($type == 'any') {
703 $query .= " ORDER BY case_activity_date ASC ";
710 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
712 * @param bool $allCases
716 * @param string $type
717 * /upcoming,recent,all/.
719 * @param string $context
724 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
726 $casesList = array();
728 //validate access for own cases.
729 if (!self
::accessCiviCase()) {
734 $session = CRM_Core_Session
::singleton();
735 $userID = $session->get('userID');
738 //validate access for all cases.
739 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
743 $condition = " AND civicrm_case.is_deleted = 0 ";
746 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
748 if ($type == 'upcoming' ||
$type == 'any') {
749 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
751 AND civicrm_case.status_id != $closedId";
754 $query = self
::getCaseActivityQuery($type, $userID, $condition);
756 $queryParams = array();
757 $result = CRM_Core_DAO
::executeQuery($query,
761 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
763 $resultFields = array(
780 if ($type == 'upcoming') {
781 $resultFields[] = 'case_scheduled_activity_date';
782 $resultFields[] = 'case_scheduled_activity_type_name';
783 $resultFields[] = 'case_scheduled_activity_type';
784 $resultFields[] = 'case_scheduled_activity_id';
786 elseif ($type == 'recent') {
787 $resultFields[] = 'case_recent_activity_date';
788 $resultFields[] = 'case_recent_activity_type_name';
789 $resultFields[] = 'case_recent_activity_type';
790 $resultFields[] = 'case_recent_activity_id';
792 elseif ($type == 'any') {
793 $resultFields[] = 'case_activity_date';
794 $resultFields[] = 'case_activity_type_name';
795 $resultFields[] = 'case_activity_type';
796 $resultFields[] = 'case_activity_id';
799 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
800 $actions = CRM_Case_Selector_Search
::links();
802 // check is the user has view/edit signer permission
803 $permissions = array(CRM_Core_Permission
::VIEW
);
804 if (CRM_Core_Permission
::check('access all cases and activities') ||
805 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
807 $permissions[] = CRM_Core_Permission
::EDIT
;
809 if (CRM_Core_Permission
::check('delete in CiviCase')) {
810 $permissions[] = CRM_Core_Permission
::DELETE
;
812 $mask = CRM_Core_Action
::mask($permissions);
814 while ($result->fetch()) {
815 foreach ($resultFields as $donCare => $field) {
816 $casesList[$result->case_id
][$field] = $result->$field;
817 if ($field == 'contact_type') {
818 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
820 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
822 'id' => $result->case_id
,
823 'cid' => $result->contact_id
,
828 'case.actions.primary',
832 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
835 'id' => $result->case_id
,
836 'cid' => $result->contact_id
,
846 elseif ($field == 'case_status') {
847 if (in_array($result->$field, $caseStatus)) {
848 $casesList[$result->case_id
]['class'] = "status-urgent";
851 $casesList[$result->case_id
]['class'] = "status-normal";
856 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
857 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
858 if (!empty($caseManagerContact)) {
859 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
860 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
863 //do check user permissions for edit/view activity.
864 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
865 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
867 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
869 $casesList[$result->case_id
]['activity_type_id'], $userID
871 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
873 $casesList[$result->case_id
]['activity_type_id'], $userID
882 * Get the summary of cases counts by type and status.
884 * @param bool $allCases
888 public static function getCasesSummary($allCases = TRUE, $userID) {
889 $caseSummary = array();
891 //validate access for civicase.
892 if (!self
::accessCiviCase()) {
896 //validate access for all cases.
897 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
901 $caseTypes = CRM_Case_PseudoConstant
::caseType();
902 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
903 $caseTypes = array_flip($caseTypes);
905 // get statuses as headers for the table
906 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
907 foreach ($caseStatuses as $key => $name) {
908 $caseSummary['headers'][$key]['status'] = $name;
909 $caseSummary['headers'][$key]['url'] = $url . $key;
912 // build rows with actual data
914 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
924 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
925 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
929 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
930 case_type_id, case_relationship.contact_id_b
932 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
933 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
934 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
935 AND option_group_case_status.id = case_status.option_group_id )
936 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
937 AND case_relationship.contact_id_b = {$userID})
939 {$myCaseWhereClause} {$myGroupByClause}";
941 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
942 while ($res->fetch()) {
943 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
944 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
947 $rows[$res->case_type
][$res->case_status
] = array(
949 'url' => CRM_Utils_System
::url('civicrm/case/search',
950 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
955 $caseSummary['rows'] = array_merge($caseTypes, $rows);
963 * @param int $contactID
967 * @param int $relationshipID
970 * case role / relationships
973 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
975 SELECT civicrm_relationship.id as civicrm_relationship_id,
976 civicrm_contact.sort_name as sort_name,
977 civicrm_email.email as email,
978 civicrm_phone.phone as phone,
979 civicrm_relationship.contact_id_b as civicrm_contact_id,
980 civicrm_relationship.contact_id_a as client_id,
981 civicrm_relationship_type.label_a_b as relation,
982 civicrm_relationship_type.id as relation_type
983 FROM civicrm_relationship
984 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
985 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
986 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
987 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
988 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
991 1 => array($contactID, 'Positive'),
992 2 => array($caseID, 'Positive'),
995 if ($relationshipID) {
996 $query .= ' AND civicrm_relationship.id = %3 ';
997 $params[3] = array($relationshipID, 'Integer');
999 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1002 while ($dao->fetch()) {
1003 $rid = $dao->civicrm_relationship_id
;
1004 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
1005 $values[$rid]['relation'] = $dao->relation
;
1006 $values[$rid]['name'] = $dao->sort_name
;
1007 $values[$rid]['email'] = $dao->email
;
1008 $values[$rid]['phone'] = $dao->phone
;
1009 $values[$rid]['relation_type'] = $dao->relation_type
;
1010 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
1011 $values[$rid]['client_id'] = $dao->client_id
;
1019 * Get Case Activities.
1021 * @param int $caseID
1023 * @param array $params
1025 * @param int $contactID
1028 * @param null $context
1029 * @param int $userID
1033 * Array of case activities
1036 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
1039 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1040 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1041 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1042 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1044 // CRM-5081 - formatting the dates to omit seconds.
1045 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
1047 SELECT COUNT(ca.id) AS ismultiple,
1049 ca.activity_type_id AS type,
1050 ca.activity_type_id AS activity_type_id,
1051 tcc.sort_name AS target_contact_name,
1052 tcc.id AS target_contact_id,
1053 scc.sort_name AS source_contact_name,
1054 scc.id AS source_contact_id,
1055 acc.sort_name AS assignee_contact_name,
1056 acc.id AS assignee_contact_id,
1058 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1059 ca.activity_date_time,
1060 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1061 ), '%Y%m%d%H%i00') AS overdue_date,
1062 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
1063 ca.status_id AS status,
1064 ca.subject AS subject,
1065 ca.is_deleted AS deleted,
1066 ca.priority_id AS priority,
1067 ca.weight AS weight,
1068 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
1071 FROM civicrm_case_activity cca
1072 INNER JOIN civicrm_activity ca
1073 ON ca.id = cca.activity_id
1074 INNER JOIN civicrm_activity_contact cas
1075 ON cas.activity_id = ca.id
1076 AND cas.record_type_id = {$sourceID}
1077 INNER JOIN civicrm_contact scc
1078 ON scc.id = cas.contact_id
1079 LEFT JOIN civicrm_activity_contact caa
1080 ON caa.activity_id = ca.id
1081 AND caa.record_type_id = {$assigneeID}
1082 LEFT JOIN civicrm_contact acc
1083 ON acc.id = caa.contact_id
1084 LEFT JOIN civicrm_activity_contact cat
1085 ON cat.activity_id = ca.id
1086 AND cat.record_type_id = {$targetID}
1087 LEFT JOIN civicrm_contact tcc
1088 ON tcc.id = cat.contact_id
1089 INNER JOIN civicrm_option_group cog
1090 ON cog.name = 'activity_type'
1091 INNER JOIN civicrm_option_value cov
1092 ON cov.option_group_id = cog.id
1093 AND cov.value = ca.activity_type_id
1094 AND cov.is_active = 1
1095 LEFT JOIN civicrm_entity_file ef
1096 ON ef.entity_table = 'civicrm_activity'
1097 AND ef.entity_id = ca.id
1098 LEFT OUTER JOIN civicrm_option_group og
1099 ON og.name = 'activity_status'
1100 LEFT OUTER JOIN civicrm_option_value ov
1101 ON ov.option_group_id=og.id
1102 AND ov.name = 'Scheduled'";
1105 WHERE cca.case_id= %1
1106 AND ca.is_current_revision = 1';
1108 if (!empty($params['source_contact_id'])) {
1110 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
1113 if (!empty($params['status_id'])) {
1115 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1118 if (!empty($params['activity_deleted'])) {
1120 AND ca.is_deleted = 1";
1124 AND ca.is_deleted = 0";
1127 if (!empty($params['activity_type_id'])) {
1129 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1132 if (!empty($params['activity_date_low'])) {
1133 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1135 if (!empty($fromActivityDate)) {
1137 AND ca.activity_date_time >= '{$fromActivityDate}'";
1140 if (!empty($params['activity_date_high'])) {
1141 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1142 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1144 if (!empty($toActivityDate)) {
1146 AND ca.activity_date_time <= '{$toActivityDate}'";
1152 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
1154 // CRM-5081 - added id to act like creation date
1156 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1159 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
1160 $orderBy = " ORDER BY $sortBy ";
1163 $page = CRM_Utils_Array
::value('page', $params);
1164 $rp = CRM_Utils_Array
::value('rp', $params);
1172 $start = (($page - 1) * $rp);
1173 $limit = " LIMIT $start, $rp";
1175 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1176 $queryParams = array(1 => array($caseID, 'Integer'));
1178 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1180 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1181 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1183 $url = CRM_Utils_System
::url("civicrm/case/activity",
1184 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1188 if ($context == 'fulltext') {
1189 $contextUrl = "&context={$context}";
1191 $editUrl = "{$url}&action=update{$contextUrl}";
1192 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1193 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1194 $viewTitle = ts('View activity');
1195 $statusTitle = ts('Edit Status');
1197 $emailActivityTypeIDs = array(
1198 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1202 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1208 $emailActivityTypeIDs = array(
1209 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1213 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1219 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1221 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1222 $compStatusValues = array();
1223 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1224 foreach ($compStatusNames as $name) {
1225 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1228 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1229 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1230 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1233 $session = CRM_Core_Session
::singleton();
1234 $userID = $session->get('userID');
1237 $caseActivities = array();
1240 while ($dao->fetch()) {
1242 $caseActivity = array();
1243 $caseActivityId = $dao->id
;
1245 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1246 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1247 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1249 //do not have sufficient permission
1250 //to access given case activity record.
1251 if (!$allowView && !$allowEdit && !$allowDelete) {
1255 //Add classes to the row, via DataTables syntax
1256 $caseActivity['DT_RowClass'] = "crm-entity";
1258 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1259 $caseActivity['DT_RowClass'] .= " status-completed";
1262 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1263 $caseActivity['DT_RowClass'] .= " status-overdue";
1266 $caseActivity['DT_RowClass'] .= " status-scheduled";
1270 if (!empty($dao->priority
)) {
1271 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1272 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1274 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1275 $caseActivity['DT_RowClass'] .= " priority-low ";
1279 //Add data to the row for inline editing, via DataTable syntax
1280 $caseActivity['DT_RowData'] = array();
1281 $caseActivity['DT_RowData']['entity'] = 'activity';
1282 $caseActivity['DT_RowData']['id'] = $caseActivityId;
1284 //Activity Date and Time
1285 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1288 $caseActivity['subject'] = $dao->subject
;
1291 $caseActivity['type'] = $activityTypes[$dao->type
]['label'];
1293 //Activity Target (With)
1294 $targetContact = '';
1295 if (isset($dao->target_contact_id
)) {
1296 $targetContact = $dao->target_contact_name
;
1297 if ($hasViewContact) {
1298 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1301 $caseActivity['target_contact_name'] = $targetContact;
1303 //Activity Source Contact (Reporter)
1304 $sourceContact = $dao->source_contact_name
;
1305 if ($hasViewContact) {
1306 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1308 $caseActivity['source_contact_name'] = $sourceContact;
1310 //Activity Assignee. CRM-4485.
1311 $assigneeContact = '';
1312 if (isset($dao->assignee_contact_id
)) {
1313 $assigneeContact = $dao->assignee_contact_name
;
1314 if ($hasViewContact) {
1315 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1318 $caseActivity['assignee_contact_name'] = $assigneeContact;
1321 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1323 // FIXME: Why are we not using CRM_Core_Action for these links? This is too much manual work and likely to get out-of-sync with core markup.
1325 $css = 'class="action-item crm-hover-button"';
1327 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1328 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1330 $additionalUrl = "&id={$caseActivityId}";
1331 if (!$dao->deleted
) {
1332 //hide edit link of activity type email.CRM-4530.
1333 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1334 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1336 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1340 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1343 elseif (!$caseDeleted) {
1344 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1345 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1348 //check for operations.
1349 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1350 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1352 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1353 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1355 // if there are file attachments we will return how many and, if only one, add a link to it
1356 if (!empty($dao->attachment_ids
)) {
1357 $attachmentIDs = explode(',', $dao->attachment_ids
);
1358 $caseActivity['no_attachments'] = count($attachmentIDs);
1359 if ($caseActivity['no_attachments'] == 1) {
1360 // if there is only one it's easy to do a link - otherwise just flag it
1361 $attachmentViewUrl = CRM_Utils_System
::url(
1363 "reset=1&eid=" . $caseActivityId . "&id=" . $dao->attachment_ids
,
1368 $url .= " <a href='$attachmentViewUrl' ><span class='icon paper-icon'></span></a>";
1372 $caseActivity['links'] = $url;
1374 array_push($caseActivities, $caseActivity);
1378 $caseActivitiesDT = array();
1379 $caseActivitiesDT['data'] = $caseActivities;
1380 $caseActivitiesDT['recordsTotal'] = $caseCount;
1381 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1383 return $caseActivitiesDT;
1387 * Get Case Related Contacts.
1389 * @param int $caseID
1391 * @param bool $skipDetails
1392 * If true include details of contacts.
1395 * array of return properties
1398 public static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1401 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1402 FROM civicrm_relationship cr
1403 LEFT JOIN civicrm_relationship_type crt
1404 ON crt.id = cr.relationship_type_id
1405 LEFT JOIN civicrm_contact cc
1406 ON cc.id = cr.contact_id_b
1407 LEFT JOIN civicrm_email ce
1408 ON ce.contact_id = cc.id
1409 AND ce.is_primary= 1
1410 WHERE cr.case_id = %1
1413 $params = array(1 => array($caseID, 'Integer'));
1414 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1416 while ($dao->fetch()) {
1418 $values[$dao->id
] = 1;
1422 'contact_id' => $dao->id
,
1423 'display_name' => $dao->name
,
1424 'sort_name' => $dao->sort_name
,
1425 'role' => $dao->role
,
1426 'email' => $dao->email
,
1436 * Send e-mail copy of activity
1438 * @param int $clientId
1439 * @param int $activityId
1441 * @param array $contacts
1442 * Array of related contact.
1444 * @param null $attachments
1445 * @param int $caseId
1449 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1454 $tplParams = $activityInfo = array();
1455 //if its a case activity
1457 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1458 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1459 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1460 $anyActivity = TRUE;
1463 $anyActivity = FALSE;
1465 $tplParams['isCaseActivity'] = 1;
1466 $tplParams['client_id'] = $clientId;
1469 $anyActivity = TRUE;
1472 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1473 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1475 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1477 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1479 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1481 $tplParams['activity'] = $activityInfo;
1482 foreach ($tplParams['activity']['fields'] as $k => $val) {
1483 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1484 $activitySubject = $val['value'];
1488 $session = CRM_Core_Session
::singleton();
1489 // CRM-8926 If user is not logged in, use the activity creator as userID
1490 if (!($userID = $session->get('userID'))) {
1491 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1494 //also create activities simultaneously of this copy.
1495 $activityParams = array();
1497 $activityParams['source_record_id'] = $activityId;
1498 $activityParams['source_contact_id'] = $userID;
1499 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1500 $activityParams['activity_date_time'] = date('YmdHis');
1501 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1502 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1503 $activityParams['case_id'] = $caseId;
1504 $activityParams['is_auto'] = 0;
1505 $activityParams['target_id'] = $clientId;
1507 $tplParams['activitySubject'] = $activitySubject;
1509 // if it’s a case activity, add hashed id to the template (CRM-5916)
1511 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1515 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1517 $receiptFrom = "$name <$address>";
1519 $recordedActivityParams = array();
1521 foreach ($contacts as $mail => $info) {
1522 $tplParams['contact'] = $info;
1523 self
::buildPermissionLinks($tplParams, $activityParams);
1525 $displayName = CRM_Utils_Array
::value('display_name', $info);
1527 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1529 'groupName' => 'msg_tpl_workflow_case',
1530 'valueName' => 'case_activity',
1531 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1532 'tplParams' => $tplParams,
1533 'from' => $receiptFrom,
1534 'toName' => $displayName,
1536 'attachments' => $attachments,
1540 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1541 $activityParams['details'] = $message;
1543 if (!empty($result[$info['contact_id']])) {
1545 * Really only need to record one activity with all the targets combined.
1546 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1547 * but it's always the same content at the moment.
1549 if (empty($recordedActivityParams)) {
1550 $recordedActivityParams = $activityParams;
1553 $recordedActivityParams['subject'] .= "; $displayName";
1555 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1558 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1562 if (!empty($recordedActivityParams)) {
1563 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1565 //create case_activity record if its case activity.
1567 $caseParams = array(
1568 'activity_id' => $activity->id
,
1569 'case_id' => $caseId,
1571 self
::processCaseActivity($caseParams);
1579 * Retrieve count of activities having a particular type, and
1580 * associated with a particular case.
1582 * @param int $caseId
1584 * @param int $activityTypeId
1585 * ID of the activity type.
1589 public static function getCaseActivityCount($caseId, $activityTypeId) {
1590 $queryParam = array(
1591 1 => array($caseId, 'Integer'),
1592 2 => array($activityTypeId, 'Integer'),
1594 $query = "SELECT count(ca.id) as countact
1595 FROM civicrm_activity ca
1596 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1597 WHERE ca.activity_type_id = %2
1598 AND cca.case_id = %1
1599 AND ca.is_deleted = 0";
1601 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1602 if ($dao->fetch()) {
1603 return $dao->countact
;
1610 * Create an activity for a case via email.
1615 * @return array|void
1616 * $activity object of newly creted activity via email
1618 public static function recordActivityViaEmail($file) {
1619 if (!file_exists($file) ||
1622 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1627 $result = CRM_Utils_Mail_Incoming
::parse($file);
1628 if ($result['is_error']) {
1632 foreach ($result['to'] as $to) {
1635 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1636 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1638 if ($replacement !== $to['email']) {
1639 $caseId = $replacement;
1640 //if caseId is invalid, return as error file
1641 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1642 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1651 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1652 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1653 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1655 if (!empty($contactDetails[$result['from']['id']])) {
1657 $params['subject'] = $result['subject'];
1658 $params['activity_date_time'] = $result['date'];
1659 $params['details'] = $result['body'];
1660 $params['source_contact_id'] = $result['from']['id'];
1661 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1666 $details = CRM_Case_PseudoConstant
::caseActivityType();
1668 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1669 $result['body'], $matches
1672 if (!empty($matches) && isset($matches[1])) {
1673 $activityType = trim($matches[1]);
1674 if (isset($details[$activityType])) {
1675 $params['activity_type_id'] = $details[$activityType]['id'];
1678 if (!isset($params['activity_type_id'])) {
1679 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1683 $activity = CRM_Activity_BAO_Activity
::create($params);
1685 $caseParams = array(
1686 'activity_id' => $activity->id
,
1687 'case_id' => $caseId,
1689 self
::processCaseActivity($caseParams);
1692 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1693 array(1 => $result['from']['email'])
1700 * Retrieve the scheduled activity type and date.
1702 * @param array $cases
1703 * Array of contact and case id.
1705 * @param string $type
1708 * Array of scheduled activity type and date
1712 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1713 $session = CRM_Core_Session
::singleton();
1714 $userID = $session->get('userID');
1716 $caseID = implode(',', $cases['case_id']);
1717 $contactID = implode(',', $cases['contact_id']);
1720 AND civicrm_case_contact.contact_id IN( {$contactID} )
1721 AND civicrm_case.id IN( {$caseID})
1722 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1724 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1726 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1728 $activityInfo = array();
1729 while ($res->fetch()) {
1730 if ($type == 'upcoming') {
1731 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1732 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1735 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1736 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1740 return $activityInfo;
1744 * Combine all the exportable fields from the lower levels object.
1747 * array of exportable Fields
1749 public static function &exportableFields() {
1750 if (!self
::$_exportableFields) {
1751 if (!self
::$_exportableFields) {
1752 self
::$_exportableFields = array();
1755 $fields = CRM_Case_DAO_Case
::export();
1756 $fields['case_role'] = array('title' => ts('Role in Case'));
1757 $fields['case_type'] = array(
1758 'title' => ts('Case Type'),
1759 'name' => 'case_type',
1761 $fields['case_status'] = array(
1762 'title' => ts('Case Status'),
1763 'name' => 'case_status',
1766 self
::$_exportableFields = $fields;
1768 return self
::$_exportableFields;
1772 * Restore the record that are associated with this case.
1774 * @param int $caseId
1775 * Id of the case to restore.
1779 public static function restoreCase($caseId) {
1780 //restore activities
1781 $activities = self
::getCaseActivityDates($caseId);
1783 foreach ($activities as $value) {
1784 CRM_Activity_BAO_Activity
::restoreActivity($value);
1788 $case = new CRM_Case_DAO_Case();
1789 $case->id
= $caseId;
1790 $case->is_deleted
= 0;
1793 //CRM-7364, enable relationships
1794 self
::enableDisableCaseRelationships($caseId, TRUE);
1801 * @param null $showLinks
1802 * @param bool $returnOnlyCount
1803 * @param int $offset
1804 * @param int $rowCount
1808 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1809 $globalContacts = array();
1811 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1812 $settings = $settingsProcessor->run();
1813 if (!empty($settings)) {
1814 $groupInfo['name'] = $settings['groupname'];
1815 if ($groupInfo['name']) {
1816 $searchParams = array('name' => $groupInfo['name']);
1818 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1820 $groupInfo['id'] = $results['id'];
1821 $groupInfo['title'] = $results['title'];
1822 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1823 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1824 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1826 if ($returnOnlyCount) {
1827 return $globalContacts;
1831 foreach ($globalContacts as $idx => $contact) {
1832 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1838 return $globalContacts;
1842 * Convenience function to get both case contacts and global in one array.
1843 * @param int $caseId
1847 public static function getRelatedAndGlobalContacts($caseId) {
1848 $relatedContacts = self
::getRelatedContacts($caseId);
1850 $groupInfo = array();
1851 $globalContacts = self
::getGlobalContacts($groupInfo);
1853 //unset values which are not required.
1854 foreach ($globalContacts as $k => & $v) {
1855 unset($v['email_id']);
1856 unset($v['group_contact_id']);
1857 unset($v['status']);
1859 $v['role'] = $groupInfo['title'];
1861 //include multiple listings for the same contact/different roles.
1862 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1863 return $relatedGlobalContacts;
1867 * Get Case ActivitiesDueDates with given criteria.
1869 * @param int $caseID
1871 * @param array $criteriaParams
1873 * @param bool $latestDate
1874 * If set newest or oldest date is selected.
1877 * case activities due dates
1880 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1882 $selectDate = " ca.activity_date_time";
1883 $where = $groupBy = ' ';
1890 if (!empty($criteriaParams['activity_type_id'])) {
1891 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1892 $where .= " AND ca.is_current_revision = 1";
1893 $groupBy .= " GROUP BY ca.activity_type_id";
1896 if (!empty($criteriaParams['newest'])) {
1897 $selectDate = " max(ca.activity_date_time) ";
1900 $selectDate = " min(ca.activity_date_time) ";
1904 $query = "SELECT ca.id, {$selectDate} as activity_date
1905 FROM civicrm_activity ca
1906 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1907 WHERE cc.id = %1 {$where} {$groupBy}";
1909 $params = array(1 => array($caseID, 'Integer'));
1910 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1912 while ($dao->fetch()) {
1913 $values[$dao->id
]['id'] = $dao->id
;
1914 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1921 * Create activities when Case or Other roles assigned/modified/deleted.
1923 * @param int $caseId
1924 * @param int $relationshipId
1926 * @param int $relContactId
1927 * Case role assignee contactId.
1928 * @param int $contactId
1931 * on success creates activity and case activity
1934 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1935 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1939 $queryParam = array();
1940 if (is_array($relationshipId)) {
1941 $relationshipId = implode(',', $relationshipId);
1942 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1945 $relationshipClause = " civicrm_relationship.id = %1";
1946 $queryParam[1] = array($relationshipId, 'Positive');
1950 SELECT cc.display_name as clientName,
1951 cca.display_name as assigneeContactName,
1952 civicrm_relationship.case_id as caseId,
1953 civicrm_relationship_type.label_a_b as relation_a_b,
1954 civicrm_relationship_type.label_b_a as relation_b_a,
1955 civicrm_relationship.contact_id_b as rel_contact_id,
1956 civicrm_relationship.contact_id_a as assign_contact_id
1957 FROM civicrm_relationship_type, civicrm_relationship
1958 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1959 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1960 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1962 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1964 while ($dao->fetch()) {
1965 //to get valid assignee contact(s).
1966 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1967 $caseRelationship = $dao->relation_a_b
;
1968 $assigneContactName = $dao->clientName
;
1969 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1972 $caseRelationship = $dao->relation_b_a
;
1973 $assigneContactName = $dao->assigneeContactName
;
1974 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1978 $session = CRM_Core_Session
::singleton();
1979 $activityParams = array(
1980 'source_contact_id' => $session->get('userID'),
1981 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1982 'activity_date_time' => date('YmdHis'),
1983 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1986 //if $relContactId is passed, role is added or modified.
1987 if (!empty($relContactId)) {
1988 $activityParams['assignee_contact_id'] = $assigneContactIds;
1990 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1996 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
2002 $activityParams['activity_type_id'] = $activityTypeID;
2004 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
2006 //create case_activity record.
2007 $caseParams = array(
2008 'activity_id' => $activity->id
,
2009 'case_id' => $caseId,
2012 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
2017 * contact which is assigned a case role of case manager.
2019 * @param int $caseType
2021 * @param int $caseId
2025 * array of contact on success otherwise empty
2028 public static function getCaseManagerContact($caseType, $caseId) {
2029 if (!$caseType ||
!$caseId) {
2033 $caseManagerContact = array();
2034 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2036 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
2038 if (!empty($managerRoleId)) {
2039 $managerRoleQuery = "
2040 SELECT civicrm_contact.id as casemanager_id,
2041 civicrm_contact.sort_name as casemanager
2042 FROM civicrm_contact
2043 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
2044 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
2045 WHERE civicrm_case.id = %2";
2047 $managerRoleParams = array(
2048 1 => array($managerRoleId, 'Integer'),
2049 2 => array($caseId, 'Integer'),
2052 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
2053 if ($dao->fetch()) {
2054 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
2055 $caseManagerContact['casemanager'] = $dao->casemanager
;
2059 return $caseManagerContact;
2063 * Get all cases with no end dates.
2065 * @param array $params
2066 * @param array $excludeCaseIds
2067 * @param bool $excludeDeleted
2069 * @param bool $includeClosed
2072 * Case and related data keyed on case id
2074 public static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE, $includeClosed = FALSE) {
2075 //params from ajax call.
2076 $where = array($includeClosed ?
'(1)' : '(ca.end_date is null)');
2077 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
2078 $where[] = "( civicrm_case_type.title LIKE '%$caseType%' )";
2080 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
2081 $config = CRM_Core_Config
::singleton();
2082 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
2083 $where[] = "( sort_name LIKE '$search' )";
2085 if ($cid = CRM_Utils_Array
::value('contact_id', $params)) {
2086 $where[] = " c.id = $cid ";
2088 if (is_array($excludeCaseIds) &&
2089 !CRM_Utils_System
::isNull($excludeCaseIds)
2091 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2093 if ($excludeDeleted) {
2094 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2097 //filter for permissioned cases.
2098 $filterCases = array();
2099 $doFilterCases = FALSE;
2100 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2101 $doFilterCases = TRUE;
2102 $session = CRM_Core_Session
::singleton();
2103 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2105 $whereClause = implode(' AND ', $where);
2108 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
2109 $limitClause = "LIMIT 0, $limit";
2113 SELECT c.id as contact_id,
2116 ca.subject as case_subject,
2117 civicrm_case_type.title as case_type,
2118 ca.start_date as start_date,
2119 ca.end_date as end_date,
2121 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2122 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2123 INNER JOIN civicrm_case_type ON ca.case_type_id = civicrm_case_type.id
2124 WHERE {$whereClause}
2125 ORDER BY c.sort_name, ca.end_date
2128 $dao = CRM_Core_DAO
::executeQuery($query);
2129 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id', 'create');
2131 $unclosedCases = array();
2132 while ($dao->fetch()) {
2133 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2136 $unclosedCases[$dao->id
] = array(
2137 'sort_name' => $dao->sort_name
,
2138 'case_type' => $dao->case_type
,
2139 'contact_id' => $dao->contact_id
,
2140 'start_date' => $dao->start_date
,
2141 'end_date' => $dao->end_date
,
2142 'case_subject' => $dao->case_subject
,
2143 'case_status' => $statuses[$dao->status_id
],
2148 return $unclosedCases;
2152 * @param int $contactId
2153 * @param bool $excludeDeleted
2155 * @return null|string
2157 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2158 $whereConditions = array();
2159 if ($excludeDeleted) {
2160 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2163 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2165 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2166 static $accessibleCaseIds;
2167 if (!is_array($accessibleCaseIds)) {
2168 $session = CRM_Core_Session
::singleton();
2169 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID'), 'any'));
2171 //no need of further processing.
2172 if (empty($accessibleCaseIds)) {
2175 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2179 if (!empty($whereConditions)) {
2180 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2184 SELECT count( civicrm_case.id )
2186 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2189 return CRM_Core_DAO
::singleValueQuery($query);
2193 * Retrieve cases related to particular contact.
2195 * @param int $contactId
2197 * @param bool $excludeDeleted
2198 * Do not include deleted cases.
2202 public static function getContactCases($contactId, $excludeDeleted = TRUE) {
2208 $whereClause = "civicrm_case_contact.contact_id = %1";
2209 if ($excludeDeleted) {
2210 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2214 SELECT civicrm_case.id, civicrm_case_type.title as case_type, civicrm_case.start_date
2216 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2217 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
2218 WHERE {$whereClause}";
2220 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2221 while ($dao->fetch()) {
2222 $cases[$dao->id
] = array(
2223 'case_id' => $dao->id
,
2224 'case_type' => $dao->case_type
,
2225 'case_start_date' => $dao->start_date
,
2234 * Retrieve related cases for give case.
2236 * @param int $mainCaseId
2238 * @param int $contactId
2240 * @param bool $excludeDeleted
2241 * Do not include deleted cases.
2245 public static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2246 //FIXME : do check for permissions.
2248 $relatedCases = array();
2249 if (!$mainCaseId ||
!$contactId) {
2250 return $relatedCases;
2253 $linkActType = array_search('Link Cases',
2254 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2256 if (!$linkActType) {
2257 return $relatedCases;
2260 $whereClause = "mainCase.id = %2";
2261 if ($excludeDeleted) {
2262 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2265 //1. first fetch related case ids.
2267 SELECT relCaseAct.case_id
2268 FROM civicrm_case mainCase
2269 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2270 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2271 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2272 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2273 WHERE $whereClause";
2275 $dao = CRM_Core_DAO
::executeQuery($query, array(
2276 1 => array($linkActType, 'Integer'),
2277 2 => array($mainCaseId, 'Integer'),
2279 $relatedCaseIds = array();
2280 while ($dao->fetch()) {
2281 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2285 // there are no related cases.
2286 if (empty($relatedCaseIds)) {
2287 return $relatedCases;
2290 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2291 if ($excludeDeleted) {
2292 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2295 //filter for permissioned cases.
2296 $filterCases = array();
2297 $doFilterCases = FALSE;
2298 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2299 $doFilterCases = TRUE;
2300 $session = CRM_Core_Session
::singleton();
2301 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2304 //2. fetch the details of related cases.
2306 SELECT relCase.id as id,
2307 civicrm_case_type.title as case_type,
2308 client.display_name as client_name,
2309 client.id as client_id
2310 FROM civicrm_case relCase
2311 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2312 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2313 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2314 WHERE {$whereClause}";
2316 $dao = CRM_Core_DAO
::executeQuery($query);
2317 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2318 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2320 while ($dao->fetch()) {
2322 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2323 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2324 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2325 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2327 $clientView = $dao->client_name
;
2328 if ($hasViewContact) {
2329 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2332 $relatedCases[$dao->id
] = array(
2333 'case_id' => $dao->id
,
2334 'case_type' => $dao->case_type
,
2335 'client_name' => $clientView,
2336 'links' => $caseView,
2341 return $relatedCases;
2345 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2347 * @see CRM_Dedupe_Merger::cpTables()
2349 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2351 * @param int $mainContactId
2352 * @param int $otherContactId
2354 public static function mergeContacts($mainContactId, $otherContactId) {
2355 self
::mergeCases($mainContactId, NULL, $otherContactId);
2359 * Function perform two task.
2360 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2361 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2363 * @param int $mainContactId
2364 * Contact id of main contact record.
2365 * @param int $mainCaseId
2366 * Case id of main case record.
2367 * @param int $otherContactId
2368 * Contact id of record which is going to merge.
2369 * @param int $otherCaseId
2370 * Case id of record which is going to merge.
2372 * @param bool $changeClient
2376 public static function mergeCases(
2377 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2378 $otherCaseId = NULL, $changeClient = FALSE) {
2379 $moveToTrash = TRUE;
2381 $duplicateContacts = FALSE;
2382 if ($mainContactId && $otherContactId &&
2383 $mainContactId != $otherContactId
2385 $duplicateContacts = TRUE;
2388 $duplicateCases = FALSE;
2389 if ($mainCaseId && $otherCaseId &&
2390 $mainCaseId != $otherCaseId
2392 $duplicateCases = TRUE;
2395 $mainCaseIds = array();
2396 if (!$duplicateContacts && !$duplicateCases) {
2397 return $mainCaseIds;
2400 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2401 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2402 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2403 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2404 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2405 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2407 $processCaseIds = array($otherCaseId);
2408 if ($duplicateContacts && !$duplicateCases) {
2409 if ($changeClient) {
2410 $processCaseIds = array($mainCaseId);
2413 //get all case ids for other contact.
2414 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2416 if (!is_array($processCaseIds)) {
2421 $session = CRM_Core_Session
::singleton();
2422 $currentUserId = $session->get('userID');
2424 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2426 // copy all cases and connect to main contact id.
2427 foreach ($processCaseIds as $otherCaseId) {
2428 if ($duplicateContacts) {
2429 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2430 $mainCaseId = $mainCase->id
;
2435 // CRM-11662 Copy Case custom data
2436 $extends = array('case');
2437 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2439 foreach ($groupTree as $groupID => $group) {
2440 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2441 foreach ($group['fields'] as $fieldID => $field) {
2442 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2446 foreach ($table as $tableName => $tableColumns) {
2447 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2448 $tableColumns[0] = $mainCaseId;
2449 $select = 'SELECT ' . implode(', ', $tableColumns);
2450 $from = ' FROM ' . $tableName;
2451 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2452 $query = $insert . $select . $from . $where;
2453 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2459 $mainCaseIds[] = $mainCaseId;
2460 //insert record for case contact.
2461 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2462 $otherCaseContact->case_id
= $otherCaseId;
2463 $otherCaseContact->find();
2464 while ($otherCaseContact->fetch()) {
2465 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2466 $mainCaseContact->case_id
= $mainCaseId;
2467 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2468 if ($mainCaseContact->contact_id
== $otherContactId) {
2469 $mainCaseContact->contact_id
= $mainContactId;
2471 //avoid duplicate object.
2472 if (!$mainCaseContact->find(TRUE)) {
2473 $mainCaseContact->save();
2475 $mainCaseContact->free();
2477 $otherCaseContact->free();
2479 elseif (!$otherContactId) {
2480 $otherContactId = $mainContactId;
2483 if (!$mainCaseId ||
!$otherCaseId ||
2484 !$mainContactId ||
!$otherContactId
2489 // get all activities for other case.
2490 $otherCaseActivities = array();
2491 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2493 //for duplicate cases do not process singleton activities.
2494 $otherActivityIds = $singletonActivityIds = array();
2495 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2496 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2497 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2500 $otherActivityIds[] = $otherActId;
2502 if ($duplicateCases) {
2503 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2506 FROM civicrm_activity
2507 WHERE activity_type_id = $openCaseType
2508 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2509 $dao = CRM_Core_DAO
::executeQuery($sql);
2510 while ($dao->fetch()) {
2511 $singletonActivityIds[] = $dao->id
;
2517 // migrate all activities and connect to main contact.
2518 $copiedActivityIds = $activityMappingIds = array();
2519 sort($otherActivityIds);
2520 foreach ($otherActivityIds as $otherActivityId) {
2522 //for duplicate cases -
2523 //do not migrate singleton activities.
2524 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2528 //migrate activity record.
2529 $otherActivity = new CRM_Activity_DAO_Activity();
2530 $otherActivity->id
= $otherActivityId;
2531 if (!$otherActivity->find(TRUE)) {
2535 $mainActVals = array();
2536 $mainActivity = new CRM_Activity_DAO_Activity();
2537 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2538 $mainActivity->copyValues($mainActVals);
2539 $mainActivity->id
= NULL;
2540 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2541 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2545 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2549 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2552 $mainActivity->save();
2553 $mainActivityId = $mainActivity->id
;
2554 if (!$mainActivityId) {
2558 $activityMappingIds[$otherActivityId] = $mainActivityId;
2559 // insert log of all activities
2560 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2562 $otherActivity->free();
2563 $mainActivity->free();
2564 $copiedActivityIds[] = $otherActivityId;
2566 //create case activity record.
2567 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2568 $mainCaseActivity->case_id
= $mainCaseId;
2569 $mainCaseActivity->activity_id
= $mainActivityId;
2570 $mainCaseActivity->save();
2571 $mainCaseActivity->free();
2573 //migrate source activity.
2574 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2575 $otherSourceActivity->activity_id
= $otherActivityId;
2576 $otherSourceActivity->record_type_id
= $sourceID;
2577 $otherSourceActivity->find();
2578 while ($otherSourceActivity->fetch()) {
2579 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2580 $mainActivitySource->record_type_id
= $sourceID;
2581 $mainActivitySource->activity_id
= $mainActivityId;
2582 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2583 if ($mainActivitySource->contact_id
== $otherContactId) {
2584 $mainActivitySource->contact_id
= $mainContactId;
2586 //avoid duplicate object.
2587 if (!$mainActivitySource->find(TRUE)) {
2588 $mainActivitySource->save();
2590 $mainActivitySource->free();
2592 $otherSourceActivity->free();
2594 //migrate target activities.
2595 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2596 $otherTargetActivity->activity_id
= $otherActivityId;
2597 $otherTargetActivity->record_type_id
= $targetID;
2598 $otherTargetActivity->find();
2599 while ($otherTargetActivity->fetch()) {
2600 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2601 $mainActivityTarget->record_type_id
= $targetID;
2602 $mainActivityTarget->activity_id
= $mainActivityId;
2603 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2604 if ($mainActivityTarget->contact_id
== $otherContactId) {
2605 $mainActivityTarget->contact_id
= $mainContactId;
2607 //avoid duplicate object.
2608 if (!$mainActivityTarget->find(TRUE)) {
2609 $mainActivityTarget->save();
2611 $mainActivityTarget->free();
2613 $otherTargetActivity->free();
2615 //migrate assignee activities.
2616 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2617 $otherAssigneeActivity->activity_id
= $otherActivityId;
2618 $otherAssigneeActivity->record_type_id
= $assigneeID;
2619 $otherAssigneeActivity->find();
2620 while ($otherAssigneeActivity->fetch()) {
2621 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2622 $mainAssigneeActivity->activity_id
= $mainActivityId;
2623 $mainAssigneeActivity->record_type_id
= $assigneeID;
2624 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2625 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2626 $mainAssigneeActivity->contact_id
= $mainContactId;
2628 //avoid duplicate object.
2629 if (!$mainAssigneeActivity->find(TRUE)) {
2630 $mainAssigneeActivity->save();
2632 $mainAssigneeActivity->free();
2634 $otherAssigneeActivity->free();
2636 // copy custom fields and attachments
2638 'activityID' => $otherActivityId,
2639 'mainActivityId' => $mainActivityId,
2641 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2644 //copy case relationship.
2645 if ($duplicateContacts) {
2646 //migrate relationship records.
2647 $otherRelationship = new CRM_Contact_DAO_Relationship();
2648 $otherRelationship->case_id
= $otherCaseId;
2649 $otherRelationship->find();
2650 $otherRelationshipIds = array();
2651 while ($otherRelationship->fetch()) {
2652 $otherRelVals = array();
2653 $updateOtherRel = FALSE;
2654 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2656 $mainRelationship = new CRM_Contact_DAO_Relationship();
2657 $mainRelationship->copyValues($otherRelVals);
2658 $mainRelationship->id
= NULL;
2659 $mainRelationship->case_id
= $mainCaseId;
2660 if ($mainRelationship->contact_id_a
== $otherContactId) {
2661 $updateOtherRel = TRUE;
2662 $mainRelationship->contact_id_a
= $mainContactId;
2665 //case creator change only when we merge user contact.
2666 if ($mainRelationship->contact_id_b
== $otherContactId) {
2667 //do not change creator for change client.
2668 if (!$changeClient) {
2669 $updateOtherRel = TRUE;
2670 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2673 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2674 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2676 //avoid duplicate object.
2677 if (!$mainRelationship->find(TRUE)) {
2678 $mainRelationship->save();
2680 $mainRelationship->free();
2682 //get the other relationship ids to update end date.
2683 if ($updateOtherRel) {
2684 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2687 $otherRelationship->free();
2689 //update other relationships end dates
2690 if (!empty($otherRelationshipIds)) {
2691 $sql = 'UPDATE civicrm_relationship
2692 SET end_date = CURDATE()
2693 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2694 CRM_Core_DAO
::executeQuery($sql);
2698 //move other case to trash.
2699 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2704 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2705 if ($changeClient) {
2706 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2707 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2709 $mergeActType = array_search('Reassigned Case', $activityTypes);
2710 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2713 2 => $otherContactDisplayName,
2714 3 => $mainContactDisplayName,
2719 elseif ($duplicateContacts) {
2720 $mergeActType = array_search('Merge Case', $activityTypes);
2721 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2724 2 => $otherContactId,
2725 3 => $mainContactId,
2731 $mergeActType = array_search('Merge Case', $activityTypes);
2732 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2733 if (!empty($copiedActivityIds)) {
2735 SELECT id, subject, activity_date_time, activity_type_id
2736 FROM civicrm_activity
2737 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2738 $dao = CRM_Core_DAO
::executeQuery($sql);
2739 while ($dao->fetch()) {
2740 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2741 if ($dao->subject
) {
2742 $mergeActSubjectDetails .= " :: {$dao->subject}";
2744 $mergeActSubjectDetails .= "<br />";
2749 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2750 $activityParams = array(
2751 'subject' => $mergeActSubject,
2752 'details' => $mergeActSubjectDetails,
2753 'status_id' => array_search('Completed', $activityStatuses),
2754 'activity_type_id' => $mergeActType,
2755 'source_contact_id' => $currentUserId,
2756 'activity_date_time' => date('YmdHis'),
2759 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2760 $mergeActivityId = $mergeActivity->id
;
2761 if (!$mergeActivityId) {
2764 $mergeActivity->free();
2766 //connect merge activity to case.
2767 $mergeCaseAct = array(
2768 'case_id' => $mainCaseId,
2769 'activity_id' => $mergeActivityId,
2772 self
::processCaseActivity($mergeCaseAct);
2775 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2777 return $mainCaseIds;
2781 * Validate contact permission for
2782 * edit/view on activity record and build links.
2784 * @param array $tplParams
2785 * Params to be sent to template for sending email.
2786 * @param array $activityParams
2787 * Info of the activity.
2791 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2792 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2793 'activity_type_id', 'id'
2796 if (!empty($tplParams['isCaseActivity'])) {
2797 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2798 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2801 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2802 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2805 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2806 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2810 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2811 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2814 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2815 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2821 * Validate contact permission for
2822 * given operation on activity record.
2824 * @param int $activityId
2825 * Activity record id.
2826 * @param string $operation
2828 * @param int $actTypeId
2830 * @param int $contactId
2831 * Contact id/if not pass consider logged in.
2832 * @param bool $checkComponent
2833 * Do we need to check component enabled.
2837 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2839 if (!$actTypeId && $activityId) {
2840 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2843 if (!$activityId ||
!$operation ||
!$actTypeId) {
2847 //do check for civicase component enabled.
2848 if ($checkComponent && !self
::enabled()) {
2852 //do check for cases.
2853 $caseActOperations = array(
2860 if (in_array($operation, $caseActOperations)) {
2861 static $unclosedCases;
2862 if (!is_array($unclosedCases)) {
2863 $unclosedCases = self
::getUnclosedCases();
2865 if ($operation == 'File On Case') {
2866 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2869 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2873 $actionOperations = array('view', 'edit', 'delete');
2874 if (in_array($operation, $actionOperations)) {
2876 //do cache when user has non/supper permission.
2877 static $allowOperations;
2879 if (!is_array($allowOperations) ||
2880 !array_key_exists($operation, $allowOperations)
2884 $session = CRM_Core_Session
::singleton();
2885 $contactId = $session->get('userID');
2888 //check for permissions.
2889 $permissions = array(
2891 'access my cases and activities',
2892 'access all cases and activities',
2895 'access my cases and activities',
2896 'access all cases and activities',
2898 'delete' => array('delete activities'),
2901 //check for core permission.
2902 $hasPermissions = array();
2903 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2904 if (is_array($checkPermissions)) {
2905 foreach ($checkPermissions as $per) {
2906 if (CRM_Core_Permission
::check($per)) {
2907 $hasPermissions[$operation][] = $per;
2913 if (!empty($hasPermissions)) {
2914 //need to check activity object specific.
2915 if (in_array($operation, array(
2920 //do we have supper permission.
2921 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2922 $allowOperations[$operation] = $allow = TRUE;
2925 //user has only access to my cases and activity.
2926 //here object specific permmions come in picture.
2928 //edit - contact must be source or assignee
2929 //view - contact must be source/assignee/target
2930 $isTarget = $isAssignee = $isSource = FALSE;
2931 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2932 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2933 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2934 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2936 $target = new CRM_Activity_DAO_ActivityContact();
2937 $target->record_type_id
= $targetID;
2938 $target->activity_id
= $activityId;
2939 $target->contact_id
= $contactId;
2940 if ($target->find(TRUE)) {
2944 $assignee = new CRM_Activity_DAO_ActivityContact();
2945 $assignee->activity_id
= $activityId;
2946 $assignee->record_type_id
= $assigneeID;
2947 $assignee->contact_id
= $contactId;
2948 if ($assignee->find(TRUE)) {
2952 $source = new CRM_Activity_DAO_ActivityContact();
2953 $source->activity_id
= $activityId;
2954 $source->record_type_id
= $sourceID;
2955 $source->contact_id
= $contactId;
2956 if ($source->find(TRUE)) {
2960 if ($operation == 'edit') {
2961 if ($isAssignee ||
$isSource) {
2965 if ($operation == 'view') {
2966 if ($isTarget ||
$isAssignee ||
$isSource) {
2972 elseif (is_array($hasPermissions[$operation])) {
2973 $allowOperations[$operation] = $allow = TRUE;
2977 //contact do not have permission.
2978 $allowOperations[$operation] = FALSE;
2983 //here contact might have supper/non permission.
2984 $allow = $allowOperations[$operation];
2988 //do further only when operation is granted.
2990 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2992 //get the activity type name.
2993 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2995 //do not allow multiple copy / edit action.
2996 $singletonNames = array(
3006 //do not allow to delete these activities, CRM-4543
3007 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
3009 //allow edit operation.
3010 $allowEditNames = array('Open Case');
3012 // do not allow File on Case
3013 $doNotFileNames = array(
3016 'Change Case Status',
3017 'Change Case Start Date',
3024 if (in_array($actTypeName, $singletonNames)) {
3026 if ($operation == 'File On Case') {
3027 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
3029 if (in_array($operation, $actionOperations)) {
3031 if ($operation == 'edit') {
3032 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
3034 elseif ($operation == 'delete') {
3035 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
3039 if ($allow && ($operation == 'delete') &&
3040 in_array($actTypeName, $doNotDeleteNames)
3045 if ($allow && ($operation == 'File On Case') &&
3046 in_array($actTypeName, $doNotFileNames)
3051 //check settings file for masking actions
3052 //on the basis the activity types
3053 //hide Edit link if activity type is NOT editable
3054 //(special case activities).CRM-5871
3055 if ($allow && in_array($operation, $actionOperations)) {
3056 static $actionFilter = array();
3057 if (!array_key_exists($operation, $actionFilter)) {
3058 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
3059 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
3061 if (array_key_exists($operation, $actionFilter[$operation]) &&
3062 in_array($actTypeId, $actionFilter[$operation][$operation])
3073 * Since we drop 'access CiviCase', allow access
3074 * if user has 'access my cases and activities'
3075 * or 'access all cases and activities'
3077 public static function accessCiviCase() {
3078 if (!self
::enabled()) {
3082 if (CRM_Core_Permission
::check('access my cases and activities') ||
3083 CRM_Core_Permission
::check('access all cases and activities')
3092 * Verify user has permission to access a case.
3094 * @param int $caseId
3095 * @param bool $denyClosed
3096 * Set TRUE if one wants closed cases to be treated as inaccessible.
3100 public static function accessCase($caseId, $denyClosed = TRUE) {
3101 if (!$caseId ||
!self
::enabled()) {
3105 // This permission always has access
3106 if (CRM_Core_Permission
::check('access all cases and activities')) {
3110 // This permission is required at minimum
3111 if (!CRM_Core_Permission
::check('access my cases and activities')) {
3115 $session = CRM_Core_Session
::singleton();
3116 $userID = CRM_Utils_Type
::validate($session->get('userID'), 'Positive');
3117 $caseId = CRM_Utils_Type
::validate($caseId, 'Positive');
3119 $condition = " AND civicrm_case.is_deleted = 0 ";
3120 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
3121 $condition .= " AND civicrm_case.id = {$caseId}";
3124 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
3125 $condition .= " AND civicrm_case.status_id != $closedId";
3128 // We don't actually care about activities in the case, but the underlying
3129 // query is verbose, and this allows us to share the basic query with
3130 // getCases(). $type=='any' means that activities will be left-joined.
3131 $query = self
::getCaseActivityQuery('any', $userID, $condition);
3132 $queryParams = array();
3133 $dao = CRM_Core_DAO
::executeQuery($query,
3137 return (bool) $dao->fetch();
3141 * Check whether activity is a case Activity.
3143 * @param int $activityID
3148 public static function isCaseActivity($activityID) {
3149 $isCaseActivity = FALSE;
3151 $params = array(1 => array($activityID, 'Integer'));
3152 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3153 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
3154 $isCaseActivity = TRUE;
3158 return $isCaseActivity;
3162 * Get all the case type ids currently in use.
3166 public static function getUsedCaseType() {
3167 static $caseTypeIds;
3169 if (!is_array($caseTypeIds)) {
3170 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3172 $dao = CRM_Core_DAO
::executeQuery($query);
3173 $caseTypeIds = array();
3174 while ($dao->fetch()) {
3175 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3178 $caseTypeIds[] = $typeId[1];
3182 return $caseTypeIds;
3186 * Get all the case status ids currently in use.
3190 public static function getUsedCaseStatuses() {
3191 static $caseStatusIds;
3193 if (!is_array($caseStatusIds)) {
3194 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3196 $dao = CRM_Core_DAO
::executeQuery($query);
3197 $caseStatusIds = array();
3198 while ($dao->fetch()) {
3199 $caseStatusIds[] = $dao->status_id
;
3203 return $caseStatusIds;
3207 * Get all the encounter medium ids currently in use.
3211 public static function getUsedEncounterMediums() {
3214 if (!is_array($mediumIds)) {
3215 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3217 $dao = CRM_Core_DAO
::executeQuery($query);
3218 $mediumIds = array();
3219 while ($dao->fetch()) {
3220 $mediumIds[] = $dao->medium_id
;
3228 * Check case configuration.
3230 * @param int $contactId
3234 public static function isCaseConfigured($contactId = NULL) {
3235 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3237 //lets check for case configured.
3238 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3239 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3240 if (!$configured['configured']) {
3241 //do check for case type and case status.
3242 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
3243 if (!empty($caseTypes)) {
3244 $configured['configured'] = TRUE;
3245 if (!$configured['configured']) {
3246 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3247 if (!empty($caseStatuses)) {
3248 $configured['configured'] = TRUE;
3253 if ($configured['configured']) {
3254 //do check for active case type and case status.
3255 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3256 if (!empty($caseTypes)) {
3257 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3258 if (!empty($caseStatuses)) {
3259 $configured['allowToAddNewCase'] = TRUE;
3263 //do we need to redirect user to case admin.
3264 if (!$configured['allowToAddNewCase'] && $contactId) {
3265 //check for current contact case count.
3266 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3267 //redirect user to case admin page.
3268 if (!$currentContatCasesCount) {
3269 $configured['redirectToCaseAdmin'] = TRUE;
3278 * Used during case component enablement and during ugprade.
3282 public static function createCaseViews() {
3283 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
3284 $dao = new CRM_Core_DAO();
3286 $sql = self
::createCaseViewsQuery('upcoming');
3288 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3292 // Above error doesn't get caught?
3293 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3294 if (is_null($doublecheck)) {
3298 $sql = self
::createCaseViewsQuery('recent');
3300 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3304 // Above error doesn't get caught?
3305 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3306 if (is_null($doublecheck)) {
3314 * Helper function, also used by the upgrade in case of error
3316 * @param string $section
3320 public static function createCaseViewsQuery($section = 'upcoming') {
3322 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3325 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3326 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3327 FROM civicrm_case_activity ca
3328 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3329 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3330 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3334 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3335 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3336 FROM civicrm_case_activity ca
3337 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3338 WHERE a.activity_date_time <= NOW()
3339 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3340 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3347 * Add/copy relationships, when new client is added for a case
3349 * @param int $caseId
3351 * @param int $contactId
3352 * Contact id / new client id.
3356 public static function addCaseRelationships($caseId, $contactId) {
3357 // get the case role / relationships for the case
3358 $caseRelationships = new CRM_Contact_DAO_Relationship();
3359 $caseRelationships->case_id
= $caseId;
3360 $caseRelationships->find();
3361 $relationshipTypes = array();
3363 // make sure we don't add duplicate relationships of same relationship type.
3364 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3366 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3368 // add relationship for new client.
3369 $newRelationship = new CRM_Contact_DAO_Relationship();
3370 $newRelationship->copyValues($values);
3371 $newRelationship->id
= NULL;
3372 $newRelationship->case_id
= $caseId;
3373 $newRelationship->contact_id_a
= $contactId;
3374 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3375 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3377 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3378 if (!$newRelationship->find(TRUE)) {
3379 $newRelationship->save();
3381 $newRelationship->free();
3383 // store relationship type of newly created relationship
3384 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3389 * Get the list of clients for a case.
3391 * @param int $caseId
3394 * associated array with client ids
3396 public static function getCaseClients($caseId) {
3398 $caseContact = new CRM_Case_DAO_CaseContact();
3399 $caseContact->case_id
= $caseId;
3400 $caseContact->find();
3402 while ($caseContact->fetch()) {
3403 $clients[] = $caseContact->contact_id
;
3410 * Get options for a given case field.
3411 * @see CRM_Core_DAO::buildOptions
3413 * @param string $fieldName
3414 * @param string $context
3415 * @see CRM_Core_DAO::buildOptionsContext
3416 * @param array $props
3417 * Whatever is known about this dao object.
3419 * @return array|bool
3421 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3422 $className = __CLASS__
;
3424 switch ($fieldName) {
3425 // This field is not part of this object but the api supports it
3427 $className = 'CRM_Activity_BAO_Activity';
3430 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);