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.
1046 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
1047 ca.activity_type_id as type,
1048 ca.activity_type_id as activity_type_id,
1049 cc.sort_name as reporter,
1050 cc.id as reporter_id,
1051 acc.sort_name AS assignee,
1052 acc.id AS assignee_id,
1053 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1054 ca.activity_date_time,
1055 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1056 ), '%Y%m%d%H%i00') as overdue_date,
1057 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
1058 ca.status_id as status,
1059 ca.subject as subject,
1060 ca.is_deleted as deleted,
1061 ca.priority_id as priority,
1062 ca.weight as weight,
1063 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1066 FROM civicrm_case_activity cca
1067 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1068 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1069 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1070 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1071 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1072 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1073 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1074 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1075 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1076 LEFT JOIN civicrm_activity_contact caa
1077 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1078 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1080 $where = 'WHERE cca.case_id= %1
1081 AND ca.is_current_revision = 1';
1083 if (!empty($params['reporter_id'])) {
1084 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1087 if (!empty($params['status_id'])) {
1088 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1091 if (!empty($params['activity_deleted'])) {
1092 $where .= " AND ca.is_deleted = 1";
1095 $where .= " AND ca.is_deleted = 0";
1098 if (!empty($params['activity_type_id'])) {
1099 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1102 if (!empty($params['activity_date_low'])) {
1103 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1105 if (!empty($params['activity_date_high'])) {
1106 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1107 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1110 if (!empty($fromActivityDate)) {
1111 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1114 if (!empty($toActivityDate)) {
1115 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1118 // hack to handle to allow initial sorting to be done by query
1119 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1120 $params['sortname'] = NULL;
1123 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1124 $params['sortorder'] = NULL;
1127 $sortname = CRM_Utils_Array
::value('sortname', $params);
1128 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1130 $groupBy = " GROUP BY ca.id ";
1132 if (!$sortname AND !$sortorder) {
1133 // CRM-5081 - added id to act like creation date
1134 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1137 $sort = "{$sortname} {$sortorder}";
1138 $sort = CRM_Utils_Type
::escape($sort, 'String');
1139 $orderBy = " ORDER BY $sort ";
1140 if ($sortname != 'display_date') {
1141 $orderBy .= ', display_date DESC';
1145 $page = CRM_Utils_Array
::value('page', $params);
1146 $rp = CRM_Utils_Array
::value('rp', $params);
1155 $start = (($page - 1) * $rp);
1156 $query = $select . $from . $where . $groupBy . $orderBy;
1158 $params = array(1 => array($caseID, 'Integer'));
1159 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1160 $params['total'] = $dao->N
;
1162 //FIXME: need to optimize/cache these queries
1163 $limit = " LIMIT $start, $rp";
1167 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1169 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1170 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1171 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1173 $url = CRM_Utils_System
::url("civicrm/case/activity",
1174 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1178 if ($context == 'fulltext') {
1179 $contextUrl = "&context={$context}";
1181 $editUrl = "{$url}&action=update{$contextUrl}";
1182 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1183 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1184 $viewTitle = ts('View activity');
1185 $statusTitle = ts('Edit Status');
1187 $emailActivityTypeIDs = array(
1188 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1192 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1198 $emailActivityTypeIDs = array(
1199 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1203 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1209 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1211 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1212 $compStatusValues = array();
1213 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1214 foreach ($compStatusNames as $name) {
1215 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1217 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1218 "reset=1&cid=", FALSE, NULL, FALSE
1220 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1221 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1224 $session = CRM_Core_Session
::singleton();
1225 $userID = $session->get('userID');
1228 while ($dao->fetch()) {
1230 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1231 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1232 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1234 //do not have sufficient permission
1235 //to access given case activity record.
1236 if (!$allowView && !$allowEdit && !$allowDelete) {
1240 $values[$dao->id
]['id'] = $dao->id
;
1241 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1243 $reporterName = $dao->reporter
;
1244 if ($hasViewContact) {
1245 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1247 $values[$dao->id
]['reporter'] = $reporterName;
1248 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1249 $targetContactUrls = $withContacts = array();
1250 foreach ($targetNames as $targetId => $targetName) {
1251 if (!in_array($targetId, $clientIds)) {
1252 $withContacts[$targetId] = $targetName;
1255 foreach ($withContacts as $cid => $name) {
1256 if ($hasViewContact) {
1257 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1259 $targetContactUrls[] = $name;
1261 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1263 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1264 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1266 //check for view activity.
1267 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1269 $url = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $dao->id
));
1270 $subject = '<a class="crm-popup medium-popup" href="' . $url . '" title="' . $viewTitle . '">' . $subject . '</a>';
1272 $values[$dao->id
]['subject'] = $subject;
1274 // add activity assignee to activity selector. CRM-4485.
1275 if (isset($dao->assignee
)) {
1276 if ($dao->ismultiple
== 1) {
1277 if ($dao->reporter_id
!= $dao->assignee_id
) {
1278 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1280 $values[$dao->id
]['assignee'] = $dao->assignee
;
1283 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1286 // 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.
1288 $css = 'class="action-item crm-hover-button"';
1289 $additionalUrl = "&id={$dao->id}";
1290 if (!$dao->deleted
) {
1291 //hide edit link of activity type email.CRM-4530.
1292 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1293 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1295 $url = '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1299 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1302 elseif (!$caseDeleted) {
1303 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1304 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1307 //check for operations.
1308 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1309 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1311 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1312 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1314 // if there are file attachments we will return how many and, if only one, add a link to it
1315 if (!empty($dao->attachment_ids
)) {
1316 $attachmentIDs = explode(',', $dao->attachment_ids
);
1317 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1318 if ($values[$dao->id
]['no_attachments'] == 1) {
1319 // if there is only one it's easy to do a link - otherwise just flag it
1320 $attachmentViewUrl = CRM_Utils_System
::url(
1322 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1327 $url .= " <a href='$attachmentViewUrl' ><span class='icon paper-icon'></span></a>";
1331 $values[$dao->id
]['links'] = $url;
1332 $values[$dao->id
]['class'] = "";
1334 if (!empty($dao->priority
)) {
1335 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1336 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1338 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1339 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1343 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1344 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1347 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1348 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1351 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1356 $values[$dao->id
]['status'] = '<div class="crmf-status_id crm-activity-status-' . $dao->id
. ' ' . $values[$dao->id
]['class'] . ' crm-editable" data-type="select" data-action="create" data-refresh="true">' . $values[$dao->id
]['status'] . '</div>';
1365 * Get Case Related Contacts.
1367 * @param int $caseID
1369 * @param bool $skipDetails
1370 * If true include details of contacts.
1373 * array of return properties
1376 public static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1379 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1380 FROM civicrm_relationship cr
1381 LEFT JOIN civicrm_relationship_type crt
1382 ON crt.id = cr.relationship_type_id
1383 LEFT JOIN civicrm_contact cc
1384 ON cc.id = cr.contact_id_b
1385 LEFT JOIN civicrm_email ce
1386 ON ce.contact_id = cc.id
1387 AND ce.is_primary= 1
1388 WHERE cr.case_id = %1
1391 $params = array(1 => array($caseID, 'Integer'));
1392 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1394 while ($dao->fetch()) {
1396 $values[$dao->id
] = 1;
1400 'contact_id' => $dao->id
,
1401 'display_name' => $dao->name
,
1402 'sort_name' => $dao->sort_name
,
1403 'role' => $dao->role
,
1404 'email' => $dao->email
,
1414 * Send e-mail copy of activity
1416 * @param int $clientId
1417 * @param int $activityId
1419 * @param array $contacts
1420 * Array of related contact.
1422 * @param null $attachments
1423 * @param int $caseId
1427 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1432 $tplParams = $activityInfo = array();
1433 //if its a case activity
1435 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1436 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1437 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1438 $anyActivity = TRUE;
1441 $anyActivity = FALSE;
1443 $tplParams['isCaseActivity'] = 1;
1444 $tplParams['client_id'] = $clientId;
1447 $anyActivity = TRUE;
1450 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1451 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1453 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1455 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1457 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1459 $tplParams['activity'] = $activityInfo;
1460 foreach ($tplParams['activity']['fields'] as $k => $val) {
1461 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1462 $activitySubject = $val['value'];
1466 $session = CRM_Core_Session
::singleton();
1467 // CRM-8926 If user is not logged in, use the activity creator as userID
1468 if (!($userID = $session->get('userID'))) {
1469 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1472 //also create activities simultaneously of this copy.
1473 $activityParams = array();
1475 $activityParams['source_record_id'] = $activityId;
1476 $activityParams['source_contact_id'] = $userID;
1477 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1478 $activityParams['activity_date_time'] = date('YmdHis');
1479 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1480 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1481 $activityParams['case_id'] = $caseId;
1482 $activityParams['is_auto'] = 0;
1483 $activityParams['target_id'] = $clientId;
1485 $tplParams['activitySubject'] = $activitySubject;
1487 // if it’s a case activity, add hashed id to the template (CRM-5916)
1489 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1493 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1495 $receiptFrom = "$name <$address>";
1497 $recordedActivityParams = array();
1499 foreach ($contacts as $mail => $info) {
1500 $tplParams['contact'] = $info;
1501 self
::buildPermissionLinks($tplParams, $activityParams);
1503 $displayName = CRM_Utils_Array
::value('display_name', $info);
1505 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1507 'groupName' => 'msg_tpl_workflow_case',
1508 'valueName' => 'case_activity',
1509 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1510 'tplParams' => $tplParams,
1511 'from' => $receiptFrom,
1512 'toName' => $displayName,
1514 'attachments' => $attachments,
1518 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1519 $activityParams['details'] = $message;
1521 if (!empty($result[$info['contact_id']])) {
1523 * Really only need to record one activity with all the targets combined.
1524 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1525 * but it's always the same content at the moment.
1527 if (empty($recordedActivityParams)) {
1528 $recordedActivityParams = $activityParams;
1531 $recordedActivityParams['subject'] .= "; $displayName";
1533 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1536 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1540 if (!empty($recordedActivityParams)) {
1541 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1543 //create case_activity record if its case activity.
1545 $caseParams = array(
1546 'activity_id' => $activity->id
,
1547 'case_id' => $caseId,
1549 self
::processCaseActivity($caseParams);
1557 * Retrieve count of activities having a particular type, and
1558 * associated with a particular case.
1560 * @param int $caseId
1562 * @param int $activityTypeId
1563 * ID of the activity type.
1567 public static function getCaseActivityCount($caseId, $activityTypeId) {
1568 $queryParam = array(
1569 1 => array($caseId, 'Integer'),
1570 2 => array($activityTypeId, 'Integer'),
1572 $query = "SELECT count(ca.id) as countact
1573 FROM civicrm_activity ca
1574 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1575 WHERE ca.activity_type_id = %2
1576 AND cca.case_id = %1
1577 AND ca.is_deleted = 0";
1579 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1580 if ($dao->fetch()) {
1581 return $dao->countact
;
1588 * Create an activity for a case via email.
1593 * @return array|void
1594 * $activity object of newly creted activity via email
1596 public static function recordActivityViaEmail($file) {
1597 if (!file_exists($file) ||
1600 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1605 $result = CRM_Utils_Mail_Incoming
::parse($file);
1606 if ($result['is_error']) {
1610 foreach ($result['to'] as $to) {
1613 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1614 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1616 if ($replacement !== $to['email']) {
1617 $caseId = $replacement;
1618 //if caseId is invalid, return as error file
1619 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1620 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1629 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1630 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1631 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1633 if (!empty($contactDetails[$result['from']['id']])) {
1635 $params['subject'] = $result['subject'];
1636 $params['activity_date_time'] = $result['date'];
1637 $params['details'] = $result['body'];
1638 $params['source_contact_id'] = $result['from']['id'];
1639 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1644 $details = CRM_Case_PseudoConstant
::caseActivityType();
1646 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1647 $result['body'], $matches
1650 if (!empty($matches) && isset($matches[1])) {
1651 $activityType = trim($matches[1]);
1652 if (isset($details[$activityType])) {
1653 $params['activity_type_id'] = $details[$activityType]['id'];
1656 if (!isset($params['activity_type_id'])) {
1657 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1661 $activity = CRM_Activity_BAO_Activity
::create($params);
1663 $caseParams = array(
1664 'activity_id' => $activity->id
,
1665 'case_id' => $caseId,
1667 self
::processCaseActivity($caseParams);
1670 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1671 array(1 => $result['from']['email'])
1678 * Retrieve the scheduled activity type and date.
1680 * @param array $cases
1681 * Array of contact and case id.
1683 * @param string $type
1686 * Array of scheduled activity type and date
1690 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1691 $session = CRM_Core_Session
::singleton();
1692 $userID = $session->get('userID');
1694 $caseID = implode(',', $cases['case_id']);
1695 $contactID = implode(',', $cases['contact_id']);
1698 AND civicrm_case_contact.contact_id IN( {$contactID} )
1699 AND civicrm_case.id IN( {$caseID})
1700 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1702 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1704 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1706 $activityInfo = array();
1707 while ($res->fetch()) {
1708 if ($type == 'upcoming') {
1709 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1710 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1713 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1714 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1718 return $activityInfo;
1722 * Combine all the exportable fields from the lower levels object.
1725 * array of exportable Fields
1727 public static function &exportableFields() {
1728 if (!self
::$_exportableFields) {
1729 if (!self
::$_exportableFields) {
1730 self
::$_exportableFields = array();
1733 $fields = CRM_Case_DAO_Case
::export();
1734 $fields['case_role'] = array('title' => ts('Role in Case'));
1735 $fields['case_type'] = array(
1736 'title' => ts('Case Type'),
1737 'name' => 'case_type',
1739 $fields['case_status'] = array(
1740 'title' => ts('Case Status'),
1741 'name' => 'case_status',
1744 self
::$_exportableFields = $fields;
1746 return self
::$_exportableFields;
1750 * Restore the record that are associated with this case.
1752 * @param int $caseId
1753 * Id of the case to restore.
1757 public static function restoreCase($caseId) {
1758 //restore activities
1759 $activities = self
::getCaseActivityDates($caseId);
1761 foreach ($activities as $value) {
1762 CRM_Activity_BAO_Activity
::restoreActivity($value);
1766 $case = new CRM_Case_DAO_Case();
1767 $case->id
= $caseId;
1768 $case->is_deleted
= 0;
1771 //CRM-7364, enable relationships
1772 self
::enableDisableCaseRelationships($caseId, TRUE);
1779 * @param null $showLinks
1780 * @param bool $returnOnlyCount
1781 * @param int $offset
1782 * @param int $rowCount
1786 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1787 $globalContacts = array();
1789 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1790 $settings = $settingsProcessor->run();
1791 if (!empty($settings)) {
1792 $groupInfo['name'] = $settings['groupname'];
1793 if ($groupInfo['name']) {
1794 $searchParams = array('name' => $groupInfo['name']);
1796 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1798 $groupInfo['id'] = $results['id'];
1799 $groupInfo['title'] = $results['title'];
1800 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1801 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1802 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1804 if ($returnOnlyCount) {
1805 return $globalContacts;
1809 foreach ($globalContacts as $idx => $contact) {
1810 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1816 return $globalContacts;
1820 * Convenience function to get both case contacts and global in one array.
1821 * @param int $caseId
1825 public static function getRelatedAndGlobalContacts($caseId) {
1826 $relatedContacts = self
::getRelatedContacts($caseId);
1828 $groupInfo = array();
1829 $globalContacts = self
::getGlobalContacts($groupInfo);
1831 //unset values which are not required.
1832 foreach ($globalContacts as $k => & $v) {
1833 unset($v['email_id']);
1834 unset($v['group_contact_id']);
1835 unset($v['status']);
1837 $v['role'] = $groupInfo['title'];
1839 //include multiple listings for the same contact/different roles.
1840 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1841 return $relatedGlobalContacts;
1845 * Get Case ActivitiesDueDates with given criteria.
1847 * @param int $caseID
1849 * @param array $criteriaParams
1851 * @param bool $latestDate
1852 * If set newest or oldest date is selected.
1855 * case activities due dates
1858 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1860 $selectDate = " ca.activity_date_time";
1861 $where = $groupBy = ' ';
1868 if (!empty($criteriaParams['activity_type_id'])) {
1869 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1870 $where .= " AND ca.is_current_revision = 1";
1871 $groupBy .= " GROUP BY ca.activity_type_id";
1874 if (!empty($criteriaParams['newest'])) {
1875 $selectDate = " max(ca.activity_date_time) ";
1878 $selectDate = " min(ca.activity_date_time) ";
1882 $query = "SELECT ca.id, {$selectDate} as activity_date
1883 FROM civicrm_activity ca
1884 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1885 WHERE cc.id = %1 {$where} {$groupBy}";
1887 $params = array(1 => array($caseID, 'Integer'));
1888 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1890 while ($dao->fetch()) {
1891 $values[$dao->id
]['id'] = $dao->id
;
1892 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1899 * Create activities when Case or Other roles assigned/modified/deleted.
1901 * @param int $caseId
1902 * @param int $relationshipId
1904 * @param int $relContactId
1905 * Case role assignee contactId.
1906 * @param int $contactId
1909 * on success creates activity and case activity
1912 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1913 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1917 $queryParam = array();
1918 if (is_array($relationshipId)) {
1919 $relationshipId = implode(',', $relationshipId);
1920 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1923 $relationshipClause = " civicrm_relationship.id = %1";
1924 $queryParam[1] = array($relationshipId, 'Positive');
1928 SELECT cc.display_name as clientName,
1929 cca.display_name as assigneeContactName,
1930 civicrm_relationship.case_id as caseId,
1931 civicrm_relationship_type.label_a_b as relation_a_b,
1932 civicrm_relationship_type.label_b_a as relation_b_a,
1933 civicrm_relationship.contact_id_b as rel_contact_id,
1934 civicrm_relationship.contact_id_a as assign_contact_id
1935 FROM civicrm_relationship_type, civicrm_relationship
1936 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1937 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1938 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1940 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1942 while ($dao->fetch()) {
1943 //to get valid assignee contact(s).
1944 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1945 $caseRelationship = $dao->relation_a_b
;
1946 $assigneContactName = $dao->clientName
;
1947 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1950 $caseRelationship = $dao->relation_b_a
;
1951 $assigneContactName = $dao->assigneeContactName
;
1952 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1956 $session = CRM_Core_Session
::singleton();
1957 $activityParams = array(
1958 'source_contact_id' => $session->get('userID'),
1959 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1960 'activity_date_time' => date('YmdHis'),
1961 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1964 //if $relContactId is passed, role is added or modified.
1965 if (!empty($relContactId)) {
1966 $activityParams['assignee_contact_id'] = $assigneContactIds;
1968 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1974 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1980 $activityParams['activity_type_id'] = $activityTypeID;
1982 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1984 //create case_activity record.
1985 $caseParams = array(
1986 'activity_id' => $activity->id
,
1987 'case_id' => $caseId,
1990 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1995 * contact which is assigned a case role of case manager.
1997 * @param int $caseType
1999 * @param int $caseId
2003 * array of contact on success otherwise empty
2006 public static function getCaseManagerContact($caseType, $caseId) {
2007 if (!$caseType ||
!$caseId) {
2011 $caseManagerContact = array();
2012 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2014 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
2016 if (!empty($managerRoleId)) {
2017 $managerRoleQuery = "
2018 SELECT civicrm_contact.id as casemanager_id,
2019 civicrm_contact.sort_name as casemanager
2020 FROM civicrm_contact
2021 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
2022 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
2023 WHERE civicrm_case.id = %2";
2025 $managerRoleParams = array(
2026 1 => array($managerRoleId, 'Integer'),
2027 2 => array($caseId, 'Integer'),
2030 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
2031 if ($dao->fetch()) {
2032 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
2033 $caseManagerContact['casemanager'] = $dao->casemanager
;
2037 return $caseManagerContact;
2041 * Get all cases with no end dates.
2043 * @param array $params
2044 * @param array $excludeCaseIds
2045 * @param bool $excludeDeleted
2047 * @param bool $includeClosed
2050 * Case and related data keyed on case id
2052 public static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE, $includeClosed = FALSE) {
2053 //params from ajax call.
2054 $where = array($includeClosed ?
'(1)' : '(ca.end_date is null)');
2055 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
2056 $where[] = "( civicrm_case_type.title LIKE '%$caseType%' )";
2058 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
2059 $config = CRM_Core_Config
::singleton();
2060 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
2061 $where[] = "( sort_name LIKE '$search' )";
2063 if ($cid = CRM_Utils_Array
::value('contact_id', $params)) {
2064 $where[] = " c.id = $cid ";
2066 if (is_array($excludeCaseIds) &&
2067 !CRM_Utils_System
::isNull($excludeCaseIds)
2069 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2071 if ($excludeDeleted) {
2072 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2075 //filter for permissioned cases.
2076 $filterCases = array();
2077 $doFilterCases = FALSE;
2078 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2079 $doFilterCases = TRUE;
2080 $session = CRM_Core_Session
::singleton();
2081 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2083 $whereClause = implode(' AND ', $where);
2086 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
2087 $limitClause = "LIMIT 0, $limit";
2091 SELECT c.id as contact_id,
2094 ca.subject as case_subject,
2095 civicrm_case_type.title as case_type,
2096 ca.start_date as start_date,
2097 ca.end_date as end_date,
2099 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2100 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2101 INNER JOIN civicrm_case_type ON ca.case_type_id = civicrm_case_type.id
2102 WHERE {$whereClause}
2103 ORDER BY c.sort_name, ca.end_date
2106 $dao = CRM_Core_DAO
::executeQuery($query);
2107 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id', 'create');
2109 $unclosedCases = array();
2110 while ($dao->fetch()) {
2111 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2114 $unclosedCases[$dao->id
] = array(
2115 'sort_name' => $dao->sort_name
,
2116 'case_type' => $dao->case_type
,
2117 'contact_id' => $dao->contact_id
,
2118 'start_date' => $dao->start_date
,
2119 'end_date' => $dao->end_date
,
2120 'case_subject' => $dao->case_subject
,
2121 'case_status' => $statuses[$dao->status_id
],
2126 return $unclosedCases;
2130 * @param int $contactId
2131 * @param bool $excludeDeleted
2133 * @return null|string
2135 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2136 $whereConditions = array();
2137 if ($excludeDeleted) {
2138 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2141 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2143 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2144 static $accessibleCaseIds;
2145 if (!is_array($accessibleCaseIds)) {
2146 $session = CRM_Core_Session
::singleton();
2147 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID'), 'any'));
2149 //no need of further processing.
2150 if (empty($accessibleCaseIds)) {
2153 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2157 if (!empty($whereConditions)) {
2158 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2162 SELECT count( civicrm_case.id )
2164 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2167 return CRM_Core_DAO
::singleValueQuery($query);
2171 * Retrieve cases related to particular contact.
2173 * @param int $contactId
2175 * @param bool $excludeDeleted
2176 * Do not include deleted cases.
2180 public static function getContactCases($contactId, $excludeDeleted = TRUE) {
2186 $whereClause = "civicrm_case_contact.contact_id = %1";
2187 if ($excludeDeleted) {
2188 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2192 SELECT civicrm_case.id, civicrm_case_type.title as case_type, civicrm_case.start_date
2194 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2195 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
2196 WHERE {$whereClause}";
2198 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2199 while ($dao->fetch()) {
2200 $cases[$dao->id
] = array(
2201 'case_id' => $dao->id
,
2202 'case_type' => $dao->case_type
,
2203 'case_start_date' => $dao->start_date
,
2212 * Retrieve related cases for give case.
2214 * @param int $mainCaseId
2216 * @param int $contactId
2218 * @param bool $excludeDeleted
2219 * Do not include deleted cases.
2223 public static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2224 //FIXME : do check for permissions.
2226 $relatedCases = array();
2227 if (!$mainCaseId ||
!$contactId) {
2228 return $relatedCases;
2231 $linkActType = array_search('Link Cases',
2232 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2234 if (!$linkActType) {
2235 return $relatedCases;
2238 $whereClause = "mainCase.id = %2";
2239 if ($excludeDeleted) {
2240 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2243 //1. first fetch related case ids.
2245 SELECT relCaseAct.case_id
2246 FROM civicrm_case mainCase
2247 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2248 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2249 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2250 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2251 WHERE $whereClause";
2253 $dao = CRM_Core_DAO
::executeQuery($query, array(
2254 1 => array($linkActType, 'Integer'),
2255 2 => array($mainCaseId, 'Integer'),
2257 $relatedCaseIds = array();
2258 while ($dao->fetch()) {
2259 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2263 // there are no related cases.
2264 if (empty($relatedCaseIds)) {
2265 return $relatedCases;
2268 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2269 if ($excludeDeleted) {
2270 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2273 //filter for permissioned cases.
2274 $filterCases = array();
2275 $doFilterCases = FALSE;
2276 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2277 $doFilterCases = TRUE;
2278 $session = CRM_Core_Session
::singleton();
2279 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2282 //2. fetch the details of related cases.
2284 SELECT relCase.id as id,
2285 civicrm_case_type.title as case_type,
2286 client.display_name as client_name,
2287 client.id as client_id
2288 FROM civicrm_case relCase
2289 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2290 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2291 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2292 WHERE {$whereClause}";
2294 $dao = CRM_Core_DAO
::executeQuery($query);
2295 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2296 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2298 while ($dao->fetch()) {
2300 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2301 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2302 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2303 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2305 $clientView = $dao->client_name
;
2306 if ($hasViewContact) {
2307 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2310 $relatedCases[$dao->id
] = array(
2311 'case_id' => $dao->id
,
2312 'case_type' => $dao->case_type
,
2313 'client_name' => $clientView,
2314 'links' => $caseView,
2319 return $relatedCases;
2323 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2325 * @see CRM_Dedupe_Merger::cpTables()
2327 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2329 * @param int $mainContactId
2330 * @param int $otherContactId
2332 public static function mergeContacts($mainContactId, $otherContactId) {
2333 self
::mergeCases($mainContactId, NULL, $otherContactId);
2337 * Function perform two task.
2338 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2339 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2341 * @param int $mainContactId
2342 * Contact id of main contact record.
2343 * @param int $mainCaseId
2344 * Case id of main case record.
2345 * @param int $otherContactId
2346 * Contact id of record which is going to merge.
2347 * @param int $otherCaseId
2348 * Case id of record which is going to merge.
2350 * @param bool $changeClient
2354 public static function mergeCases(
2355 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2356 $otherCaseId = NULL, $changeClient = FALSE) {
2357 $moveToTrash = TRUE;
2359 $duplicateContacts = FALSE;
2360 if ($mainContactId && $otherContactId &&
2361 $mainContactId != $otherContactId
2363 $duplicateContacts = TRUE;
2366 $duplicateCases = FALSE;
2367 if ($mainCaseId && $otherCaseId &&
2368 $mainCaseId != $otherCaseId
2370 $duplicateCases = TRUE;
2373 $mainCaseIds = array();
2374 if (!$duplicateContacts && !$duplicateCases) {
2375 return $mainCaseIds;
2378 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2379 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2380 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2381 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2382 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2383 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2385 $processCaseIds = array($otherCaseId);
2386 if ($duplicateContacts && !$duplicateCases) {
2387 if ($changeClient) {
2388 $processCaseIds = array($mainCaseId);
2391 //get all case ids for other contact.
2392 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2394 if (!is_array($processCaseIds)) {
2399 $session = CRM_Core_Session
::singleton();
2400 $currentUserId = $session->get('userID');
2402 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2404 // copy all cases and connect to main contact id.
2405 foreach ($processCaseIds as $otherCaseId) {
2406 if ($duplicateContacts) {
2407 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2408 $mainCaseId = $mainCase->id
;
2413 // CRM-11662 Copy Case custom data
2414 $extends = array('case');
2415 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2417 foreach ($groupTree as $groupID => $group) {
2418 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2419 foreach ($group['fields'] as $fieldID => $field) {
2420 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2424 foreach ($table as $tableName => $tableColumns) {
2425 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2426 $tableColumns[0] = $mainCaseId;
2427 $select = 'SELECT ' . implode(', ', $tableColumns);
2428 $from = ' FROM ' . $tableName;
2429 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2430 $query = $insert . $select . $from . $where;
2431 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2437 $mainCaseIds[] = $mainCaseId;
2438 //insert record for case contact.
2439 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2440 $otherCaseContact->case_id
= $otherCaseId;
2441 $otherCaseContact->find();
2442 while ($otherCaseContact->fetch()) {
2443 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2444 $mainCaseContact->case_id
= $mainCaseId;
2445 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2446 if ($mainCaseContact->contact_id
== $otherContactId) {
2447 $mainCaseContact->contact_id
= $mainContactId;
2449 //avoid duplicate object.
2450 if (!$mainCaseContact->find(TRUE)) {
2451 $mainCaseContact->save();
2453 $mainCaseContact->free();
2455 $otherCaseContact->free();
2457 elseif (!$otherContactId) {
2458 $otherContactId = $mainContactId;
2461 if (!$mainCaseId ||
!$otherCaseId ||
2462 !$mainContactId ||
!$otherContactId
2467 // get all activities for other case.
2468 $otherCaseActivities = array();
2469 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2471 //for duplicate cases do not process singleton activities.
2472 $otherActivityIds = $singletonActivityIds = array();
2473 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2474 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2475 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2478 $otherActivityIds[] = $otherActId;
2480 if ($duplicateCases) {
2481 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2484 FROM civicrm_activity
2485 WHERE activity_type_id = $openCaseType
2486 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2487 $dao = CRM_Core_DAO
::executeQuery($sql);
2488 while ($dao->fetch()) {
2489 $singletonActivityIds[] = $dao->id
;
2495 // migrate all activities and connect to main contact.
2496 $copiedActivityIds = $activityMappingIds = array();
2497 sort($otherActivityIds);
2498 foreach ($otherActivityIds as $otherActivityId) {
2500 //for duplicate cases -
2501 //do not migrate singleton activities.
2502 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2506 //migrate activity record.
2507 $otherActivity = new CRM_Activity_DAO_Activity();
2508 $otherActivity->id
= $otherActivityId;
2509 if (!$otherActivity->find(TRUE)) {
2513 $mainActVals = array();
2514 $mainActivity = new CRM_Activity_DAO_Activity();
2515 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2516 $mainActivity->copyValues($mainActVals);
2517 $mainActivity->id
= NULL;
2518 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2519 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2523 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2527 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2530 $mainActivity->save();
2531 $mainActivityId = $mainActivity->id
;
2532 if (!$mainActivityId) {
2536 $activityMappingIds[$otherActivityId] = $mainActivityId;
2537 // insert log of all activities
2538 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2540 $otherActivity->free();
2541 $mainActivity->free();
2542 $copiedActivityIds[] = $otherActivityId;
2544 //create case activity record.
2545 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2546 $mainCaseActivity->case_id
= $mainCaseId;
2547 $mainCaseActivity->activity_id
= $mainActivityId;
2548 $mainCaseActivity->save();
2549 $mainCaseActivity->free();
2551 //migrate source activity.
2552 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2553 $otherSourceActivity->activity_id
= $otherActivityId;
2554 $otherSourceActivity->record_type_id
= $sourceID;
2555 $otherSourceActivity->find();
2556 while ($otherSourceActivity->fetch()) {
2557 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2558 $mainActivitySource->record_type_id
= $sourceID;
2559 $mainActivitySource->activity_id
= $mainActivityId;
2560 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2561 if ($mainActivitySource->contact_id
== $otherContactId) {
2562 $mainActivitySource->contact_id
= $mainContactId;
2564 //avoid duplicate object.
2565 if (!$mainActivitySource->find(TRUE)) {
2566 $mainActivitySource->save();
2568 $mainActivitySource->free();
2570 $otherSourceActivity->free();
2572 //migrate target activities.
2573 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2574 $otherTargetActivity->activity_id
= $otherActivityId;
2575 $otherTargetActivity->record_type_id
= $targetID;
2576 $otherTargetActivity->find();
2577 while ($otherTargetActivity->fetch()) {
2578 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2579 $mainActivityTarget->record_type_id
= $targetID;
2580 $mainActivityTarget->activity_id
= $mainActivityId;
2581 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2582 if ($mainActivityTarget->contact_id
== $otherContactId) {
2583 $mainActivityTarget->contact_id
= $mainContactId;
2585 //avoid duplicate object.
2586 if (!$mainActivityTarget->find(TRUE)) {
2587 $mainActivityTarget->save();
2589 $mainActivityTarget->free();
2591 $otherTargetActivity->free();
2593 //migrate assignee activities.
2594 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2595 $otherAssigneeActivity->activity_id
= $otherActivityId;
2596 $otherAssigneeActivity->record_type_id
= $assigneeID;
2597 $otherAssigneeActivity->find();
2598 while ($otherAssigneeActivity->fetch()) {
2599 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2600 $mainAssigneeActivity->activity_id
= $mainActivityId;
2601 $mainAssigneeActivity->record_type_id
= $assigneeID;
2602 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2603 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2604 $mainAssigneeActivity->contact_id
= $mainContactId;
2606 //avoid duplicate object.
2607 if (!$mainAssigneeActivity->find(TRUE)) {
2608 $mainAssigneeActivity->save();
2610 $mainAssigneeActivity->free();
2612 $otherAssigneeActivity->free();
2614 // copy custom fields and attachments
2616 'activityID' => $otherActivityId,
2617 'mainActivityId' => $mainActivityId,
2619 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2622 //copy case relationship.
2623 if ($duplicateContacts) {
2624 //migrate relationship records.
2625 $otherRelationship = new CRM_Contact_DAO_Relationship();
2626 $otherRelationship->case_id
= $otherCaseId;
2627 $otherRelationship->find();
2628 $otherRelationshipIds = array();
2629 while ($otherRelationship->fetch()) {
2630 $otherRelVals = array();
2631 $updateOtherRel = FALSE;
2632 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2634 $mainRelationship = new CRM_Contact_DAO_Relationship();
2635 $mainRelationship->copyValues($otherRelVals);
2636 $mainRelationship->id
= NULL;
2637 $mainRelationship->case_id
= $mainCaseId;
2638 if ($mainRelationship->contact_id_a
== $otherContactId) {
2639 $updateOtherRel = TRUE;
2640 $mainRelationship->contact_id_a
= $mainContactId;
2643 //case creator change only when we merge user contact.
2644 if ($mainRelationship->contact_id_b
== $otherContactId) {
2645 //do not change creator for change client.
2646 if (!$changeClient) {
2647 $updateOtherRel = TRUE;
2648 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2651 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2652 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2654 //avoid duplicate object.
2655 if (!$mainRelationship->find(TRUE)) {
2656 $mainRelationship->save();
2658 $mainRelationship->free();
2660 //get the other relationship ids to update end date.
2661 if ($updateOtherRel) {
2662 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2665 $otherRelationship->free();
2667 //update other relationships end dates
2668 if (!empty($otherRelationshipIds)) {
2669 $sql = 'UPDATE civicrm_relationship
2670 SET end_date = CURDATE()
2671 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2672 CRM_Core_DAO
::executeQuery($sql);
2676 //move other case to trash.
2677 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2682 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2683 if ($changeClient) {
2684 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2685 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2687 $mergeActType = array_search('Reassigned Case', $activityTypes);
2688 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2691 2 => $otherContactDisplayName,
2692 3 => $mainContactDisplayName,
2697 elseif ($duplicateContacts) {
2698 $mergeActType = array_search('Merge Case', $activityTypes);
2699 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2702 2 => $otherContactId,
2703 3 => $mainContactId,
2709 $mergeActType = array_search('Merge Case', $activityTypes);
2710 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2711 if (!empty($copiedActivityIds)) {
2713 SELECT id, subject, activity_date_time, activity_type_id
2714 FROM civicrm_activity
2715 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2716 $dao = CRM_Core_DAO
::executeQuery($sql);
2717 while ($dao->fetch()) {
2718 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2719 if ($dao->subject
) {
2720 $mergeActSubjectDetails .= " :: {$dao->subject}";
2722 $mergeActSubjectDetails .= "<br />";
2727 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2728 $activityParams = array(
2729 'subject' => $mergeActSubject,
2730 'details' => $mergeActSubjectDetails,
2731 'status_id' => array_search('Completed', $activityStatuses),
2732 'activity_type_id' => $mergeActType,
2733 'source_contact_id' => $currentUserId,
2734 'activity_date_time' => date('YmdHis'),
2737 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2738 $mergeActivityId = $mergeActivity->id
;
2739 if (!$mergeActivityId) {
2742 $mergeActivity->free();
2744 //connect merge activity to case.
2745 $mergeCaseAct = array(
2746 'case_id' => $mainCaseId,
2747 'activity_id' => $mergeActivityId,
2750 self
::processCaseActivity($mergeCaseAct);
2753 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2755 return $mainCaseIds;
2759 * Validate contact permission for
2760 * edit/view on activity record and build links.
2762 * @param array $tplParams
2763 * Params to be sent to template for sending email.
2764 * @param array $activityParams
2765 * Info of the activity.
2769 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2770 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2771 'activity_type_id', 'id'
2774 if (!empty($tplParams['isCaseActivity'])) {
2775 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2776 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2779 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2780 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2783 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2784 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2788 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2789 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2792 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2793 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2799 * Validate contact permission for
2800 * given operation on activity record.
2802 * @param int $activityId
2803 * Activity record id.
2804 * @param string $operation
2806 * @param int $actTypeId
2808 * @param int $contactId
2809 * Contact id/if not pass consider logged in.
2810 * @param bool $checkComponent
2811 * Do we need to check component enabled.
2815 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2817 if (!$actTypeId && $activityId) {
2818 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2821 if (!$activityId ||
!$operation ||
!$actTypeId) {
2825 //do check for civicase component enabled.
2826 if ($checkComponent && !self
::enabled()) {
2830 //do check for cases.
2831 $caseActOperations = array(
2838 if (in_array($operation, $caseActOperations)) {
2839 static $unclosedCases;
2840 if (!is_array($unclosedCases)) {
2841 $unclosedCases = self
::getUnclosedCases();
2843 if ($operation == 'File On Case') {
2844 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2847 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2851 $actionOperations = array('view', 'edit', 'delete');
2852 if (in_array($operation, $actionOperations)) {
2854 //do cache when user has non/supper permission.
2855 static $allowOperations;
2857 if (!is_array($allowOperations) ||
2858 !array_key_exists($operation, $allowOperations)
2862 $session = CRM_Core_Session
::singleton();
2863 $contactId = $session->get('userID');
2866 //check for permissions.
2867 $permissions = array(
2869 'access my cases and activities',
2870 'access all cases and activities',
2873 'access my cases and activities',
2874 'access all cases and activities',
2876 'delete' => array('delete activities'),
2879 //check for core permission.
2880 $hasPermissions = array();
2881 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2882 if (is_array($checkPermissions)) {
2883 foreach ($checkPermissions as $per) {
2884 if (CRM_Core_Permission
::check($per)) {
2885 $hasPermissions[$operation][] = $per;
2891 if (!empty($hasPermissions)) {
2892 //need to check activity object specific.
2893 if (in_array($operation, array(
2898 //do we have supper permission.
2899 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2900 $allowOperations[$operation] = $allow = TRUE;
2903 //user has only access to my cases and activity.
2904 //here object specific permmions come in picture.
2906 //edit - contact must be source or assignee
2907 //view - contact must be source/assignee/target
2908 $isTarget = $isAssignee = $isSource = FALSE;
2909 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2910 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2911 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2912 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2914 $target = new CRM_Activity_DAO_ActivityContact();
2915 $target->record_type_id
= $targetID;
2916 $target->activity_id
= $activityId;
2917 $target->contact_id
= $contactId;
2918 if ($target->find(TRUE)) {
2922 $assignee = new CRM_Activity_DAO_ActivityContact();
2923 $assignee->activity_id
= $activityId;
2924 $assignee->record_type_id
= $assigneeID;
2925 $assignee->contact_id
= $contactId;
2926 if ($assignee->find(TRUE)) {
2930 $source = new CRM_Activity_DAO_ActivityContact();
2931 $source->activity_id
= $activityId;
2932 $source->record_type_id
= $sourceID;
2933 $source->contact_id
= $contactId;
2934 if ($source->find(TRUE)) {
2938 if ($operation == 'edit') {
2939 if ($isAssignee ||
$isSource) {
2943 if ($operation == 'view') {
2944 if ($isTarget ||
$isAssignee ||
$isSource) {
2950 elseif (is_array($hasPermissions[$operation])) {
2951 $allowOperations[$operation] = $allow = TRUE;
2955 //contact do not have permission.
2956 $allowOperations[$operation] = FALSE;
2961 //here contact might have supper/non permission.
2962 $allow = $allowOperations[$operation];
2966 //do further only when operation is granted.
2968 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2970 //get the activity type name.
2971 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2973 //do not allow multiple copy / edit action.
2974 $singletonNames = array(
2984 //do not allow to delete these activities, CRM-4543
2985 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2987 //allow edit operation.
2988 $allowEditNames = array('Open Case');
2990 // do not allow File on Case
2991 $doNotFileNames = array(
2994 'Change Case Status',
2995 'Change Case Start Date',
3002 if (in_array($actTypeName, $singletonNames)) {
3004 if ($operation == 'File On Case') {
3005 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
3007 if (in_array($operation, $actionOperations)) {
3009 if ($operation == 'edit') {
3010 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
3012 elseif ($operation == 'delete') {
3013 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
3017 if ($allow && ($operation == 'delete') &&
3018 in_array($actTypeName, $doNotDeleteNames)
3023 if ($allow && ($operation == 'File On Case') &&
3024 in_array($actTypeName, $doNotFileNames)
3029 //check settings file for masking actions
3030 //on the basis the activity types
3031 //hide Edit link if activity type is NOT editable
3032 //(special case activities).CRM-5871
3033 if ($allow && in_array($operation, $actionOperations)) {
3034 static $actionFilter = array();
3035 if (!array_key_exists($operation, $actionFilter)) {
3036 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
3037 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
3039 if (array_key_exists($operation, $actionFilter[$operation]) &&
3040 in_array($actTypeId, $actionFilter[$operation][$operation])
3051 * Since we drop 'access CiviCase', allow access
3052 * if user has 'access my cases and activities'
3053 * or 'access all cases and activities'
3055 public static function accessCiviCase() {
3056 if (!self
::enabled()) {
3060 if (CRM_Core_Permission
::check('access my cases and activities') ||
3061 CRM_Core_Permission
::check('access all cases and activities')
3070 * Verify user has permission to access a case.
3072 * @param int $caseId
3073 * @param bool $denyClosed
3074 * Set TRUE if one wants closed cases to be treated as inaccessible.
3078 public static function accessCase($caseId, $denyClosed = TRUE) {
3079 if (!$caseId ||
!self
::enabled()) {
3083 // This permission always has access
3084 if (CRM_Core_Permission
::check('access all cases and activities')) {
3088 // This permission is required at minimum
3089 if (!CRM_Core_Permission
::check('access my cases and activities')) {
3093 $session = CRM_Core_Session
::singleton();
3094 $userID = CRM_Utils_Type
::validate($session->get('userID'), 'Positive');
3095 $caseId = CRM_Utils_Type
::validate($caseId, 'Positive');
3097 $condition = " AND civicrm_case.is_deleted = 0 ";
3098 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
3099 $condition .= " AND civicrm_case.id = {$caseId}";
3102 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
3103 $condition .= " AND civicrm_case.status_id != $closedId";
3106 // We don't actually care about activities in the case, but the underlying
3107 // query is verbose, and this allows us to share the basic query with
3108 // getCases(). $type=='any' means that activities will be left-joined.
3109 $query = self
::getCaseActivityQuery('any', $userID, $condition);
3110 $queryParams = array();
3111 $dao = CRM_Core_DAO
::executeQuery($query,
3115 return (bool) $dao->fetch();
3119 * Check whether activity is a case Activity.
3121 * @param int $activityID
3126 public static function isCaseActivity($activityID) {
3127 $isCaseActivity = FALSE;
3129 $params = array(1 => array($activityID, 'Integer'));
3130 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3131 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
3132 $isCaseActivity = TRUE;
3136 return $isCaseActivity;
3140 * Get all the case type ids currently in use.
3144 public static function getUsedCaseType() {
3145 static $caseTypeIds;
3147 if (!is_array($caseTypeIds)) {
3148 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3150 $dao = CRM_Core_DAO
::executeQuery($query);
3151 $caseTypeIds = array();
3152 while ($dao->fetch()) {
3153 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3156 $caseTypeIds[] = $typeId[1];
3160 return $caseTypeIds;
3164 * Get all the case status ids currently in use.
3168 public static function getUsedCaseStatuses() {
3169 static $caseStatusIds;
3171 if (!is_array($caseStatusIds)) {
3172 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3174 $dao = CRM_Core_DAO
::executeQuery($query);
3175 $caseStatusIds = array();
3176 while ($dao->fetch()) {
3177 $caseStatusIds[] = $dao->status_id
;
3181 return $caseStatusIds;
3185 * Get all the encounter medium ids currently in use.
3189 public static function getUsedEncounterMediums() {
3192 if (!is_array($mediumIds)) {
3193 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3195 $dao = CRM_Core_DAO
::executeQuery($query);
3196 $mediumIds = array();
3197 while ($dao->fetch()) {
3198 $mediumIds[] = $dao->medium_id
;
3206 * Check case configuration.
3208 * @param int $contactId
3212 public static function isCaseConfigured($contactId = NULL) {
3213 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3215 //lets check for case configured.
3216 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3217 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3218 if (!$configured['configured']) {
3219 //do check for case type and case status.
3220 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
3221 if (!empty($caseTypes)) {
3222 $configured['configured'] = TRUE;
3223 if (!$configured['configured']) {
3224 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3225 if (!empty($caseStatuses)) {
3226 $configured['configured'] = TRUE;
3231 if ($configured['configured']) {
3232 //do check for active case type and case status.
3233 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3234 if (!empty($caseTypes)) {
3235 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3236 if (!empty($caseStatuses)) {
3237 $configured['allowToAddNewCase'] = TRUE;
3241 //do we need to redirect user to case admin.
3242 if (!$configured['allowToAddNewCase'] && $contactId) {
3243 //check for current contact case count.
3244 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3245 //redirect user to case admin page.
3246 if (!$currentContatCasesCount) {
3247 $configured['redirectToCaseAdmin'] = TRUE;
3256 * Used during case component enablement and during ugprade.
3260 public static function createCaseViews() {
3261 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
3262 $dao = new CRM_Core_DAO();
3264 $sql = self
::createCaseViewsQuery('upcoming');
3266 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3270 // Above error doesn't get caught?
3271 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3272 if (is_null($doublecheck)) {
3276 $sql = self
::createCaseViewsQuery('recent');
3278 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3282 // Above error doesn't get caught?
3283 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3284 if (is_null($doublecheck)) {
3292 * Helper function, also used by the upgrade in case of error
3294 * @param string $section
3298 public static function createCaseViewsQuery($section = 'upcoming') {
3300 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3303 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3304 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3305 FROM civicrm_case_activity ca
3306 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3307 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3308 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3312 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3313 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3314 FROM civicrm_case_activity ca
3315 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3316 WHERE a.activity_date_time <= NOW()
3317 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3318 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3325 * Add/copy relationships, when new client is added for a case
3327 * @param int $caseId
3329 * @param int $contactId
3330 * Contact id / new client id.
3334 public static function addCaseRelationships($caseId, $contactId) {
3335 // get the case role / relationships for the case
3336 $caseRelationships = new CRM_Contact_DAO_Relationship();
3337 $caseRelationships->case_id
= $caseId;
3338 $caseRelationships->find();
3339 $relationshipTypes = array();
3341 // make sure we don't add duplicate relationships of same relationship type.
3342 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3344 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3346 // add relationship for new client.
3347 $newRelationship = new CRM_Contact_DAO_Relationship();
3348 $newRelationship->copyValues($values);
3349 $newRelationship->id
= NULL;
3350 $newRelationship->case_id
= $caseId;
3351 $newRelationship->contact_id_a
= $contactId;
3352 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3353 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3355 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3356 if (!$newRelationship->find(TRUE)) {
3357 $newRelationship->save();
3359 $newRelationship->free();
3361 // store relationship type of newly created relationship
3362 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3367 * Get the list of clients for a case.
3369 * @param int $caseId
3372 * associated array with client ids
3374 public static function getCaseClients($caseId) {
3376 $caseContact = new CRM_Case_DAO_CaseContact();
3377 $caseContact->case_id
= $caseId;
3378 $caseContact->find();
3380 while ($caseContact->fetch()) {
3381 $clients[] = $caseContact->contact_id
;
3388 * Get options for a given case field.
3389 * @see CRM_Core_DAO::buildOptions
3391 * @param string $fieldName
3392 * @param string $context
3393 * @see CRM_Core_DAO::buildOptionsContext
3394 * @param array $props
3395 * Whatever is known about this dao object.
3397 * @return array|bool
3399 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3400 $className = __CLASS__
;
3402 switch ($fieldName) {
3403 // This field is not part of this object but the api supports it
3405 $className = 'CRM_Activity_BAO_Activity';
3408 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);