3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class 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
48 static $_exportableFields = NULL;
53 public function __construct() {
54 parent
::__construct();
58 * Is CiviCase enabled?
62 public static function enabled() {
63 $config = CRM_Core_Config
::singleton();
64 return in_array('CiviCase', $config->enableComponents
);
68 * Takes an associative array and creates a case object
70 * the function extract all the params it needs to initialize the create a
71 * case object. the params array could contain additional unused name/value
74 * @param array $params
75 * (reference ) an assoc array of name/value pairs.
77 * @return CRM_Case_BAO_Case object
80 public static function add(&$params) {
81 $caseDAO = new CRM_Case_DAO_Case();
82 $caseDAO->copyValues($params);
83 return $caseDAO->save();
87 * Given the list of params in the params array, fetch the object
88 * and store the values in the values array
90 * @param array $params
91 * Input parameters to find object.
92 * @param array $values
93 * Output values of the object.
95 * The array that holds all the db ids.
97 * @return CRM_Case_BAO_Case|null the found object or null
100 public static function &getValues(&$params, &$values, &$ids) {
101 $case = new CRM_Case_BAO_Case();
103 $case->copyValues($params);
105 if ($case->find(TRUE)) {
106 $ids['case'] = $case->id
;
107 CRM_Core_DAO
::storeValues($case, $values);
114 * Takes an associative array and creates a case object
116 * @param array $params
117 * (reference ) an assoc array of name/value pairs.
119 * @return CRM_Case_BAO_Case object
122 public static function &create(&$params) {
123 $transaction = new CRM_Core_Transaction();
125 if (!empty($params['id'])) {
126 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
129 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
132 $case = self
::add($params);
134 if (!empty($params['custom']) &&
135 is_array($params['custom'])
137 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
140 if (is_a($case, 'CRM_Core_Error')) {
141 $transaction->rollback();
145 if (!empty($params['id'])) {
146 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
149 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
151 $transaction->commit();
153 //we are not creating log for case
154 //since case log can be tracked using log for activity.
159 * Create case contact record
161 * @param array case_id, contact_id
165 public static function addCaseToContact($params) {
166 $caseContact = new CRM_Case_DAO_CaseContact();
167 $caseContact->case_id
= $params['case_id'];
168 $caseContact->contact_id
= $params['contact_id'];
169 $caseContact->find(TRUE);
170 $caseContact->save();
172 // add to recently viewed
173 $caseType = CRM_Case_BAO_Case
::getCaseType($caseContact->case_id
);
174 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
175 "action=view&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
178 $title = CRM_Contact_BAO_Contact
::displayName($caseContact->contact_id
) . ' - ' . $caseType;
180 $recentOther = array();
181 if (CRM_Core_Permission
::checkActionPermission('CiviCase', CRM_Core_Action
::DELETE
)) {
182 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/case',
183 "action=delete&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
187 // add the recently created case
188 CRM_Utils_Recent
::add($title,
190 $caseContact->case_id
,
192 $params['contact_id'],
201 * Delet case contact record
207 public static function deleteCaseContact($caseID) {
208 $caseContact = new CRM_Case_DAO_CaseContact();
209 $caseContact->case_id
= $caseID;
210 $caseContact->delete();
212 // delete the recently created Case
217 CRM_Utils_Recent
::del($caseRecent);
221 * convert associative array names to values
224 * This function is used by both the web form layer and the api. Note that
225 * the api needs the name => value conversion, also the view layer typically
226 * requires value => name conversion
228 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
229 $id = $property . '_id';
231 $src = $reverse ?
$property : $id;
232 $dst = $reverse ?
$id : $property;
234 if (!array_key_exists($src, $defaults)) {
238 $look = $reverse ?
array_flip($lookup) : $lookup;
240 if (is_array($look)) {
241 if (!array_key_exists($defaults[$src], $look)) {
245 $defaults[$dst] = $look[$defaults[$src]];
250 * Takes a bunch of params that are needed to match certain criteria and
251 * retrieves the relevant objects. We'll tweak this function to be more
252 * full featured over a period of time. This is the inverse function of
253 * create. It also stores all the retrieved values in the default array
255 * @param array $params
256 * (reference ) an assoc array of name/value pairs.
257 * @param array $defaults
258 * (reference ) an assoc array to hold the name / value pairs.
259 * in a hierarchical manner
261 * (reference) the array that holds all the db ids.
263 * @return CRM_Case_BAO_Case object
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.
280 public static function processCaseActivity(&$params) {
281 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
282 $caseActivityDAO->activity_id
= $params['activity_id'];
283 $caseActivityDAO->case_id
= $params['case_id'];
285 $caseActivityDAO->find(TRUE);
286 $caseActivityDAO->save();
290 * Get the case subject for Activity
292 * @param int $activityId
295 * @return string|null
298 public static function getCaseSubject($activityId) {
299 $caseActivity = new CRM_Case_DAO_CaseActivity();
300 $caseActivity->activity_id
= $activityId;
301 if ($caseActivity->find(TRUE)) {
302 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
311 * @param string $colName
313 * @return string case type
316 public static function getCaseType($caseId, $colName = 'title') {
318 SELECT civicrm_case_type.{$colName} FROM civicrm_case
319 LEFT JOIN civicrm_case_type ON
320 civicrm_case.case_type_id = civicrm_case_type.id
321 WHERE civicrm_case.id = %1";
323 $queryParams = array(1 => array($caseId, 'Integer'));
325 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
329 * Delete the record that are associated with this case
330 * record are deleted from case
333 * Id of the case to delete.
335 * @param bool $moveToTrash
337 * @return bool is successful
340 public static function deleteCase($caseId, $moveToTrash = FALSE) {
341 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
344 $activities = self
::getCaseActivityDates($caseId);
346 foreach ($activities as $value) {
347 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
352 $transaction = new CRM_Core_Transaction();
354 $case = new CRM_Case_DAO_Case();
357 $result = $case->delete();
358 $transaction->commit();
361 $result = $case->is_deleted
= 1;
366 // CRM-7364, disable relationships
367 self
::enableDisableCaseRelationships($caseId, FALSE);
369 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
371 // remove case from recent items.
376 CRM_Utils_Recent
::del($caseRecent);
384 * Enable disable case related relationships
388 * @param bool $enable
394 public static function enableDisableCaseRelationships($caseId, $enable) {
395 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
396 if (!empty($contactIds)) {
397 foreach ($contactIds as $cid) {
398 $roles = self
::getCaseRoles($cid, $caseId);
399 if (!empty($roles)) {
400 $relationshipIds = implode(',', array_keys($roles));
401 $enable = (int) $enable;
402 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
403 WHERE id IN ( {$relationshipIds} )";
404 CRM_Core_DAO
::executeQuery($query);
411 * Delete the activities related to case
413 * @param int $activityId
414 * Id of the activity.
419 public static function deleteCaseActivity($activityId) {
420 $case = new CRM_Case_DAO_CaseActivity();
421 $case->activity_id
= $activityId;
426 * Retrieve contact_id by case_id
431 * @param int $contactID
435 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
436 $caseContact = new CRM_Case_DAO_CaseContact();
437 $caseContact->case_id
= $caseId;
438 $caseContact->find();
439 $contactArray = array();
441 while ($caseContact->fetch()) {
442 if ($contactID != $caseContact->contact_id
) {
443 $contactArray[$count] = $caseContact->contact_id
;
448 return $contactArray;
452 * Look up a case using an activity ID
454 * @param int $activityId
456 * @return int, case ID
458 public static function getCaseIdByActivityId($activityId) {
459 $originalId = CRM_Core_DAO
::singleValueQuery(
460 'SELECT original_id FROM civicrm_activity WHERE id = %1',
461 array('1' => array($activityId, 'Integer'))
463 $caseId = CRM_Core_DAO
::singleValueQuery(
464 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
466 '1' => array($activityId, 'Integer'),
467 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
474 * Retrieve contact names by caseId
483 public static function getContactNames($caseId) {
484 $contactNames = array();
486 return $contactNames;
490 SELECT contact_a.sort_name name,
491 contact_a.display_name as display_name,
493 contact_a.birth_date as birth_date,
496 FROM civicrm_contact contact_a
497 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
498 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
499 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
500 WHERE civicrm_case_contact.case_id = %1";
502 $dao = CRM_Core_DAO
::executeQuery($query,
503 array(1 => array($caseId, 'Integer'))
505 while ($dao->fetch()) {
506 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
507 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
508 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
509 $contactNames[$dao->cid
]['email'] = $dao->email
;
510 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
511 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
512 $contactNames[$dao->cid
]['role'] = ts('Client');
515 return $contactNames;
519 * Retrieve case_id by contact_id
521 * @param int $contactID
522 * @param bool $includeDeleted
523 * Include the deleted cases in result.
524 * @param null $caseType
529 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
532 FROM civicrm_case_contact cc
533 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
535 if (isset($caseType)) {
537 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
538 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
540 if (!isset($caseType)) {
541 $query .= "WHERE cc.contact_id = %1";
543 if (!$includeDeleted) {
544 $query .= " AND ca.is_deleted = 0";
547 $params = array(1 => array($contactID, 'Integer'));
548 $dao = CRM_Core_DAO
::executeQuery($query, $params);
550 $caseArray = array();
551 while ($dao->fetch()) {
552 $caseArray[] = $dao->id
;
560 * @param string $type
562 * @param null $condition
563 * @param int $isDeleted
567 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL, $isDeleted = 0) {
569 $session = CRM_Core_Session
::singleton();
570 $userID = $session->get('userID');
573 $actStatus = array_flip(CRM_Core_PseudoConstant
::activityStatus('name'));
574 $scheduledStatusId = $actStatus['Scheduled'];
577 civicrm_case.id as case_id,
578 civicrm_case.subject as case_subject,
579 civicrm_contact.id as contact_id,
580 civicrm_contact.sort_name as sort_name,
581 civicrm_phone.phone as phone,
582 civicrm_contact.contact_type as contact_type,
583 civicrm_contact.contact_sub_type as contact_sub_type,
584 t_act.activity_type_id,
585 c_type.title as case_type,
586 civicrm_case.case_type_id as case_type_id,
587 cov_status.label as case_status,
588 cov_status.label as case_status_name,
590 civicrm_case.start_date as case_start_date,
591 case_relation_type.label_b_a as case_role, ";
593 if ($type == 'upcoming') {
595 t_act.desired_date as case_scheduled_activity_date,
596 t_act.id as case_scheduled_activity_id,
597 t_act.act_type_name as case_scheduled_activity_type_name,
598 t_act.act_type AS case_scheduled_activity_type ";
600 elseif ($type == 'recent') {
602 t_act.desired_date as case_recent_activity_date,
603 t_act.id as case_recent_activity_id,
604 t_act.act_type_name as case_recent_activity_type_name,
605 t_act.act_type AS case_recent_activity_type ";
607 elseif ($type == 'any') {
609 t_act.desired_date as case_activity_date,
610 t_act.id as case_activity_id,
611 t_act.act_type_name as case_activity_type_name,
612 t_act.act_type AS case_activity_type ";
615 $query .= " FROM civicrm_case
616 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
617 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
619 if ($type == 'upcoming') {
620 // This gets the earliest activity per case that's scheduled within 14 days from now.
621 // 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.
622 // In this case we don't really care which one, so min(id) works.
623 // optimized in CRM-11837
624 $query .= " INNER JOIN
626 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
631 FROM civicrm_view_case_activity_upcoming
632 ORDER BY activity_date_time ASC, id ASC
636 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
637 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
641 elseif ($type == 'recent') {
642 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
643 //improve query performance - CRM-10598
644 $query .= " INNER JOIN
646 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
651 FROM civicrm_view_case_activity_recent
652 ORDER BY activity_date_time DESC, id ASC
656 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
657 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
660 elseif ($type == 'any') {
661 $query .= " LEFT JOIN
663 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
664 FROM civicrm_activity act4
665 LEFT JOIN civicrm_case_activity ca4
666 ON ca4.activity_id = act4.id
667 AND act4.is_current_revision = 1
668 LEFT JOIN civicrm_option_group aog
669 ON aog.name='activity_type'
670 LEFT JOIN civicrm_option_value aov
671 ON aov.option_group_id = aog.id
672 AND aov.value = act4.activity_type_id
677 ON t_act.case_id = civicrm_case.id
678 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
679 LEFT JOIN civicrm_relationship case_relationship
680 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
681 AND case_relationship.case_id = civicrm_case.id )
683 LEFT JOIN civicrm_relationship_type case_relation_type
684 ON ( case_relation_type.id = case_relationship.relationship_type_id
685 AND case_relation_type.id = case_relationship.relationship_type_id )
687 LEFT JOIN civicrm_case_type c_type
688 ON civicrm_case.case_type_id = c_type.id
690 LEFT JOIN civicrm_option_group cog_status
691 ON cog_status.name = 'case_status'
693 LEFT JOIN civicrm_option_value cov_status
694 ON ( civicrm_case.status_id = cov_status.value
695 AND cog_status.id = cov_status.option_group_id )
699 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
700 $query .= " WHERE (1) $condition ";
703 if ($type == 'upcoming') {
704 $query .= " ORDER BY case_scheduled_activity_date ASC ";
706 elseif ($type == 'recent') {
707 $query .= " ORDER BY case_recent_activity_date ASC ";
709 elseif ($type == 'any') {
710 $query .= " ORDER BY case_activity_date ASC ";
717 * Retrieve cases related to particular contact or whole contact
718 * used in Dashboad and Tab
720 * @param bool $allCases
724 * @param string $type
725 * /upcoming,recent,all/.
727 * @param string $context
729 * @return array Array of Cases
732 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
734 $casesList = array();
736 //validate access for own cases.
737 if (!self
::accessCiviCase()) {
742 $session = CRM_Core_Session
::singleton();
743 $userID = $session->get('userID');
746 //validate access for all cases.
747 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
751 $condition = " AND civicrm_case.is_deleted = 0 ";
754 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
756 if ($type == 'upcoming' ||
$type == 'any') {
757 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
759 AND civicrm_case.status_id != $closedId";
762 $query = self
::getCaseActivityQuery($type, $userID, $condition);
764 $queryParams = array();
765 $result = CRM_Core_DAO
::executeQuery($query,
769 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
771 $resultFields = array(
788 if ($type == 'upcoming') {
789 $resultFields[] = 'case_scheduled_activity_date';
790 $resultFields[] = 'case_scheduled_activity_type_name';
791 $resultFields[] = 'case_scheduled_activity_type';
792 $resultFields[] = 'case_scheduled_activity_id';
794 elseif ($type == 'recent') {
795 $resultFields[] = 'case_recent_activity_date';
796 $resultFields[] = 'case_recent_activity_type_name';
797 $resultFields[] = 'case_recent_activity_type';
798 $resultFields[] = 'case_recent_activity_id';
800 elseif ($type == 'any') {
801 $resultFields[] = 'case_activity_date';
802 $resultFields[] = 'case_activity_type_name';
803 $resultFields[] = 'case_activity_type';
804 $resultFields[] = 'case_activity_id';
807 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
808 $actions = CRM_Case_Selector_Search
::links();
810 // check is the user has view/edit signer permission
811 $permissions = array(CRM_Core_Permission
::VIEW
);
812 if (CRM_Core_Permission
::check('access all cases and activities') ||
813 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
815 $permissions[] = CRM_Core_Permission
::EDIT
;
817 if (CRM_Core_Permission
::check('delete in CiviCase')) {
818 $permissions[] = CRM_Core_Permission
::DELETE
;
820 $mask = CRM_Core_Action
::mask($permissions);
822 while ($result->fetch()) {
823 foreach ($resultFields as $donCare => $field) {
824 $casesList[$result->case_id
][$field] = $result->$field;
825 if ($field == 'contact_type') {
826 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
828 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
830 'id' => $result->case_id
,
831 'cid' => $result->contact_id
,
836 'case.actions.primary',
840 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
843 'id' => $result->case_id
,
844 'cid' => $result->contact_id
,
854 elseif ($field == 'case_status') {
855 if (in_array($result->$field, $caseStatus)) {
856 $casesList[$result->case_id
]['class'] = "status-urgent";
859 $casesList[$result->case_id
]['class'] = "status-normal";
864 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
865 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
866 if (!empty($caseManagerContact)) {
867 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
868 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
871 //do check user permissions for edit/view activity.
872 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
873 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
875 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
877 $casesList[$result->case_id
]['activity_type_id'], $userID
879 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
881 $casesList[$result->case_id
]['activity_type_id'], $userID
890 * Get the summary of cases counts by type and status.
892 * @param bool $allCases
896 public static function getCasesSummary($allCases = TRUE, $userID) {
897 $caseSummary = array();
899 //validate access for civicase.
900 if (!self
::accessCiviCase()) {
904 //validate access for all cases.
905 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
909 $caseTypes = CRM_Case_PseudoConstant
::caseType();
910 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
911 $caseTypes = array_flip($caseTypes);
913 // get statuses as headers for the table
914 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
915 foreach ($caseStatuses as $key => $name) {
916 $caseSummary['headers'][$key]['status'] = $name;
917 $caseSummary['headers'][$key]['url'] = $url . $key;
920 // build rows with actual data
922 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
932 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
933 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
937 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
938 case_type_id, case_relationship.contact_id_b
940 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
941 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
942 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
943 AND option_group_case_status.id = case_status.option_group_id )
944 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
945 AND case_relationship.contact_id_b = {$userID})
947 {$myCaseWhereClause} {$myGroupByClause}";
949 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
950 while ($res->fetch()) {
951 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
952 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
955 $rows[$res->case_type
][$res->case_status
] = array(
957 'url' => CRM_Utils_System
::url('civicrm/case/search',
958 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
963 $caseSummary['rows'] = array_merge($caseTypes, $rows);
971 * @param int $contactID
975 * @param int $relationshipID
977 * @return array case role / relationships
981 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
983 SELECT civicrm_relationship.id as civicrm_relationship_id,
984 civicrm_contact.sort_name as sort_name,
985 civicrm_email.email as email,
986 civicrm_phone.phone as phone,
987 civicrm_relationship.contact_id_b as civicrm_contact_id,
988 civicrm_relationship.contact_id_a as client_id,
989 civicrm_relationship_type.label_a_b as relation,
990 civicrm_relationship_type.id as relation_type
991 FROM civicrm_relationship
992 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
993 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
994 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
995 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
996 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
999 1 => array($contactID, 'Positive'),
1000 2 => array($caseID, 'Positive'),
1003 if ($relationshipID) {
1004 $query .= ' AND civicrm_relationship.id = %3 ';
1005 $params[3] = array($relationshipID, 'Integer');
1007 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1010 while ($dao->fetch()) {
1011 $rid = $dao->civicrm_relationship_id
;
1012 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
1013 $values[$rid]['relation'] = $dao->relation
;
1014 $values[$rid]['name'] = $dao->sort_name
;
1015 $values[$rid]['email'] = $dao->email
;
1016 $values[$rid]['phone'] = $dao->phone
;
1017 $values[$rid]['relation_type'] = $dao->relation_type
;
1018 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
1019 $values[$rid]['client_id'] = $dao->client_id
;
1027 * Get Case Activities
1029 * @param int $caseID
1031 * @param array $params
1033 * @param int $contactID
1036 * @param null $context
1037 * @param int $userID
1040 * @return array of case activities
1044 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
1047 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1048 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1049 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1050 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1052 // CRM-5081 - formatting the dates to omit seconds.
1053 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
1054 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
1055 ca.activity_type_id as type,
1056 ca.activity_type_id as activity_type_id,
1057 cc.sort_name as reporter,
1058 cc.id as reporter_id,
1059 acc.sort_name AS assignee,
1060 acc.id AS assignee_id,
1061 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1062 ca.activity_date_time,
1063 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1064 ), '%Y%m%d%H%i00') as overdue_date,
1065 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
1066 ca.status_id as status,
1067 ca.subject as subject,
1068 ca.is_deleted as deleted,
1069 ca.priority_id as priority,
1070 ca.weight as weight,
1071 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1074 FROM civicrm_case_activity cca
1075 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1076 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1077 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1078 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1079 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1080 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1081 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1082 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1083 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1084 LEFT JOIN civicrm_activity_contact caa
1085 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1086 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1088 $where = 'WHERE cca.case_id= %1
1089 AND ca.is_current_revision = 1';
1091 if (!empty($params['reporter_id'])) {
1092 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1095 if (!empty($params['status_id'])) {
1096 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1099 if (!empty($params['activity_deleted'])) {
1100 $where .= " AND ca.is_deleted = 1";
1103 $where .= " AND ca.is_deleted = 0";
1106 if (!empty($params['activity_type_id'])) {
1107 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1110 if (!empty($params['activity_date_low'])) {
1111 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1113 if (!empty($params['activity_date_high'])) {
1114 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1115 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1118 if (!empty($fromActivityDate)) {
1119 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1122 if (!empty($toActivityDate)) {
1123 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1126 // hack to handle to allow initial sorting to be done by query
1127 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1128 $params['sortname'] = NULL;
1131 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1132 $params['sortorder'] = NULL;
1135 $sortname = CRM_Utils_Array
::value('sortname', $params);
1136 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1138 $groupBy = " GROUP BY ca.id ";
1140 if (!$sortname AND !$sortorder) {
1141 // CRM-5081 - added id to act like creation date
1142 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1145 $sort = "{$sortname} {$sortorder}";
1146 $sort = CRM_Utils_Type
::escape($sort, 'String');
1147 $orderBy = " ORDER BY $sort ";
1148 if ($sortname != 'display_date') {
1149 $orderBy .= ', display_date DESC';
1153 $page = CRM_Utils_Array
::value('page', $params);
1154 $rp = CRM_Utils_Array
::value('rp', $params);
1163 $start = (($page - 1) * $rp);
1164 $query = $select . $from . $where . $groupBy . $orderBy;
1166 $params = array(1 => array($caseID, 'Integer'));
1167 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1168 $params['total'] = $dao->N
;
1170 //FIXME: need to optimize/cache these queries
1171 $limit = " LIMIT $start, $rp";
1175 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1177 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1178 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1179 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1181 $url = CRM_Utils_System
::url("civicrm/case/activity",
1182 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1186 if ($context == 'fulltext') {
1187 $contextUrl = "&context={$context}";
1189 $editUrl = "{$url}&action=update{$contextUrl}";
1190 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1191 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1192 $viewTitle = ts('View activity');
1193 $statusTitle = ts('Edit Status');
1195 $emailActivityTypeIDs = array(
1196 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1200 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1206 $emailActivityTypeIDs = array(
1207 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1211 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1217 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1219 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1220 $compStatusValues = array();
1221 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1222 foreach ($compStatusNames as $name) {
1223 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1225 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1226 "reset=1&cid=", FALSE, NULL, FALSE
1228 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1229 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1232 $session = CRM_Core_Session
::singleton();
1233 $userID = $session->get('userID');
1236 while ($dao->fetch()) {
1238 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1239 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1240 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1242 //do not have sufficient permission
1243 //to access given case activity record.
1244 if (!$allowView && !$allowEdit && !$allowDelete) {
1248 $values[$dao->id
]['id'] = $dao->id
;
1249 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1251 $reporterName = $dao->reporter
;
1252 if ($hasViewContact) {
1253 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1255 $values[$dao->id
]['reporter'] = $reporterName;
1256 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1257 $targetContactUrls = $withContacts = array();
1258 foreach ($targetNames as $targetId => $targetName) {
1259 if (!in_array($targetId, $clientIds)) {
1260 $withContacts[$targetId] = $targetName;
1263 foreach ($withContacts as $cid => $name) {
1264 if ($hasViewContact) {
1265 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1267 $targetContactUrls[] = $name;
1269 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1271 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1272 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1274 //check for view activity.
1275 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1277 $url = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $dao->id
));
1278 $subject = '<a class="crm-popup medium-popup" href="' . $url . '" title="' . $viewTitle . '">' . $subject . '</a>';
1280 $values[$dao->id
]['subject'] = $subject;
1282 // add activity assignee to activity selector. CRM-4485.
1283 if (isset($dao->assignee
)) {
1284 if ($dao->ismultiple
== 1) {
1285 if ($dao->reporter_id
!= $dao->assignee_id
) {
1286 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1288 $values[$dao->id
]['assignee'] = $dao->assignee
;
1291 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1294 // 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.
1296 $css = 'class="action-item crm-hover-button"';
1297 $additionalUrl = "&id={$dao->id}";
1298 if (!$dao->deleted
) {
1299 //hide edit link of activity type email.CRM-4530.
1300 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1301 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1303 $url = '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1307 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1310 elseif (!$caseDeleted) {
1311 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1312 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1315 //check for operations.
1316 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1317 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1319 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1320 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1322 // if there are file attachments we will return how many and, if only one, add a link to it
1323 if (!empty($dao->attachment_ids
)) {
1324 $attachmentIDs = explode(',', $dao->attachment_ids
);
1325 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1326 if ($values[$dao->id
]['no_attachments'] == 1) {
1327 // if there is only one it's easy to do a link - otherwise just flag it
1328 $attachmentViewUrl = CRM_Utils_System
::url(
1330 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1335 $url .= " <a href='$attachmentViewUrl' ><span class='icon paper-icon'></span></a>";
1339 $values[$dao->id
]['links'] = $url;
1340 $values[$dao->id
]['class'] = "";
1342 if (!empty($dao->priority
)) {
1343 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1344 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1346 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1347 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1351 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1352 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1355 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1356 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1359 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1364 $values[$dao->id
]['status'] = '<a class="crm-activity-status crm-activity-status-' . $dao->id
. ' ' . $values[$dao->id
]['class'] . ' crm-activity-change-status crm-editable-enabled" activity_id=' . $dao->id
. ' current_status=' . $dao->status
. ' case_id=' . $caseID . ' href="#" title=\'' . $statusTitle . '\'>' . $values[$dao->id
]['status'] . '</a>';
1373 * Get Case Related Contacts
1375 * @param int $caseID
1377 * @param bool $skipDetails
1378 * If true include details of contacts.
1380 * @return array $searchRows array of return properties
1384 public static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1387 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1388 FROM civicrm_relationship cr
1389 LEFT JOIN civicrm_relationship_type crt
1390 ON crt.id = cr.relationship_type_id
1391 LEFT JOIN civicrm_contact cc
1392 ON cc.id = cr.contact_id_b
1393 LEFT JOIN civicrm_email ce
1394 ON ce.contact_id = cc.id
1395 AND ce.is_primary= 1
1396 WHERE cr.case_id = %1
1399 $params = array(1 => array($caseID, 'Integer'));
1400 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1402 while ($dao->fetch()) {
1404 $values[$dao->id
] = 1;
1408 'contact_id' => $dao->id
,
1409 'display_name' => $dao->name
,
1410 'sort_name' => $dao->sort_name
,
1411 'role' => $dao->role
,
1412 'email' => $dao->email
,
1422 * Send e-mail copy of activity
1424 * @param int $clientId
1425 * @param int $activityId
1427 * @param array $contacts
1428 * Array of related contact.
1430 * @param null $attachments
1431 * @param int $caseId
1435 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1440 $tplParams = $activityInfo = array();
1441 //if its a case activity
1443 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1444 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1445 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1446 $anyActivity = TRUE;
1449 $anyActivity = FALSE;
1451 $tplParams['isCaseActivity'] = 1;
1452 $tplParams['client_id'] = $clientId;
1455 $anyActivity = TRUE;
1458 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1459 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1461 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1463 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1465 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1467 $tplParams['activity'] = $activityInfo;
1468 foreach ($tplParams['activity']['fields'] as $k => $val) {
1469 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1470 $activitySubject = $val['value'];
1474 $session = CRM_Core_Session
::singleton();
1475 // CRM-8926 If user is not logged in, use the activity creator as userID
1476 if (!($userID = $session->get('userID'))) {
1477 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1480 //also create activities simultaneously of this copy.
1481 $activityParams = array();
1483 $activityParams['source_record_id'] = $activityId;
1484 $activityParams['source_contact_id'] = $userID;
1485 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1486 $activityParams['activity_date_time'] = date('YmdHis');
1487 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1488 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1489 $activityParams['case_id'] = $caseId;
1490 $activityParams['is_auto'] = 0;
1491 $activityParams['target_id'] = $clientId;
1493 $tplParams['activitySubject'] = $activitySubject;
1495 // if it’s a case activity, add hashed id to the template (CRM-5916)
1497 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1501 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1503 $receiptFrom = "$name <$address>";
1505 $recordedActivityParams = array();
1507 foreach ($contacts as $mail => $info) {
1508 $tplParams['contact'] = $info;
1509 self
::buildPermissionLinks($tplParams, $activityParams);
1511 $displayName = CRM_Utils_Array
::value('display_name', $info);
1513 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1515 'groupName' => 'msg_tpl_workflow_case',
1516 'valueName' => 'case_activity',
1517 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1518 'tplParams' => $tplParams,
1519 'from' => $receiptFrom,
1520 'toName' => $displayName,
1522 'attachments' => $attachments,
1526 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1527 $activityParams['details'] = $message;
1529 if (!empty($result[$info['contact_id']])) {
1531 * Really only need to record one activity with all the targets combined.
1532 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1533 * but it's always the same content at the moment.
1535 if (empty($recordedActivityParams)) {
1536 $recordedActivityParams = $activityParams;
1539 $recordedActivityParams['subject'] .= "; $displayName";
1541 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1544 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1548 if (!empty($recordedActivityParams)) {
1549 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1551 //create case_activity record if its case activity.
1553 $caseParams = array(
1554 'activity_id' => $activity->id
,
1555 'case_id' => $caseId,
1557 self
::processCaseActivity($caseParams);
1565 * Retrieve count of activities having a particular type, and
1566 * associated with a particular case.
1568 * @param int $caseId
1570 * @param int $activityTypeId
1571 * ID of the activity type.
1577 public static function getCaseActivityCount($caseId, $activityTypeId) {
1578 $queryParam = array(
1579 1 => array($caseId, 'Integer'),
1580 2 => array($activityTypeId, 'Integer'),
1582 $query = "SELECT count(ca.id) as countact
1583 FROM civicrm_activity ca
1584 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1585 WHERE ca.activity_type_id = %2
1586 AND cca.case_id = %1
1587 AND ca.is_deleted = 0";
1589 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1590 if ($dao->fetch()) {
1591 return $dao->countact
;
1598 * Create an activity for a case via email
1603 * @return array|void $activity object of newly creted activity via email
1606 public static function recordActivityViaEmail($file) {
1607 if (!file_exists($file) ||
1610 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1615 $result = CRM_Utils_Mail_Incoming
::parse($file);
1616 if ($result['is_error']) {
1620 foreach ($result['to'] as $to) {
1623 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1624 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1626 if ($replacement !== $to['email']) {
1627 $caseId = $replacement;
1628 //if caseId is invalid, return as error file
1629 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1630 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1639 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1640 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1641 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1643 if (!empty($contactDetails[$result['from']['id']])) {
1645 $params['subject'] = $result['subject'];
1646 $params['activity_date_time'] = $result['date'];
1647 $params['details'] = $result['body'];
1648 $params['source_contact_id'] = $result['from']['id'];
1649 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1654 $details = CRM_Case_PseudoConstant
::caseActivityType();
1656 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1657 $result['body'], $matches
1660 if (!empty($matches) && isset($matches[1])) {
1661 $activityType = trim($matches[1]);
1662 if (isset($details[$activityType])) {
1663 $params['activity_type_id'] = $details[$activityType]['id'];
1666 if (!isset($params['activity_type_id'])) {
1667 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1671 $activity = CRM_Activity_BAO_Activity
::create($params);
1673 $caseParams = array(
1674 'activity_id' => $activity->id
,
1675 'case_id' => $caseId,
1677 self
::processCaseActivity($caseParams);
1680 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1681 array(1 => $result['from']['email'])
1688 * Retrieve the scheduled activity type and date
1690 * @param array $cases
1691 * Array of contact and case id.
1693 * @param string $type
1695 * @return array $activityInfo Array of scheduled activity type and date
1700 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1701 $session = CRM_Core_Session
::singleton();
1702 $userID = $session->get('userID');
1704 $caseID = implode(',', $cases['case_id']);
1705 $contactID = implode(',', $cases['contact_id']);
1708 AND civicrm_case_contact.contact_id IN( {$contactID} )
1709 AND civicrm_case.id IN( {$caseID})
1710 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1712 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1714 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1716 $activityInfo = array();
1717 while ($res->fetch()) {
1718 if ($type == 'upcoming') {
1719 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1720 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1723 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1724 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1728 return $activityInfo;
1732 * Combine all the exportable fields from the lower levels object
1734 * @return array array of exportable Fields
1737 public static function &exportableFields() {
1738 if (!self
::$_exportableFields) {
1739 if (!self
::$_exportableFields) {
1740 self
::$_exportableFields = array();
1743 $fields = CRM_Case_DAO_Case
::export();
1744 $fields['case_role'] = array('title' => ts('Role in Case'));
1745 $fields['case_type'] = array(
1746 'title' => ts('Case Type'),
1747 'name' => 'case_type',
1749 $fields['case_status'] = array(
1750 'title' => ts('Case Status'),
1751 'name' => 'case_status',
1754 self
::$_exportableFields = $fields;
1756 return self
::$_exportableFields;
1760 * Restore the record that are associated with this case
1762 * @param int $caseId
1763 * Id of the case to restore.
1765 * @return true if success.
1768 public static function restoreCase($caseId) {
1769 //restore activities
1770 $activities = self
::getCaseActivityDates($caseId);
1772 foreach ($activities as $value) {
1773 CRM_Activity_BAO_Activity
::restoreActivity($value);
1777 $case = new CRM_Case_DAO_Case();
1778 $case->id
= $caseId;
1779 $case->is_deleted
= 0;
1782 //CRM-7364, enable relationships
1783 self
::enableDisableCaseRelationships($caseId, TRUE);
1790 * @param null $showLinks
1791 * @param bool $returnOnlyCount
1792 * @param int $offset
1793 * @param int $rowCount
1797 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1798 $globalContacts = array();
1800 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1801 $settings = $settingsProcessor->run();
1802 if (!empty($settings)) {
1803 $groupInfo['name'] = $settings['groupname'];
1804 if ($groupInfo['name']) {
1805 $searchParams = array('name' => $groupInfo['name']);
1807 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1809 $groupInfo['id'] = $results['id'];
1810 $groupInfo['title'] = $results['title'];
1811 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1812 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1813 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1815 if ($returnOnlyCount) {
1816 return $globalContacts;
1820 foreach ($globalContacts as $idx => $contact) {
1821 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1827 return $globalContacts;
1831 * Convenience function to get both case contacts and global in one array
1832 * @param int $caseId
1836 public static function getRelatedAndGlobalContacts($caseId) {
1837 $relatedContacts = self
::getRelatedContacts($caseId);
1839 $groupInfo = array();
1840 $globalContacts = self
::getGlobalContacts($groupInfo);
1842 //unset values which are not required.
1843 foreach ($globalContacts as $k => & $v) {
1844 unset($v['email_id']);
1845 unset($v['group_contact_id']);
1846 unset($v['status']);
1848 $v['role'] = $groupInfo['title'];
1850 //include multiple listings for the same contact/different roles.
1851 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1852 return $relatedGlobalContacts;
1856 * Get Case ActivitiesDueDates with given criteria.
1858 * @param int $caseID
1860 * @param array $criteriaParams
1862 * @param bool $latestDate
1863 * If set newest or oldest date is selceted.
1865 * @return returns case activities due dates
1869 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1871 $selectDate = " ca.activity_date_time";
1872 $where = $groupBy = ' ';
1879 if (!empty($criteriaParams['activity_type_id'])) {
1880 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1881 $where .= " AND ca.is_current_revision = 1";
1882 $groupBy .= " GROUP BY ca.activity_type_id";
1885 if (!empty($criteriaParams['newest'])) {
1886 $selectDate = " max(ca.activity_date_time) ";
1889 $selectDate = " min(ca.activity_date_time) ";
1893 $query = "SELECT ca.id, {$selectDate} as activity_date
1894 FROM civicrm_activity ca
1895 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1896 WHERE cc.id = %1 {$where} {$groupBy}";
1898 $params = array(1 => array($caseID, 'Integer'));
1899 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1901 while ($dao->fetch()) {
1902 $values[$dao->id
]['id'] = $dao->id
;
1903 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1910 * Create activities when Case or Other roles assigned/modified/deleted.
1912 * @param int $caseId
1913 * @param int $relationshipId
1915 * @param int $relContactId
1916 * Case role assignee contactId.
1917 * @param int $contactId
1919 * @return void on success creates activity and case activity
1923 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1924 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1928 $queryParam = array();
1929 if (is_array($relationshipId)) {
1930 $relationshipId = implode(',', $relationshipId);
1931 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1934 $relationshipClause = " civicrm_relationship.id = %1";
1935 $queryParam[1] = array($relationshipId, 'Positive');
1939 SELECT cc.display_name as clientName,
1940 cca.display_name as assigneeContactName,
1941 civicrm_relationship.case_id as caseId,
1942 civicrm_relationship_type.label_a_b as relation_a_b,
1943 civicrm_relationship_type.label_b_a as relation_b_a,
1944 civicrm_relationship.contact_id_b as rel_contact_id,
1945 civicrm_relationship.contact_id_a as assign_contact_id
1946 FROM civicrm_relationship_type, civicrm_relationship
1947 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1948 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1949 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1951 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1953 while ($dao->fetch()) {
1954 //to get valid assignee contact(s).
1955 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1956 $caseRelationship = $dao->relation_a_b
;
1957 $assigneContactName = $dao->clientName
;
1958 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1961 $caseRelationship = $dao->relation_b_a
;
1962 $assigneContactName = $dao->assigneeContactName
;
1963 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1967 $session = CRM_Core_Session
::singleton();
1968 $activityParams = array(
1969 'source_contact_id' => $session->get('userID'),
1970 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1971 'activity_date_time' => date('YmdHis'),
1972 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1975 //if $relContactId is passed, role is added or modified.
1976 if (!empty($relContactId)) {
1977 $activityParams['assignee_contact_id'] = $assigneContactIds;
1979 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1985 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1991 $activityParams['activity_type_id'] = $activityTypeID;
1993 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1995 //create case_activity record.
1996 $caseParams = array(
1997 'activity_id' => $activity->id
,
1998 'case_id' => $caseId,
2001 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
2006 * contact which is assigned a case role of case manager.
2008 * @param int $caseType
2010 * @param int $caseId
2013 * @return array $caseManagerContact array of contact on success otherwise empty
2017 public static function getCaseManagerContact($caseType, $caseId) {
2018 if (!$caseType ||
!$caseId) {
2022 $caseManagerContact = array();
2023 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2025 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
2027 if (!empty($managerRoleId)) {
2028 $managerRoleQuery = "
2029 SELECT civicrm_contact.id as casemanager_id,
2030 civicrm_contact.sort_name as casemanager
2031 FROM civicrm_contact
2032 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
2033 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
2034 WHERE civicrm_case.id = %2";
2036 $managerRoleParams = array(
2037 1 => array($managerRoleId, 'Integer'),
2038 2 => array($caseId, 'Integer'),
2041 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
2042 if ($dao->fetch()) {
2043 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
2044 $caseManagerContact['casemanager'] = $dao->casemanager
;
2048 return $caseManagerContact;
2052 * Get all cases with no end dates
2054 * @param array $params
2055 * @param array $excludeCaseIds
2056 * @param bool $excludeDeleted
2058 * @return array of case and related data keyed on case id
2060 public static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE, $includeClosed = FALSE) {
2061 //params from ajax call.
2062 $where = array($includeClosed ?
'(1)' : '(ca.end_date is null)');
2063 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
2064 $where[] = "( civicrm_case_type.title LIKE '%$caseType%' )";
2066 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
2067 $config = CRM_Core_Config
::singleton();
2068 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
2069 $where[] = "( sort_name LIKE '$search' )";
2071 if ($cid = CRM_Utils_Array
::value('contact_id', $params)) {
2072 $where[] = " c.id = $cid ";
2074 if (is_array($excludeCaseIds) &&
2075 !CRM_Utils_System
::isNull($excludeCaseIds)
2077 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2079 if ($excludeDeleted) {
2080 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2083 //filter for permissioned cases.
2084 $filterCases = array();
2085 $doFilterCases = FALSE;
2086 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2087 $doFilterCases = TRUE;
2088 $session = CRM_Core_Session
::singleton();
2089 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2091 $whereClause = implode(' AND ', $where);
2094 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
2095 $limitClause = "LIMIT 0, $limit";
2099 SELECT c.id as contact_id,
2102 ca.subject as case_subject,
2103 civicrm_case_type.title as case_type,
2104 ca.start_date as start_date,
2105 ca.end_date as end_date,
2107 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2108 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2109 INNER JOIN civicrm_case_type ON ca.case_type_id = civicrm_case_type.id
2110 WHERE {$whereClause}
2111 ORDER BY c.sort_name, ca.end_date
2114 $dao = CRM_Core_DAO
::executeQuery($query);
2115 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id', 'create');
2117 $unclosedCases = array();
2118 while ($dao->fetch()) {
2119 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2122 $unclosedCases[$dao->id
] = array(
2123 'sort_name' => $dao->sort_name
,
2124 'case_type' => $dao->case_type
,
2125 'contact_id' => $dao->contact_id
,
2126 'start_date' => $dao->start_date
,
2127 'end_date' => $dao->end_date
,
2128 'case_subject' => $dao->case_subject
,
2129 'case_status' => $statuses[$dao->status_id
],
2134 return $unclosedCases;
2138 * @param int $contactId
2139 * @param bool $excludeDeleted
2141 * @return null|string
2143 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2144 $whereConditions = array();
2145 if ($excludeDeleted) {
2146 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2149 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2151 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2152 static $accessibleCaseIds;
2153 if (!is_array($accessibleCaseIds)) {
2154 $session = CRM_Core_Session
::singleton();
2155 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID'), 'any'));
2157 //no need of further processing.
2158 if (empty($accessibleCaseIds)) {
2161 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2165 if (!empty($whereConditions)) {
2166 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2170 SELECT count( civicrm_case.id )
2172 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2175 return CRM_Core_DAO
::singleValueQuery($query);
2179 * Retrieve cases related to particular contact.
2181 * @param int $contactId
2183 * @param bool $excludeDeleted
2184 * Do not include deleted cases.
2186 * @return an array of cases.
2189 public static function getContactCases($contactId, $excludeDeleted = TRUE) {
2195 $whereClause = "civicrm_case_contact.contact_id = %1";
2196 if ($excludeDeleted) {
2197 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2201 SELECT civicrm_case.id, civicrm_case_type.title as case_type, civicrm_case.start_date
2203 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2204 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
2205 WHERE {$whereClause}";
2207 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2208 while ($dao->fetch()) {
2209 $cases[$dao->id
] = array(
2210 'case_id' => $dao->id
,
2211 'case_type' => $dao->case_type
,
2212 'case_start_date' => $dao->start_date
,
2221 * Retrieve related cases for give case.
2223 * @param int $mainCaseId
2225 * @param int $contactId
2227 * @param bool $excludeDeleted
2228 * Do not include deleted cases.
2230 * @return an array of related cases.
2233 public static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2234 //FIXME : do check for permissions.
2236 $relatedCases = array();
2237 if (!$mainCaseId ||
!$contactId) {
2238 return $relatedCases;
2241 $linkActType = array_search('Link Cases',
2242 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2244 if (!$linkActType) {
2245 return $relatedCases;
2248 $whereClause = "mainCase.id = %2";
2249 if ($excludeDeleted) {
2250 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2253 //1. first fetch related case ids.
2255 SELECT relCaseAct.case_id
2256 FROM civicrm_case mainCase
2257 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2258 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2259 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2260 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2261 WHERE $whereClause";
2263 $dao = CRM_Core_DAO
::executeQuery($query, array(
2264 1 => array($linkActType, 'Integer'),
2265 2 => array($mainCaseId, 'Integer'),
2267 $relatedCaseIds = array();
2268 while ($dao->fetch()) {
2269 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2273 // there are no related cases.
2274 if (empty($relatedCaseIds)) {
2275 return $relatedCases;
2278 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2279 if ($excludeDeleted) {
2280 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2283 //filter for permissioned cases.
2284 $filterCases = array();
2285 $doFilterCases = FALSE;
2286 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2287 $doFilterCases = TRUE;
2288 $session = CRM_Core_Session
::singleton();
2289 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2292 //2. fetch the details of related cases.
2294 SELECT relCase.id as id,
2295 civicrm_case_type.title as case_type,
2296 client.display_name as client_name,
2297 client.id as client_id
2298 FROM civicrm_case relCase
2299 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2300 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2301 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2302 WHERE {$whereClause}";
2304 $dao = CRM_Core_DAO
::executeQuery($query);
2305 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2306 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2308 while ($dao->fetch()) {
2310 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2311 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2312 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2313 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2315 $clientView = $dao->client_name
;
2316 if ($hasViewContact) {
2317 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2320 $relatedCases[$dao->id
] = array(
2321 'case_id' => $dao->id
,
2322 'case_type' => $dao->case_type
,
2323 'client_name' => $clientView,
2324 'links' => $caseView,
2329 return $relatedCases;
2333 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2335 * @see CRM_Dedupe_Merger::cpTables()
2337 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2339 public static function mergeContacts($mainContactId, $otherContactId) {
2340 self
::mergeCases($mainContactId, NULL, $otherContactId);
2344 * Function perform two task.
2345 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2346 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2348 * @param int $mainContactId
2349 * Contact id of main contact record.
2350 * @param int $mainCaseId
2351 * Case id of main case record.
2352 * @param int $otherContactId
2353 * Contact id of record which is going to merge.
2354 * @param int $otherCaseId
2355 * Case id of record which is going to merge.
2357 * @param bool $changeClient
2359 * @return integer|NULL
2362 static function mergeCases(
2363 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2364 $otherCaseId = NULL, $changeClient = FALSE) {
2365 $moveToTrash = TRUE;
2367 $duplicateContacts = FALSE;
2368 if ($mainContactId && $otherContactId &&
2369 $mainContactId != $otherContactId
2371 $duplicateContacts = TRUE;
2374 $duplicateCases = FALSE;
2375 if ($mainCaseId && $otherCaseId &&
2376 $mainCaseId != $otherCaseId
2378 $duplicateCases = TRUE;
2381 $mainCaseIds = array();
2382 if (!$duplicateContacts && !$duplicateCases) {
2383 return $mainCaseIds;
2386 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2387 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2388 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2389 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2390 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2391 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2393 $processCaseIds = array($otherCaseId);
2394 if ($duplicateContacts && !$duplicateCases) {
2395 if ($changeClient) {
2396 $processCaseIds = array($mainCaseId);
2399 //get all case ids for other contact.
2400 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2402 if (!is_array($processCaseIds)) {
2407 $session = CRM_Core_Session
::singleton();
2408 $currentUserId = $session->get('userID');
2410 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2412 // copy all cases and connect to main contact id.
2413 foreach ($processCaseIds as $otherCaseId) {
2414 if ($duplicateContacts) {
2415 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2416 $mainCaseId = $mainCase->id
;
2421 // CRM-11662 Copy Case custom data
2422 $extends = array('case');
2423 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2425 foreach ($groupTree as $groupID => $group) {
2426 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2427 foreach ($group['fields'] as $fieldID => $field) {
2428 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2432 foreach ($table as $tableName => $tableColumns) {
2433 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2434 $tableColumns[0] = $mainCaseId;
2435 $select = 'SELECT ' . implode(', ', $tableColumns);
2436 $from = ' FROM ' . $tableName;
2437 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2438 $query = $insert . $select . $from . $where;
2439 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2445 $mainCaseIds[] = $mainCaseId;
2446 //insert record for case contact.
2447 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2448 $otherCaseContact->case_id
= $otherCaseId;
2449 $otherCaseContact->find();
2450 while ($otherCaseContact->fetch()) {
2451 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2452 $mainCaseContact->case_id
= $mainCaseId;
2453 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2454 if ($mainCaseContact->contact_id
== $otherContactId) {
2455 $mainCaseContact->contact_id
= $mainContactId;
2457 //avoid duplicate object.
2458 if (!$mainCaseContact->find(TRUE)) {
2459 $mainCaseContact->save();
2461 $mainCaseContact->free();
2463 $otherCaseContact->free();
2465 elseif (!$otherContactId) {
2466 $otherContactId = $mainContactId;
2469 if (!$mainCaseId ||
!$otherCaseId ||
2470 !$mainContactId ||
!$otherContactId
2475 // get all activities for other case.
2476 $otherCaseActivities = array();
2477 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2479 //for duplicate cases do not process singleton activities.
2480 $otherActivityIds = $singletonActivityIds = array();
2481 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2482 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2483 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2486 $otherActivityIds[] = $otherActId;
2488 if ($duplicateCases) {
2489 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2492 FROM civicrm_activity
2493 WHERE activity_type_id = $openCaseType
2494 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2495 $dao = CRM_Core_DAO
::executeQuery($sql);
2496 while ($dao->fetch()) {
2497 $singletonActivityIds[] = $dao->id
;
2503 // migrate all activities and connect to main contact.
2504 $copiedActivityIds = $activityMappingIds = array();
2505 sort($otherActivityIds);
2506 foreach ($otherActivityIds as $otherActivityId) {
2508 //for duplicate cases -
2509 //do not migrate singleton activities.
2510 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2514 //migrate activity record.
2515 $otherActivity = new CRM_Activity_DAO_Activity();
2516 $otherActivity->id
= $otherActivityId;
2517 if (!$otherActivity->find(TRUE)) {
2521 $mainActVals = array();
2522 $mainActivity = new CRM_Activity_DAO_Activity();
2523 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2524 $mainActivity->copyValues($mainActVals);
2525 $mainActivity->id
= NULL;
2526 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2527 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2531 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2535 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2538 $mainActivity->save();
2539 $mainActivityId = $mainActivity->id
;
2540 if (!$mainActivityId) {
2544 $activityMappingIds[$otherActivityId] = $mainActivityId;
2545 // insert log of all activities
2546 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2548 $otherActivity->free();
2549 $mainActivity->free();
2550 $copiedActivityIds[] = $otherActivityId;
2552 //create case activity record.
2553 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2554 $mainCaseActivity->case_id
= $mainCaseId;
2555 $mainCaseActivity->activity_id
= $mainActivityId;
2556 $mainCaseActivity->save();
2557 $mainCaseActivity->free();
2559 //migrate source activity.
2560 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2561 $otherSourceActivity->activity_id
= $otherActivityId;
2562 $otherSourceActivity->record_type_id
= $sourceID;
2563 $otherSourceActivity->find();
2564 while ($otherSourceActivity->fetch()) {
2565 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2566 $mainActivitySource->record_type_id
= $sourceID;
2567 $mainActivitySource->activity_id
= $mainActivityId;
2568 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2569 if ($mainActivitySource->contact_id
== $otherContactId) {
2570 $mainActivitySource->contact_id
= $mainContactId;
2572 //avoid duplicate object.
2573 if (!$mainActivitySource->find(TRUE)) {
2574 $mainActivitySource->save();
2576 $mainActivitySource->free();
2578 $otherSourceActivity->free();
2580 //migrate target activities.
2581 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2582 $otherTargetActivity->activity_id
= $otherActivityId;
2583 $otherTargetActivity->record_type_id
= $targetID;
2584 $otherTargetActivity->find();
2585 while ($otherTargetActivity->fetch()) {
2586 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2587 $mainActivityTarget->record_type_id
= $targetID;
2588 $mainActivityTarget->activity_id
= $mainActivityId;
2589 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2590 if ($mainActivityTarget->contact_id
== $otherContactId) {
2591 $mainActivityTarget->contact_id
= $mainContactId;
2593 //avoid duplicate object.
2594 if (!$mainActivityTarget->find(TRUE)) {
2595 $mainActivityTarget->save();
2597 $mainActivityTarget->free();
2599 $otherTargetActivity->free();
2601 //migrate assignee activities.
2602 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2603 $otherAssigneeActivity->activity_id
= $otherActivityId;
2604 $otherAssigneeActivity->record_type_id
= $assigneeID;
2605 $otherAssigneeActivity->find();
2606 while ($otherAssigneeActivity->fetch()) {
2607 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2608 $mainAssigneeActivity->activity_id
= $mainActivityId;
2609 $mainAssigneeActivity->record_type_id
= $assigneeID;
2610 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2611 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2612 $mainAssigneeActivity->contact_id
= $mainContactId;
2614 //avoid duplicate object.
2615 if (!$mainAssigneeActivity->find(TRUE)) {
2616 $mainAssigneeActivity->save();
2618 $mainAssigneeActivity->free();
2620 $otherAssigneeActivity->free();
2622 // copy custom fields and attachments
2624 'activityID' => $otherActivityId,
2625 'mainActivityId' => $mainActivityId,
2627 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2630 //copy case relationship.
2631 if ($duplicateContacts) {
2632 //migrate relationship records.
2633 $otherRelationship = new CRM_Contact_DAO_Relationship();
2634 $otherRelationship->case_id
= $otherCaseId;
2635 $otherRelationship->find();
2636 $otherRelationshipIds = array();
2637 while ($otherRelationship->fetch()) {
2638 $otherRelVals = array();
2639 $updateOtherRel = FALSE;
2640 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2642 $mainRelationship = new CRM_Contact_DAO_Relationship();
2643 $mainRelationship->copyValues($otherRelVals);
2644 $mainRelationship->id
= NULL;
2645 $mainRelationship->case_id
= $mainCaseId;
2646 if ($mainRelationship->contact_id_a
== $otherContactId) {
2647 $updateOtherRel = TRUE;
2648 $mainRelationship->contact_id_a
= $mainContactId;
2651 //case creator change only when we merge user contact.
2652 if ($mainRelationship->contact_id_b
== $otherContactId) {
2653 //do not change creator for change client.
2654 if (!$changeClient) {
2655 $updateOtherRel = TRUE;
2656 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2659 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2660 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2662 //avoid duplicate object.
2663 if (!$mainRelationship->find(TRUE)) {
2664 $mainRelationship->save();
2666 $mainRelationship->free();
2668 //get the other relationship ids to update end date.
2669 if ($updateOtherRel) {
2670 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2673 $otherRelationship->free();
2675 //update other relationships end dates
2676 if (!empty($otherRelationshipIds)) {
2677 $sql = 'UPDATE civicrm_relationship
2678 SET end_date = CURDATE()
2679 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2680 CRM_Core_DAO
::executeQuery($sql);
2684 //move other case to trash.
2685 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2690 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2691 if ($changeClient) {
2692 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2693 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2695 $mergeActType = array_search('Reassigned Case', $activityTypes);
2696 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2699 2 => $otherContactDisplayName,
2700 3 => $mainContactDisplayName,
2705 elseif ($duplicateContacts) {
2706 $mergeActType = array_search('Merge Case', $activityTypes);
2707 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2710 2 => $otherContactId,
2711 3 => $mainContactId,
2717 $mergeActType = array_search('Merge Case', $activityTypes);
2718 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2719 if (!empty($copiedActivityIds)) {
2721 SELECT id, subject, activity_date_time, activity_type_id
2722 FROM civicrm_activity
2723 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2724 $dao = CRM_Core_DAO
::executeQuery($sql);
2725 while ($dao->fetch()) {
2726 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2727 if ($dao->subject
) {
2728 $mergeActSubjectDetails .= " :: {$dao->subject}";
2730 $mergeActSubjectDetails .= "<br />";
2735 //create merge activity record.
2736 $activityParams = array(
2737 'subject' => $mergeActSubject,
2738 'details' => $mergeActSubjectDetails,
2739 'status_id' => array_search('Completed', $activityStatuses),
2740 'activity_type_id' => $mergeActType,
2741 'source_contact_id' => $mainContactId,
2742 'activity_date_time' => date('YmdHis'),
2745 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2746 $mergeActivityId = $mergeActivity->id
;
2747 if (!$mergeActivityId) {
2750 $mergeActivity->free();
2752 //connect merge activity to case.
2753 $mergeCaseAct = array(
2754 'case_id' => $mainCaseId,
2755 'activity_id' => $mergeActivityId,
2758 self
::processCaseActivity($mergeCaseAct);
2761 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2763 return $mainCaseIds;
2767 * Validate contact permission for
2768 * edit/view on activity record and build links.
2770 * @param array $tplParams
2771 * Params to be sent to template for sending email.
2772 * @param array $activityParams
2773 * Info of the activity.
2778 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2779 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2780 'activity_type_id', 'id'
2783 if (!empty($tplParams['isCaseActivity'])) {
2784 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2785 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2788 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2789 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2792 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2793 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2797 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2798 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2801 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2802 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2808 * Validate contact permission for
2809 * given operation on activity record.
2811 * @param int $activityId
2812 * Activity record id.
2813 * @param string $operation
2815 * @param int $actTypeId
2817 * @param int $contactId
2818 * Contact id/if not pass consider logged in.
2819 * @param bool $checkComponent
2820 * Do we need to check component enabled.
2822 * @return boolean $allow true/false
2825 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2827 if (!$actTypeId && $activityId) {
2828 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2831 if (!$activityId ||
!$operation ||
!$actTypeId) {
2835 //do check for civicase component enabled.
2836 if ($checkComponent && !self
::enabled()) {
2840 //do check for cases.
2841 $caseActOperations = array(
2848 if (in_array($operation, $caseActOperations)) {
2849 static $unclosedCases;
2850 if (!is_array($unclosedCases)) {
2851 $unclosedCases = self
::getUnclosedCases();
2853 if ($operation == 'File On Case') {
2854 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2857 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2861 $actionOperations = array('view', 'edit', 'delete');
2862 if (in_array($operation, $actionOperations)) {
2864 //do cache when user has non/supper permission.
2865 static $allowOperations;
2867 if (!is_array($allowOperations) ||
2868 !array_key_exists($operation, $allowOperations)
2872 $session = CRM_Core_Session
::singleton();
2873 $contactId = $session->get('userID');
2876 //check for permissions.
2877 $permissions = array(
2879 'access my cases and activities',
2880 'access all cases and activities',
2883 'access my cases and activities',
2884 'access all cases and activities',
2886 'delete' => array('delete activities'),
2889 //check for core permission.
2890 $hasPermissions = array();
2891 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2892 if (is_array($checkPermissions)) {
2893 foreach ($checkPermissions as $per) {
2894 if (CRM_Core_Permission
::check($per)) {
2895 $hasPermissions[$operation][] = $per;
2901 if (!empty($hasPermissions)) {
2902 //need to check activity object specific.
2903 if (in_array($operation, array(
2908 //do we have supper permission.
2909 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2910 $allowOperations[$operation] = $allow = TRUE;
2913 //user has only access to my cases and activity.
2914 //here object specific permmions come in picture.
2916 //edit - contact must be source or assignee
2917 //view - contact must be source/assignee/target
2918 $isTarget = $isAssignee = $isSource = FALSE;
2919 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2920 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2921 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2922 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2924 $target = new CRM_Activity_DAO_ActivityContact();
2925 $target->record_type_id
= $targetID;
2926 $target->activity_id
= $activityId;
2927 $target->contact_id
= $contactId;
2928 if ($target->find(TRUE)) {
2932 $assignee = new CRM_Activity_DAO_ActivityContact();
2933 $assignee->activity_id
= $activityId;
2934 $assignee->record_type_id
= $assigneeID;
2935 $assignee->contact_id
= $contactId;
2936 if ($assignee->find(TRUE)) {
2940 $source = new CRM_Activity_DAO_ActivityContact();
2941 $source->activity_id
= $activityId;
2942 $source->record_type_id
= $sourceID;
2943 $source->contact_id
= $contactId;
2944 if ($source->find(TRUE)) {
2948 if ($operation == 'edit') {
2949 if ($isAssignee ||
$isSource) {
2953 if ($operation == 'view') {
2954 if ($isTarget ||
$isAssignee ||
$isSource) {
2960 elseif (is_array($hasPermissions[$operation])) {
2961 $allowOperations[$operation] = $allow = TRUE;
2965 //contact do not have permission.
2966 $allowOperations[$operation] = FALSE;
2971 //here contact might have supper/non permission.
2972 $allow = $allowOperations[$operation];
2976 //do further only when operation is granted.
2978 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2980 //get the activity type name.
2981 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2983 //do not allow multiple copy / edit action.
2984 $singletonNames = array(
2994 //do not allow to delete these activities, CRM-4543
2995 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2997 //allow edit operation.
2998 $allowEditNames = array('Open Case');
3000 // do not allow File on Case
3001 $doNotFileNames = array(
3004 'Change Case Status',
3005 'Change Case Start Date',
3012 if (in_array($actTypeName, $singletonNames)) {
3014 if ($operation == 'File On Case') {
3015 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
3017 if (in_array($operation, $actionOperations)) {
3019 if ($operation == 'edit') {
3020 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
3022 elseif ($operation == 'delete') {
3023 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
3027 if ($allow && ($operation == 'delete') &&
3028 in_array($actTypeName, $doNotDeleteNames)
3033 if ($allow && ($operation == 'File On Case') &&
3034 in_array($actTypeName, $doNotFileNames)
3039 //check settings file for masking actions
3040 //on the basis the activity types
3041 //hide Edit link if activity type is NOT editable
3042 //(special case activities).CRM-5871
3043 if ($allow && in_array($operation, $actionOperations)) {
3044 static $actionFilter = array();
3045 if (!array_key_exists($operation, $actionFilter)) {
3046 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
3047 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
3049 if (array_key_exists($operation, $actionFilter[$operation]) &&
3050 in_array($actTypeId, $actionFilter[$operation][$operation])
3061 * Since we drop 'access CiviCase', allow access
3062 * if user has 'access my cases and activities'
3063 * or 'access all cases and activities'
3065 public static function accessCiviCase() {
3066 if (!self
::enabled()) {
3070 if (CRM_Core_Permission
::check('access my cases and activities') ||
3071 CRM_Core_Permission
::check('access all cases and activities')
3080 * Verify user has permission to access a case
3082 * @param int $caseId
3083 * @param bool $denyClosed
3084 * Set TRUE if one wants closed cases to be treated as inaccessible.
3088 public static function accessCase($caseId, $denyClosed = TRUE) {
3089 if (!$caseId ||
!self
::enabled()) {
3093 // This permission always has access
3094 if (CRM_Core_Permission
::check('access all cases and activities')) {
3098 // This permission is required at minimum
3099 if (!CRM_Core_Permission
::check('access my cases and activities')) {
3103 $session = CRM_Core_Session
::singleton();
3104 $userID = CRM_Utils_Type
::validate($session->get('userID'), 'Positive');
3105 $caseId = CRM_Utils_Type
::validate($caseId, 'Positive');
3107 $condition = " AND civicrm_case.is_deleted = 0 ";
3108 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
3109 $condition .= " AND civicrm_case.id = {$caseId}";
3112 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
3113 $condition .= " AND civicrm_case.status_id != $closedId";
3116 // We don't actually care about activities in the case, but the underlying
3117 // query is verbose, and this allows us to share the basic query with
3118 // getCases(). $type=='any' means that activities will be left-joined.
3119 $query = self
::getCaseActivityQuery('any', $userID, $condition);
3120 $queryParams = array();
3121 $dao = CRM_Core_DAO
::executeQuery($query,
3125 return (bool) $dao->fetch();
3129 * Check whether activity is a case Activity
3131 * @param int $activityID
3134 * @return boolean $isCaseActivity true/false
3136 public static function isCaseActivity($activityID) {
3137 $isCaseActivity = FALSE;
3139 $params = array(1 => array($activityID, 'Integer'));
3140 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3141 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
3142 $isCaseActivity = TRUE;
3146 return $isCaseActivity;
3150 * Get all the case type ids currently in use
3153 * @return array $caseTypeIds
3155 public static function getUsedCaseType() {
3156 static $caseTypeIds;
3158 if (!is_array($caseTypeIds)) {
3159 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3161 $dao = CRM_Core_DAO
::executeQuery($query);
3162 $caseTypeIds = array();
3163 while ($dao->fetch()) {
3164 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3167 $caseTypeIds[] = $typeId[1];
3171 return $caseTypeIds;
3175 * Get all the case status ids currently in use
3178 * @return array $caseStatusIds
3180 public static function getUsedCaseStatuses() {
3181 static $caseStatusIds;
3183 if (!is_array($caseStatusIds)) {
3184 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3186 $dao = CRM_Core_DAO
::executeQuery($query);
3187 $caseStatusIds = array();
3188 while ($dao->fetch()) {
3189 $caseStatusIds[] = $dao->status_id
;
3193 return $caseStatusIds;
3197 * Get all the encounter medium ids currently in use
3200 public static function getUsedEncounterMediums() {
3203 if (!is_array($mediumIds)) {
3204 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3206 $dao = CRM_Core_DAO
::executeQuery($query);
3207 $mediumIds = array();
3208 while ($dao->fetch()) {
3209 $mediumIds[] = $dao->medium_id
;
3217 * Check case configuration.
3219 * @param int $contactId
3221 * @return array $configured
3223 public static function isCaseConfigured($contactId = NULL) {
3224 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3226 //lets check for case configured.
3227 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3228 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3229 if (!$configured['configured']) {
3230 //do check for case type and case status.
3231 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
3232 if (!empty($caseTypes)) {
3233 $configured['configured'] = TRUE;
3234 if (!$configured['configured']) {
3235 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3236 if (!empty($caseStatuses)) {
3237 $configured['configured'] = TRUE;
3242 if ($configured['configured']) {
3243 //do check for active case type and case status.
3244 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3245 if (!empty($caseTypes)) {
3246 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3247 if (!empty($caseStatuses)) {
3248 $configured['allowToAddNewCase'] = TRUE;
3252 //do we need to redirect user to case admin.
3253 if (!$configured['allowToAddNewCase'] && $contactId) {
3254 //check for current contact case count.
3255 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3256 //redirect user to case admin page.
3257 if (!$currentContatCasesCount) {
3258 $configured['redirectToCaseAdmin'] = TRUE;
3267 * Used during case component enablement and during ugprade
3269 public static function createCaseViews() {
3270 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
3271 $dao = new CRM_Core_DAO();
3273 $sql = self
::createCaseViewsQuery('upcoming');
3275 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3279 // Above error doesn't get caught?
3280 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3281 if (is_null($doublecheck)) {
3285 $sql = self
::createCaseViewsQuery('recent');
3287 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3291 // Above error doesn't get caught?
3292 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3293 if (is_null($doublecheck)) {
3301 * Helper function, also used by the upgrade in case of error
3303 public static function createCaseViewsQuery($section = 'upcoming') {
3305 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3308 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3309 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3310 FROM civicrm_case_activity ca
3311 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3312 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3313 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3317 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3318 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3319 FROM civicrm_case_activity ca
3320 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3321 WHERE a.activity_date_time <= NOW()
3322 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3323 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3330 * Add/copy relationships, when new client is added for a case
3332 * @param int $caseId
3334 * @param int $contactId
3335 * Contact id / new client id.
3339 public static function addCaseRelationships($caseId, $contactId) {
3340 // get the case role / relationships for the case
3341 $caseRelationships = new CRM_Contact_DAO_Relationship();
3342 $caseRelationships->case_id
= $caseId;
3343 $caseRelationships->find();
3344 $relationshipTypes = array();
3346 // make sure we don't add duplicate relationships of same relationship type.
3347 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3349 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3351 // add relationship for new client.
3352 $newRelationship = new CRM_Contact_DAO_Relationship();
3353 $newRelationship->copyValues($values);
3354 $newRelationship->id
= NULL;
3355 $newRelationship->case_id
= $caseId;
3356 $newRelationship->contact_id_a
= $contactId;
3357 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3358 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3360 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3361 if (!$newRelationship->find(TRUE)) {
3362 $newRelationship->save();
3364 $newRelationship->free();
3366 // store relationship type of newly created relationship
3367 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3372 * Get the list of clients for a case
3374 * @param int $caseId
3376 * @return array $clients associated array with client ids
3379 public static function getCaseClients($caseId) {
3381 $caseContact = new CRM_Case_DAO_CaseContact();
3382 $caseContact->case_id
= $caseId;
3383 $caseContact->find();
3385 while ($caseContact->fetch()) {
3386 $clients[] = $caseContact->contact_id
;
3393 * Get options for a given case field.
3394 * @see CRM_Core_DAO::buildOptions
3396 * @param string $fieldName
3397 * @param string $context
3398 * : @see CRM_Core_DAO::buildOptionsContext.
3399 * @param array $props
3400 * : whatever is known about this dao object.
3402 * @return Array|bool
3404 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3405 $className = __CLASS__
;
3407 switch ($fieldName) {
3408 // This field is not part of this object but the api supports it
3410 $className = 'CRM_Activity_BAO_Activity';
3413 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);