3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class 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;
50 function __construct() {
51 parent
::__construct();
55 * takes an associative array and creates a case object
57 * the function extract all the params it needs to initialize the create a
58 * case object. the params array could contain additional unused name/value
61 * @param array $params (reference ) an assoc array of name/value pairs
62 * @param array $ids the array that holds all the db ids
64 * @return object CRM_Case_BAO_Case object
68 static function add(&$params) {
69 $caseDAO = new CRM_Case_DAO_Case();
70 $caseDAO->copyValues($params);
71 return $caseDAO->save();
75 * Given the list of params in the params array, fetch the object
76 * and store the values in the values array
78 * @param array $params input parameters to find object
79 * @param array $values output values of the object
80 * @param array $ids the array that holds all the db ids
82 * @return CRM_Case_BAO_Case|null the found object or null
86 static function &getValues(&$params, &$values, &$ids) {
87 $case = new CRM_Case_BAO_Case();
89 $case->copyValues($params);
91 if ($case->find(TRUE)) {
92 $ids['case'] = $case->id
;
93 CRM_Core_DAO
::storeValues($case, $values);
100 * takes an associative array and creates a case object
102 * @param array $params (reference ) an assoc array of name/value pairs
103 * @param array $ids the array that holds all the db ids
105 * @return object CRM_Case_BAO_Case object
109 static function &create(&$params) {
110 $transaction = new CRM_Core_Transaction();
112 if (CRM_Utils_Array
::value('id', $params)) {
113 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
116 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
119 $case = self
::add($params);
121 if (CRM_Utils_Array
::value('custom', $params) &&
122 is_array($params['custom'])
124 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
127 if (is_a($case, 'CRM_Core_Error')) {
128 $transaction->rollback();
132 if (CRM_Utils_Array
::value('id', $params)) {
133 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
136 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
138 $transaction->commit();
140 //we are not creating log for case
141 //since case log can be tracked using log for activity.
146 * Create case contact record
148 * @param array case_id, contact_id
153 static function addCaseToContact($params) {
154 $caseContact = new CRM_Case_DAO_CaseContact();
155 $caseContact->case_id
= $params['case_id'];
156 $caseContact->contact_id
= $params['contact_id'];
157 $caseContact->find(TRUE);
158 $caseContact->save();
160 // add to recently viewed
161 $caseType = CRM_Case_PseudoConstant
::caseTypeName($caseContact->case_id
, 'label');
162 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
163 "action=view&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
166 $title = CRM_Contact_BAO_Contact
::displayName($caseContact->contact_id
) . ' - ' . $caseType['name'];
168 $recentOther = array();
169 if (CRM_Core_Permission
::checkActionPermission('CiviCase', CRM_Core_Action
::DELETE
)) {
170 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/case',
171 "action=delete&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
175 // add the recently created case
176 CRM_Utils_Recent
::add($title,
178 $caseContact->case_id
,
180 $params['contact_id'],
189 * Delet case contact record
196 static function deleteCaseContact($caseID) {
197 $caseContact = new CRM_Case_DAO_CaseContact();
198 $caseContact->case_id
= $caseID;
199 $caseContact->delete();
201 // delete the recently created Case
206 CRM_Utils_Recent
::del($caseRecent);
210 * This function is used to convert associative array names to values
213 * This function is used by both the web form layer and the api. Note that
214 * the api needs the name => value conversion, also the view layer typically
215 * requires value => name conversion
217 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
218 $id = $property . '_id';
220 $src = $reverse ?
$property : $id;
221 $dst = $reverse ?
$id : $property;
223 if (!array_key_exists($src, $defaults)) {
227 $look = $reverse ?
array_flip($lookup) : $lookup;
229 if (is_array($look)) {
230 if (!array_key_exists($defaults[$src], $look)) {
234 $defaults[$dst] = $look[$defaults[$src]];
239 * Takes a bunch of params that are needed to match certain criteria and
240 * retrieves the relevant objects. We'll tweak this function to be more
241 * full featured over a period of time. This is the inverse function of
242 * create. It also stores all the retrieved values in the default array
244 * @param array $params (reference ) an assoc array of name/value pairs
245 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
246 * in a hierarchical manner
247 * @param array $ids (reference) the array that holds all the db ids
249 * @return object CRM_Case_BAO_Case object
253 static function retrieve(&$params, &$defaults, &$ids) {
254 $case = CRM_Case_BAO_Case
::getValues($params, $defaults, $ids);
259 * Function to process case activity add/delete
260 * takes an associative array and
262 * @param array $params (reference ) an assoc array of name/value pairs
267 static function processCaseActivity(&$params) {
268 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
269 $caseActivityDAO->activity_id
= $params['activity_id'];
270 $caseActivityDAO->case_id
= $params['case_id'];
272 $caseActivityDAO->find(TRUE);
273 $caseActivityDAO->save();
277 * Function to get the case subject for Activity
279 * @param int $activityId activity id
281 * @return case subject or null
285 static function getCaseSubject($activityId) {
286 $caseActivity = new CRM_Case_DAO_CaseActivity();
287 $caseActivity->activity_id
= $activityId;
288 if ($caseActivity->find(TRUE)) {
289 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
295 * Function to get the case type.
303 static function getCaseType($caseId, $colName = 'label') {
312 INNER JOIN civicrm_option_group og ON og.name='case_type'
313 INNER JOIN civicrm_option_value ov ON ( ca.case_type_id=ov.value AND ov.option_group_id=og.id )
316 $params = array(1 => array($caseId, 'Integer'));
318 return CRM_Core_DAO
::singleValueQuery($sql, $params);
322 * Delete the record that are associated with this case
323 * record are deleted from case
325 * @param int $caseId id of the case to delete
331 static function deleteCase($caseId, $moveToTrash = FALSE) {
332 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
335 $activities = self
::getCaseActivityDates($caseId);
337 foreach ($activities as $value) {
338 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
343 $transaction = new CRM_Core_Transaction();
345 $case = new CRM_Case_DAO_Case();
348 $result = $case->delete();
349 $transaction->commit();
352 $result = $case->is_deleted
= 1;
357 // CRM-7364, disable relationships
358 self
::enableDisableCaseRelationships($caseId, FALSE);
360 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
362 // remove case from recent items.
367 CRM_Utils_Recent
::del($caseRecent);
375 * Function to enable disable case related relationships
377 * @param int $caseId case id
378 * @param boolean $enable action
384 static function enableDisableCaseRelationships($caseId, $enable) {
385 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
386 if (!empty($contactIds)) {
387 foreach ($contactIds as $cid) {
388 $roles = self
::getCaseRoles($cid, $caseId);
389 if (!empty($roles)) {
390 $relationshipIds = implode(',', array_keys($roles));
391 $enable = (int) $enable;
392 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
393 WHERE id IN ( {$relationshipIds} )";
394 CRM_Core_DAO
::executeQuery($query);
401 * Delete the activities related to case
403 * @param int $activityId id of the activity
409 static function deleteCaseActivity($activityId) {
410 $case = new CRM_Case_DAO_CaseActivity();
411 $case->activity_id
= $activityId;
416 * Retrieve contact_id by case_id
418 * @param int $caseId ID of the case
424 static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
425 $caseContact = new CRM_Case_DAO_CaseContact();
426 $caseContact->case_id
= $caseId;
427 $caseContact->find();
428 $contactArray = array();
430 while ($caseContact->fetch()) {
431 if ($contactID != $caseContact->contact_id
) {
432 $contactArray[$count] = $caseContact->contact_id
;
437 return $contactArray;
441 * Look up a case using an activity ID
443 * @param $activity_id
445 * @return int, case ID
447 static function getCaseIdByActivityId($activityId) {
448 $originalId = CRM_Core_DAO
::singleValueQuery(
449 'SELECT original_id FROM civicrm_activity WHERE id = %1',
450 array('1' => array($activityId, 'Integer'))
452 $caseId = CRM_Core_DAO
::singleValueQuery(
453 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
455 '1' => array($activityId, 'Integer'),
456 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
463 * Retrieve contact names by caseId
465 * @param int $caseId ID of the case
472 static function getContactNames($caseId) {
473 $contactNames = array();
475 return $contactNames;
479 SELECT contact_a.sort_name name,
480 contact_a.display_name as display_name,
482 contact_a.birth_date as birth_date,
485 FROM civicrm_contact contact_a
486 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
487 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
488 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
489 WHERE civicrm_case_contact.case_id = %1";
491 $dao = CRM_Core_DAO
::executeQuery($query,
492 array(1 => array($caseId, 'Integer'))
494 while ($dao->fetch()) {
495 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
496 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
497 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
498 $contactNames[$dao->cid
]['email'] = $dao->email
;
499 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
500 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
501 $contactNames[$dao->cid
]['role'] = ts('Client');
504 return $contactNames;
508 * Retrieve case_id by contact_id
510 * @param int $contactId ID of the contact
511 * @param boolean $includeDeleted include the deleted cases in result
518 static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE) {
521 FROM civicrm_case_contact cc
522 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
523 WHERE cc.contact_id = %1
525 if (!$includeDeleted) {
526 $query .= " AND ca.is_deleted = 0";
529 $params = array(1 => array($contactID, 'Integer'));
530 $dao = CRM_Core_DAO
::executeQuery($query, $params);
532 $caseArray = array();
533 while ($dao->fetch()) {
534 $caseArray[] = $dao->id
;
541 static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL, $isDeleted = 0) {
543 $session = CRM_Core_Session
::singleton();
544 $userID = $session->get('userID');
547 $actStatus = array_flip(CRM_Core_PseudoConstant
::activityStatus('name'));
548 $scheduledStatusId = $actStatus['Scheduled'];
551 civicrm_case.id as case_id,
552 civicrm_case.subject as case_subject,
553 civicrm_contact.id as contact_id,
554 civicrm_contact.sort_name as sort_name,
555 civicrm_phone.phone as phone,
556 civicrm_contact.contact_type as contact_type,
557 civicrm_contact.contact_sub_type as contact_sub_type,
558 t_act.activity_type_id,
559 cov_type.label as case_type,
560 cov_type.name as case_type_name,
561 cov_status.label as case_status,
562 cov_status.label as case_status_name,
564 civicrm_case.start_date as case_start_date,
565 case_relation_type.label_b_a as case_role, ";
567 if ($type == 'upcoming') {
569 t_act.desired_date as case_scheduled_activity_date,
570 t_act.id as case_scheduled_activity_id,
571 t_act.act_type_name as case_scheduled_activity_type_name,
572 t_act.act_type AS case_scheduled_activity_type ";
574 elseif ($type == 'recent') {
576 t_act.desired_date as case_recent_activity_date,
577 t_act.id as case_recent_activity_id,
578 t_act.act_type_name as case_recent_activity_type_name,
579 t_act.act_type AS case_recent_activity_type ";
582 $query .= " FROM civicrm_case
583 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
584 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
586 if ($type == 'upcoming') {
587 // This gets the earliest activity per case that's scheduled within 14 days from now.
588 // 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.
589 // In this case we don't really care which one, so min(id) works.
590 // optimized in CRM-11837
591 $query .= " INNER JOIN
593 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
598 FROM civicrm_view_case_activity_upcoming
599 ORDER BY activity_date_time ASC, id ASC
603 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
604 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
608 elseif ($type == 'recent') {
609 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
610 //improve query performance - CRM-10598
611 $query .= " INNER JOIN
613 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
618 FROM civicrm_view_case_activity_recent
619 ORDER BY activity_date_time DESC, id ASC
623 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
624 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
629 ON t_act.case_id = civicrm_case.id
630 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
631 LEFT JOIN civicrm_relationship case_relationship
632 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
633 AND case_relationship.case_id = civicrm_case.id )
635 LEFT JOIN civicrm_relationship_type case_relation_type
636 ON ( case_relation_type.id = case_relationship.relationship_type_id
637 AND case_relation_type.id = case_relationship.relationship_type_id )
639 LEFT JOIN civicrm_option_group cog_type
640 ON cog_type.name = 'case_type'
642 LEFT JOIN civicrm_option_value cov_type
643 ON ( civicrm_case.case_type_id = cov_type.value
644 AND cog_type.id = cov_type.option_group_id )
646 LEFT JOIN civicrm_option_group cog_status
647 ON cog_status.name = 'case_status'
649 LEFT JOIN civicrm_option_value cov_status
650 ON ( civicrm_case.status_id = cov_status.value
651 AND cog_status.id = cov_status.option_group_id )
655 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
656 $query .= " WHERE (1) $condition ";
659 if ($type == 'upcoming') {
660 $query .= " ORDER BY case_scheduled_activity_date ASC ";
662 elseif ($type == 'recent') {
663 $query .= " ORDER BY case_recent_activity_date ASC ";
670 * Retrieve cases related to particular contact or whole contact
671 * used in Dashboad and Tab
673 * @param boolean $allCases
677 * @param String $type /upcoming,recent,all/
679 * @return array Array of Cases
684 static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
686 $casesList = array();
688 //validate access for own cases.
689 if (!self
::accessCiviCase()) {
694 $session = CRM_Core_Session
::singleton();
695 $userID = $session->get('userID');
698 //validate access for all cases.
699 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
704 $condition = " AND civicrm_case.is_deleted = 0 ";
707 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
710 if ($type == 'upcoming') {
711 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
713 AND civicrm_case.status_id != $closedId";
716 $query = self
::getCaseActivityQuery($type, $userID, $condition);
718 $queryParams = array();
719 $result = CRM_Core_DAO
::executeQuery($query,
723 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
725 $resultFields = array(
742 if ($type == 'upcoming') {
743 $resultFields[] = 'case_scheduled_activity_date';
744 $resultFields[] = 'case_scheduled_activity_type_name';
745 $resultFields[] = 'case_scheduled_activity_type';
746 $resultFields[] = 'case_scheduled_activity_id';
748 elseif ($type == 'recent') {
749 $resultFields[] = 'case_recent_activity_date';
750 $resultFields[] = 'case_recent_activity_type_name';
751 $resultFields[] = 'case_recent_activity_type';
752 $resultFields[] = 'case_recent_activity_id';
755 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
756 $actions = CRM_Case_Selector_Search
::links();
759 // check is the user has view/edit signer permission
760 $permissions = array(CRM_Core_Permission
::VIEW
);
761 if (CRM_Core_Permission
::check('access all cases and activities') ||
762 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
764 $permissions[] = CRM_Core_Permission
::EDIT
;
766 if (CRM_Core_Permission
::check('delete in CiviCase')) {
767 $permissions[] = CRM_Core_Permission
::DELETE
;
769 $mask = CRM_Core_Action
::mask($permissions);
771 while ($result->fetch()) {
772 foreach ($resultFields as $donCare => $field) {
773 $casesList[$result->case_id
][$field] = $result->$field;
774 if ($field == 'contact_type') {
775 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
776 $result->contact_sub_type
: $result->contact_type
778 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
780 'id' => $result->case_id
,
781 'cid' => $result->contact_id
,
786 'case.actions.primary',
790 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
793 'id' => $result->case_id
,
794 'cid' => $result->contact_id
,
804 elseif ($field == 'case_status') {
805 if (in_array($result->$field, $caseStatus)) {
806 $casesList[$result->case_id
]['class'] = "status-urgent";
809 $casesList[$result->case_id
]['class'] = "status-normal";
814 $caseManagerContact = self
::getCaseManagerContact($result->case_type_name
, $result->case_id
);
815 if (!empty($caseManagerContact)) {
816 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
817 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
820 //do check user permissions for edit/view activity.
821 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
822 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
824 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
826 $casesList[$result->case_id
]['activity_type_id'], $userID
828 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
830 $casesList[$result->case_id
]['activity_type_id'], $userID
839 * Function to get the summary of cases counts by type and status.
841 static function getCasesSummary($allCases = TRUE, $userID) {
842 $caseSummary = array();
844 //validate access for civicase.
845 if (!self
::accessCiviCase()) {
849 //validate access for all cases.
850 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
854 $caseTypes = CRM_Case_PseudoConstant
::caseType();
855 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
856 $caseTypes = array_flip($caseTypes);
858 // get statuses as headers for the table
859 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
860 foreach ($caseStatuses as $key => $name) {
861 $caseSummary['headers'][$key]['status'] = $name;
862 $caseSummary['headers'][$key]['url'] = $url . $key;
865 // build rows with actual data
867 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
877 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
878 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
881 $seperator = CRM_Core_DAO
::VALUE_SEPARATOR
;
884 SELECT case_status.label AS case_status, status_id, case_type.label AS case_type,
885 REPLACE(case_type_id,'{$seperator}','') AS case_type_id, case_relationship.contact_id_b
887 LEFT JOIN civicrm_option_group option_group_case_type ON ( option_group_case_type.name = 'case_type' )
888 LEFT JOIN civicrm_option_value case_type ON ( civicrm_case.case_type_id = case_type.value
889 AND option_group_case_type.id = case_type.option_group_id )
890 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
891 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
892 AND option_group_case_status.id = case_status.option_group_id )
893 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
894 AND case_relationship.contact_id_b = {$userID})
896 {$myCaseWhereClause} {$myGroupByClause}";
898 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
899 while ($res->fetch()) {
900 if (CRM_Utils_Array
::value($res->case_type
, $rows) && CRM_Utils_Array
::value($res->case_status
, $rows[$res->case_type
])) {
901 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
904 $rows[$res->case_type
][$res->case_status
] = array(
906 'url' => CRM_Utils_System
::url('civicrm/case/search',
907 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
912 $caseSummary['rows'] = array_merge($caseTypes, $rows);
918 * Function to get Case roles
920 * @param int $contactID contact id
921 * @param int $caseID case id
922 * @return returns case role / relationships
926 static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
928 SELECT civicrm_relationship.id as civicrm_relationship_id,
929 civicrm_contact.sort_name as sort_name,
930 civicrm_email.email as email,
931 civicrm_phone.phone as phone,
932 civicrm_relationship.contact_id_b as civicrm_contact_id,
933 civicrm_relationship.contact_id_a as client_id,
934 civicrm_relationship_type.label_a_b as relation,
935 civicrm_relationship_type.id as relation_type
936 FROM civicrm_relationship
937 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
938 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
939 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
940 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
941 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
945 1 => array($contactID, 'Positive'),
946 2 => array($caseID, 'Positive'),
949 if ($relationshipID) {
950 $query .= ' AND civicrm_relationship.id = %3 ';
951 $params[3] = array($relationshipID, 'Integer');
953 $dao = CRM_Core_DAO
::executeQuery($query, $params);
956 while ($dao->fetch()) {
957 $rid = $dao->civicrm_relationship_id
;
958 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
959 $values[$rid]['relation'] = $dao->relation
;
960 $values[$rid]['name'] = $dao->sort_name
;
961 $values[$rid]['email'] = $dao->email
;
962 $values[$rid]['phone'] = $dao->phone
;
963 $values[$rid]['relation_type'] = $dao->relation_type
;
964 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
965 $values[$rid]['client_id'] = $dao->client_id
;
973 * Function to get Case Activities
975 * @param int $caseID case id
976 * @param array $params posted params
977 * @param int $contactID contact id
979 * @return returns case activities
983 static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
986 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
987 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
988 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
989 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
991 // CRM-5081 - formatting the dates to omit seconds.
992 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
993 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
994 ca.activity_type_id as type,
995 ca.activity_type_id as activity_type_id,
996 cc.sort_name as reporter,
997 cc.id as reporter_id,
998 acc.sort_name AS assignee,
999 acc.id AS assignee_id,
1000 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1001 ca.activity_date_time,
1002 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1003 ), '%Y%m%d%H%i00') as overdue_date,
1004 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
1005 ca.status_id as status,
1006 ca.subject as subject,
1007 ca.is_deleted as deleted,
1008 ca.priority_id as priority,
1009 ca.weight as weight,
1010 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1013 FROM civicrm_case_activity cca
1014 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1015 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1016 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1017 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1018 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1019 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1020 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1021 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1022 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1023 LEFT JOIN civicrm_activity_contact caa
1024 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1025 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1027 $where = 'WHERE cca.case_id= %1
1028 AND ca.is_current_revision = 1';
1030 if (CRM_Utils_Array
::value('reporter_id', $params)) {
1031 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1034 if (CRM_Utils_Array
::value('status_id', $params)) {
1035 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1038 if (CRM_Utils_Array
::value('activity_deleted', $params)) {
1039 $where .= " AND ca.is_deleted = 1";
1042 $where .= " AND ca.is_deleted = 0";
1045 if (CRM_Utils_Array
::value('activity_type_id', $params)) {
1046 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1049 if (CRM_Utils_Array
::value('activity_date_low', $params)) {
1050 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1052 if (CRM_Utils_Array
::value('activity_date_high', $params)) {
1053 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1054 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1057 if (!empty($fromActivityDate)) {
1058 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1061 if (!empty($toActivityDate)) {
1062 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1065 // hack to handle to allow initial sorting to be done by query
1066 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1067 $params['sortname'] = NULL;
1070 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1071 $params['sortorder'] = NULL;
1074 $sortname = CRM_Utils_Array
::value('sortname', $params);
1075 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1077 $groupBy = " GROUP BY ca.id ";
1079 if (!$sortname AND !$sortorder) {
1080 // CRM-5081 - added id to act like creation date
1081 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1084 $sort = "{$sortname} {$sortorder}";
1085 $sort = CRM_Utils_Type
::escape($sort, 'String');
1086 $orderBy = " ORDER BY $sort ";
1087 if ($sortname != 'display_date') {
1088 $orderBy .= ', display_date DESC';
1092 $page = CRM_Utils_Array
::value('page', $params);
1093 $rp = CRM_Utils_Array
::value('rp', $params);
1102 $start = (($page - 1) * $rp);
1103 $query = $select . $from . $where . $groupBy . $orderBy;
1105 $params = array(1 => array($caseID, 'Integer'));
1106 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1107 $params['total'] = $dao->N
;
1109 //FIXME: need to optimize/cache these queries
1110 $limit = " LIMIT $start, $rp";
1114 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1117 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1118 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1119 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1121 $url = CRM_Utils_System
::url("civicrm/case/activity",
1122 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1126 if ($context == 'fulltext') {
1127 $contextUrl = "&context={$context}";
1129 $editUrl = "{$url}&action=update{$contextUrl}";
1130 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1131 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1132 $viewTitle = ts('View this activity.');
1133 $statusTitle = ts('Edit status');
1135 $emailActivityTypeIDs = array(
1136 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1140 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1146 $emailActivityTypeIDs = array(
1147 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1151 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1157 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1159 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1160 $compStatusValues = array();
1161 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1162 foreach ($compStatusNames as $name) {
1163 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1165 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1166 "reset=1&cid=", FALSE, NULL, FALSE
1168 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1169 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1172 $session = CRM_Core_Session
::singleton();
1173 $userID = $session->get('userID');
1176 while ($dao->fetch()) {
1178 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1179 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1180 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1182 //do not have sufficient permission
1183 //to access given case activity record.
1184 if (!$allowView && !$allowEdit && !$allowDelete) {
1188 $values[$dao->id
]['id'] = $dao->id
;
1189 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1191 $reporterName = $dao->reporter
;
1192 if ($hasViewContact) {
1193 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1195 $values[$dao->id
]['reporter'] = $reporterName;
1196 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1197 $targetContactUrls = $withContacts = array();
1198 foreach ($targetNames as $targetId => $targetName) {
1199 if (!in_array($targetId, $clientIds)) {
1200 $withContacts[$targetId] = $targetName;
1203 foreach ($withContacts as $cid => $name) {
1204 if ($hasViewContact) {
1205 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1207 $targetContactUrls[] = $name;
1209 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1211 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1212 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1214 //check for view activity.
1215 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1217 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id
. ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1219 $values[$dao->id
]['subject'] = $subject;
1221 // add activity assignee to activity selector. CRM-4485.
1222 if (isset($dao->assignee
)) {
1223 if ($dao->ismultiple
== 1) {
1224 if ($dao->reporter_id
!= $dao->assignee_id
) {
1225 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1227 $values[$dao->id
]['assignee'] = $dao->assignee
;
1230 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1234 $additionalUrl = "&id={$dao->id}";
1235 if (!$dao->deleted
) {
1236 //hide edit link of activity type email.CRM-4530.
1237 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1238 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1240 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1247 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1250 elseif (!$caseDeleted) {
1251 $url = '<a href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1252 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1255 //check for operations.
1256 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1257 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1259 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1260 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1262 // if there are file attachments we will return how many and, if only one, add a link to it
1263 if (!empty($dao->attachment_ids
)) {
1264 $attachmentIDs = explode(',', $dao->attachment_ids
);
1265 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1266 if ($values[$dao->id
]['no_attachments'] == 1) {
1267 // if there is only one it's easy to do a link - otherwise just flag it
1268 $attachmentViewUrl = CRM_Utils_System
::url(
1270 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1275 $url .= " | " . "<a href=$attachmentViewUrl >" . ts('View Attachment') . '</a> ';
1280 $values[$dao->id
]['links'] = $url;
1281 $values[$dao->id
]['class'] = "";
1283 if (!empty($dao->priority
)) {
1284 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1285 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1287 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1288 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1292 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1293 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1296 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1297 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1300 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1305 $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>';
1314 * Function to get Case Related Contacts
1316 * @param int $caseID case id
1317 * @param boolean $skipDetails if true include details of contacts
1319 * @return returns $searchRows array of returnproperties
1323 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1325 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1326 FROM civicrm_relationship cr
1327 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1328 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1329 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1330 WHERE cr.case_id = %1 AND ce.is_primary= 1
1333 $params = array(1 => array($caseID, 'Integer'));
1334 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1336 while ($dao->fetch()) {
1338 $values[$dao->id
] = 1;
1342 'contact_id' => $dao->id
,
1343 'display_name' => $dao->name
,
1344 'sort_name' => $dao->sort_name
,
1345 'role' => $dao->role
,
1346 'email' => $dao->email
,
1356 * Function that sends e-mail copy of activity
1358 * @param int $activityId activity Id
1359 * @param array $contacts array of related contact
1364 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1369 $tplParams = $activityInfo = array();
1370 //if its a case activity
1372 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1373 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1374 if (CRM_Utils_Array
::value($activityTypeId, $nonCaseActivityTypes)) {
1375 $anyActivity = TRUE;
1378 $anyActivity = FALSE;
1380 $tplParams['isCaseActivity'] = 1;
1381 $tplParams['client_id'] = $clientId;
1384 $anyActivity = TRUE;
1387 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1388 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1390 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1392 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1394 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1396 $tplParams['activity'] = $activityInfo;
1397 foreach ($tplParams['activity']['fields'] as $k => $val) {
1398 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1399 $activitySubject = $val['value'];
1403 $session = CRM_Core_Session
::singleton();
1404 // CRM-8926 If user is not logged in, use the activity creator as userID
1405 if (!($userID = $session->get('userID'))) {
1406 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1409 //also create activities simultaneously of this copy.
1410 $activityParams = array();
1412 $activityParams['source_record_id'] = $activityId;
1413 $activityParams['source_contact_id'] = $userID;
1414 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1415 $activityParams['activity_date_time'] = date('YmdHis');
1416 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1417 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1418 $activityParams['case_id'] = $caseId;
1419 $activityParams['is_auto'] = 0;
1420 $activityParams['target_id'] = $clientId;
1422 $tplParams['activitySubject'] = $activitySubject;
1424 // if it’s a case activity, add hashed id to the template (CRM-5916)
1426 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1430 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1432 $receiptFrom = "$name <$address>";
1434 $recordedActivityParams = array();
1436 foreach ($contacts as $mail => $info) {
1437 $tplParams['contact'] = $info;
1438 self
::buildPermissionLinks($tplParams, $activityParams);
1440 $displayName = CRM_Utils_Array
::value('display_name', $info);
1442 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1444 'groupName' => 'msg_tpl_workflow_case',
1445 'valueName' => 'case_activity',
1446 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1447 'tplParams' => $tplParams,
1448 'from' => $receiptFrom,
1449 'toName' => $displayName,
1451 'attachments' => $attachments,
1455 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1456 $activityParams['details'] = $message;
1458 if (!empty($result[$info['contact_id']])) {
1460 * Really only need to record one activity with all the targets combined.
1461 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1462 * but it's always the same content at the moment.
1464 if (empty($recordedActivityParams)) {
1465 $recordedActivityParams = $activityParams;
1468 $recordedActivityParams['subject'] .= "; $displayName";
1470 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1473 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1477 if (!empty($recordedActivityParams)) {
1478 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1480 //create case_activity record if its case activity.
1482 $caseParams = array(
1483 'activity_id' => $activity->id
,
1484 'case_id' => $caseId,
1486 self
::processCaseActivity($caseParams);
1494 * Retrieve count of activities having a particular type, and
1495 * associated with a particular case.
1497 * @param int $caseId ID of the case
1498 * @param int $activityTypeId ID of the activity type
1505 static function getCaseActivityCount($caseId, $activityTypeId) {
1506 $queryParam = array(
1507 1 => array($caseId, 'Integer'),
1508 2 => array($activityTypeId, 'Integer'),
1510 $query = "SELECT count(ca.id) as countact
1511 FROM civicrm_activity ca
1512 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1513 WHERE ca.activity_type_id = %2
1514 AND cca.case_id = %1
1515 AND ca.is_deleted = 0";
1517 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1518 if ($dao->fetch()) {
1519 return $dao->countact
;
1526 * Create an activity for a case via email
1528 * @param int $file email sent
1530 * @return $activity object of newly creted activity via email
1535 static function recordActivityViaEmail($file) {
1536 if (!file_exists($file) ||
1539 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1544 $result = CRM_Utils_Mail_Incoming
::parse($file);
1545 if ($result['is_error']) {
1549 foreach ($result['to'] as $to) {
1552 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1553 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1555 if ($replacement !== $to['email']) {
1556 $caseId = $replacement;
1557 //if caseId is invalid, return as error file
1558 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1559 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1568 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1569 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1570 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1572 if (CRM_Utils_Array
::value($result['from']['id'], $contactDetails)) {
1574 $params['subject'] = $result['subject'];
1575 $params['activity_date_time'] = $result['date'];
1576 $params['details'] = $result['body'];
1577 $params['source_contact_id'] = $result['from']['id'];
1578 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1583 $details = CRM_Case_PseudoConstant
::caseActivityType();
1585 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1586 $result['body'], $matches
1589 if (!empty($matches) && isset($matches[1])) {
1590 $activityType = trim($matches[1]);
1591 if (isset($details[$activityType])) {
1592 $params['activity_type_id'] = $details[$activityType]['id'];
1595 if (!isset($params['activity_type_id'])) {
1596 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1600 $activity = CRM_Activity_BAO_Activity
::create($params);
1602 $caseParams = array(
1603 'activity_id' => $activity->id
,
1604 'case_id' => $caseId,
1606 self
::processCaseActivity($caseParams);
1609 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1610 array(1 => $result['from']['email'])
1617 * Function to retrieve the scheduled activity type and date
1619 * @param array $cases Array of contact and case id
1621 * @return array $activityInfo Array of scheduled activity type and date
1627 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1628 $session = CRM_Core_Session
::singleton();
1629 $userID = $session->get('userID');
1631 $caseID = implode(',', $cases['case_id']);
1632 $contactID = implode(',', $cases['contact_id']);
1635 AND civicrm_case_contact.contact_id IN( {$contactID} )
1636 AND civicrm_case.id IN( {$caseID})
1637 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1639 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1641 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1643 $activityInfo = array();
1644 while ($res->fetch()) {
1645 if ($type == 'upcoming') {
1646 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1647 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1650 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1651 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1655 return $activityInfo;
1659 * combine all the exportable fields from the lower levels object
1661 * @return array array of exportable Fields
1665 static function &exportableFields() {
1666 if (!self
::$_exportableFields) {
1667 if (!self
::$_exportableFields) {
1668 self
::$_exportableFields = array();
1671 $fields = CRM_Case_DAO_Case
::export();
1672 $fields['case_role'] = array('title' => ts('Role in Case'));
1673 $fields['case_type'] = array(
1674 'title' => ts('Case Type'),
1675 'name' => 'case_type',
1677 $fields['case_status'] = array(
1678 'title' => ts('Case Status'),
1679 'name' => 'case_status',
1682 self
::$_exportableFields = $fields;
1684 return self
::$_exportableFields;
1688 * Restore the record that are associated with this case
1690 * @param int $caseId id of the case to restore
1692 * @return true if success.
1696 static function restoreCase($caseId) {
1697 //restore activities
1698 $activities = self
::getCaseActivityDates($caseId);
1700 foreach ($activities as $value) {
1701 CRM_Activity_BAO_Activity
::restoreActivity($value);
1705 $case = new CRM_Case_DAO_Case();
1706 $case->id
= $caseId;
1707 $case->is_deleted
= 0;
1710 //CRM-7364, enable relationships
1711 self
::enableDisableCaseRelationships($caseId, TRUE);
1715 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1716 $globalContacts = array();
1718 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1719 $settings = $settingsProcessor->run();
1720 if (!empty($settings)) {
1721 $groupInfo['name'] = $settings['groupname'];
1722 if ($groupInfo['name']) {
1723 $searchParams = array('name' => $groupInfo['name']);
1725 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1727 $groupInfo['id'] = $results['id'];
1728 $groupInfo['title'] = $results['title'];
1729 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1730 $return = array('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1731 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1732 list($globalContacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1734 if ($returnOnlyCount) {
1735 return $globalContacts;
1739 foreach ($globalContacts as $idx => $contact) {
1740 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1746 return $globalContacts;
1750 * Convenience function to get both case contacts and global in one array
1752 static function getRelatedAndGlobalContacts($caseId) {
1753 $relatedContacts = self
::getRelatedContacts($caseId);
1755 $groupInfo = array();
1756 $globalContacts = self
::getGlobalContacts($groupInfo);
1758 //unset values which are not required.
1759 foreach ($globalContacts as $k => & $v) {
1760 unset($v['email_id']);
1761 unset($v['group_contact_id']);
1762 unset($v['status']);
1764 $v['role'] = $groupInfo['title'];
1766 //include multiple listings for the same contact/different roles.
1767 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1768 return $relatedGlobalContacts;
1772 * Function to get Case ActivitiesDueDates with given criteria.
1774 * @param int $caseID case id
1775 * @param array $criteriaParams given criteria
1776 * @param boolean $latestDate if set newest or oldest date is selceted.
1778 * @return returns case activities due dates
1782 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1784 $selectDate = " ca.activity_date_time";
1785 $where = $groupBy = ' ';
1792 if (CRM_Utils_Array
::value('activity_type_id', $criteriaParams)) {
1793 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1794 $where .= " AND ca.is_current_revision = 1";
1795 $groupBy .= " GROUP BY ca.activity_type_id";
1798 if (CRM_Utils_Array
::value('newest', $criteriaParams)) {
1799 $selectDate = " max(ca.activity_date_time) ";
1802 $selectDate = " min(ca.activity_date_time) ";
1806 $query = "SELECT ca.id, {$selectDate} as activity_date
1807 FROM civicrm_activity ca
1808 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1809 WHERE cc.id = %1 {$where} {$groupBy}";
1811 $params = array(1 => array($caseID, 'Integer'));
1812 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1814 while ($dao->fetch()) {
1815 $values[$dao->id
]['id'] = $dao->id
;
1816 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1823 * Function to create activities when Case or Other roles assigned/modified/deleted.
1825 * @param int $caseID case id
1826 * @param int $relationshipId relationship id
1827 * @param int $relContactId case role assignee contactId.
1829 * @return void on success creates activity and case activity
1833 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1834 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1838 $queryParam = array();
1839 if (is_array($relationshipId)) {
1840 $relationshipId = implode(',', $relationshipId);
1841 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1844 $relationshipClause = " civicrm_relationship.id = %1";
1845 $queryParam[1] = array($relationshipId, 'Positive');
1849 SELECT cc.display_name as clientName,
1850 cca.display_name as assigneeContactName,
1851 civicrm_relationship.case_id as caseId,
1852 civicrm_relationship_type.label_a_b as relation_a_b,
1853 civicrm_relationship_type.label_b_a as relation_b_a,
1854 civicrm_relationship.contact_id_b as rel_contact_id,
1855 civicrm_relationship.contact_id_a as assign_contact_id
1856 FROM civicrm_relationship_type, civicrm_relationship
1857 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1858 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1859 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1861 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1863 while ($dao->fetch()) {
1864 //to get valid assignee contact(s).
1865 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1866 $caseRelationship = $dao->relation_a_b
;
1867 $assigneContactName = $dao->clientName
;
1868 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1871 $caseRelationship = $dao->relation_b_a
;
1872 $assigneContactName = $dao->assigneeContactName
;
1873 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1877 $session = CRM_Core_Session
::singleton();
1878 $activityParams = array(
1879 'source_contact_id' => $session->get('userID'),
1880 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1881 'activity_date_time' => date('YmdHis'),
1882 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1885 //if $relContactId is passed, role is added or modified.
1886 if (!empty($relContactId)) {
1887 $activityParams['assignee_contact_id'] = $assigneContactIds;
1889 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1895 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1901 $activityParams['activity_type_id'] = $activityTypeID;
1903 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1905 //create case_activity record.
1906 $caseParams = array(
1907 'activity_id' => $activity->id
,
1908 'case_id' => $caseId,
1911 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1915 * Function to get case manger
1916 * contact which is assigned a case role of case manager.
1918 * @param int $caseType case type
1919 * @param int $caseId case id
1921 * @return array $caseManagerContact array of contact on success otherwise empty
1925 static function getCaseManagerContact($caseType, $caseId) {
1926 if (!$caseType ||
!$caseId) {
1930 $caseManagerContact = array();
1931 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1933 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1935 if (!empty($managerRoleId)) {
1936 $managerRoleQuery = "
1937 SELECT civicrm_contact.id as casemanager_id,
1938 civicrm_contact.sort_name as casemanager
1939 FROM civicrm_contact
1940 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1941 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1942 WHERE civicrm_case.id = %2";
1944 $managerRoleParams = array(
1945 1 => array($managerRoleId, 'Integer'),
1946 2 => array($caseId, 'Integer'),
1949 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1950 if ($dao->fetch()) {
1951 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1952 $caseManagerContact['casemanager'] = $dao->casemanager
;
1956 return $caseManagerContact;
1960 * Get all cases with no end dates
1962 * @return array of case and related data keyed on case id
1964 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1965 //params from ajax call.
1966 $where = array('( ca.end_date is null )');
1967 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
1968 $where[] = "( ov.label LIKE '%$caseType%' )";
1970 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
1971 $config = CRM_Core_Config
::singleton();
1972 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
1973 $where[] = "( sort_name LIKE '$search' )";
1975 if (is_array($excludeCaseIds) &&
1976 !CRM_Utils_System
::isNull($excludeCaseIds)
1978 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
1980 if ($excludeDeleted) {
1981 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
1984 //filter for permissioned cases.
1985 $filterCases = array();
1986 $doFilterCases = FALSE;
1987 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1988 $doFilterCases = TRUE;
1989 $session = CRM_Core_Session
::singleton();
1990 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1992 $whereClause = implode(' AND ', $where);
1995 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
1996 $limitClause = "LIMIT 0, $limit";
2000 SELECT c.id as contact_id,
2003 ca.subject as case_subject,
2004 ov.label as case_type,
2005 ca.start_date as start_date
2006 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2007 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2008 INNER JOIN civicrm_option_group og ON og.name='case_type'
2009 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2010 WHERE {$whereClause}
2011 ORDER BY c.sort_name
2014 $dao = CRM_Core_DAO
::executeQuery($query);
2015 $unclosedCases = array();
2016 while ($dao->fetch()) {
2017 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2020 $unclosedCases[$dao->id
] = array(
2021 'sort_name' => $dao->sort_name
,
2022 'case_type' => $dao->case_type
,
2023 'contact_id' => $dao->contact_id
,
2024 'start_date' => $dao->start_date
,
2025 'case_subject' => $dao->case_subject
,
2030 return $unclosedCases;
2033 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2034 $whereConditions = array();
2035 if ($excludeDeleted) {
2036 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2039 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2041 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2042 static $accessibleCaseIds;
2043 if (!is_array($accessibleCaseIds)) {
2044 $session = CRM_Core_Session
::singleton();
2045 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID')));
2047 //no need of further processing.
2048 if (empty($accessibleCaseIds)) {
2051 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2055 if (!empty($whereConditions)) {
2056 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2060 SELECT count( civicrm_case.id )
2062 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2065 return CRM_Core_DAO
::singleValueQuery($query);
2069 * Retrieve cases related to particular contact.
2071 * @param int $contactId contact id
2072 * @param boolean $excludeDeleted do not include deleted cases.
2074 * @return an array of cases.
2078 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2084 $whereClause = "civicrm_case_contact.contact_id = %1";
2085 if ($excludeDeleted) {
2086 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2090 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2092 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2093 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2094 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2095 AND case_type_og.id = case_type_ov.option_group_id )
2096 WHERE {$whereClause}";
2098 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2099 while ($dao->fetch()) {
2100 $cases[$dao->id
] = array(
2101 'case_id' => $dao->id
,
2102 'case_type' => $dao->case_type
,
2103 'case_start_date' => $dao->start_date
,
2112 * Retrieve related cases for give case.
2114 * @param int $mainCaseId id of main case
2115 * @param int $contactId id of contact
2116 * @param boolean $excludeDeleted do not include deleted cases.
2118 * @return an array of related cases.
2122 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2123 //FIXME : do check for permissions.
2125 $relatedCases = array();
2126 if (!$mainCaseId ||
!$contactId) {
2127 return $relatedCases;
2130 $linkActType = array_search('Link Cases',
2131 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2133 if (!$linkActType) {
2134 return $relatedCases;
2137 $whereClause = "mainCase.id = %2";
2138 if ($excludeDeleted) {
2139 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2142 //1. first fetch related case ids.
2144 SELECT relCaseAct.case_id
2145 FROM civicrm_case mainCase
2146 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2147 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2148 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2149 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2150 WHERE $whereClause";
2152 $dao = CRM_Core_DAO
::executeQuery($query, array(
2153 1 => array($linkActType, 'Integer'),
2154 2 => array($mainCaseId, 'Integer'),
2156 $relatedCaseIds = array();
2157 while ($dao->fetch()) {
2158 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2162 // there are no related cases.
2163 if (empty($relatedCaseIds)) {
2164 return $relatedCases;
2167 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2168 if ($excludeDeleted) {
2169 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2172 //filter for permissioned cases.
2173 $filterCases = array();
2174 $doFilterCases = FALSE;
2175 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2176 $doFilterCases = TRUE;
2177 $session = CRM_Core_Session
::singleton();
2178 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2181 //2. fetch the details of related cases.
2183 SELECT relCase.id as id,
2184 case_type_ov.label as case_type,
2185 client.display_name as client_name,
2186 client.id as client_id
2187 FROM civicrm_case relCase
2188 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2189 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2190 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2191 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2192 AND case_type_og.id = case_type_ov.option_group_id )
2193 WHERE {$whereClause}";
2195 $dao = CRM_Core_DAO
::executeQuery($query);
2196 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2197 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2199 while ($dao->fetch()) {
2201 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2202 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2203 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2204 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2206 $clientView = $dao->client_name
;
2207 if ($hasViewContact) {
2208 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2211 $relatedCases[$dao->id
] = array(
2212 'case_id' => $dao->id
,
2213 'case_type' => $dao->case_type
,
2214 'client_name' => $clientView,
2215 'links' => $caseView,
2220 return $relatedCases;
2224 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2226 * @see CRM_Dedupe_Merger::cpTables()
2228 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2230 static function mergeContacts($mainContactId, $otherContactId) {
2231 self
::mergeCases($mainContactId, NULL, $otherContactId);
2235 * Function perform two task.
2236 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2237 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2239 * @param int $mainContactId contact id of main contact record.
2240 * @param int $mainCaseId case id of main case record.
2241 * @param int $otherContactId contact id of record which is going to merge.
2242 * @param int $otherCaseId case id of record which is going to merge.
2247 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2248 $otherCaseId = NULL, $changeClient = FALSE) {
2249 $moveToTrash = TRUE;
2251 $duplicateContacts = FALSE;
2252 if ($mainContactId && $otherContactId &&
2253 $mainContactId != $otherContactId
2255 $duplicateContacts = TRUE;
2258 $duplicateCases = FALSE;
2259 if ($mainCaseId && $otherCaseId &&
2260 $mainCaseId != $otherCaseId
2262 $duplicateCases = TRUE;
2265 $mainCaseIds = array();
2266 if (!$duplicateContacts && !$duplicateCases) {
2267 return $mainCaseIds;
2270 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2271 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2272 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2273 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2274 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2275 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2277 $processCaseIds = array($otherCaseId);
2278 if ($duplicateContacts && !$duplicateCases) {
2279 if ($changeClient) {
2280 $processCaseIds = array($mainCaseId);
2283 //get all case ids for other contact.
2284 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2286 if (!is_array($processCaseIds)) {
2291 $session = CRM_Core_Session
::singleton();
2292 $currentUserId = $session->get('userID');
2294 // copy all cases and connect to main contact id.
2295 foreach ($processCaseIds as $otherCaseId) {
2296 if ($duplicateContacts) {
2297 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2298 $mainCaseId = $mainCase->id
;
2303 // CRM-11662 Copy Case custom data
2304 $extends = array('case');
2305 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2307 foreach ($groupTree as $groupID => $group) {
2308 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2309 foreach ($group['fields'] as $fieldID => $field) {
2310 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2314 foreach ($table as $tableName => $tableColumns) {
2315 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2316 $tableColumns[0] = $mainCaseId;
2317 $select = 'SELECT ' . implode(', ', $tableColumns);
2318 $from = ' FROM ' . $tableName;
2319 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2320 $query = $insert . $select . $from . $where;
2321 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2327 $mainCaseIds[] = $mainCaseId;
2328 //insert record for case contact.
2329 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2330 $otherCaseContact->case_id
= $otherCaseId;
2331 $otherCaseContact->find();
2332 while ($otherCaseContact->fetch()) {
2333 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2334 $mainCaseContact->case_id
= $mainCaseId;
2335 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2336 if ($mainCaseContact->contact_id
== $otherContactId) {
2337 $mainCaseContact->contact_id
= $mainContactId;
2339 //avoid duplicate object.
2340 if (!$mainCaseContact->find(TRUE)) {
2341 $mainCaseContact->save();
2343 $mainCaseContact->free();
2345 $otherCaseContact->free();
2347 elseif (!$otherContactId) {
2348 $otherContactId = $mainContactId;
2351 if (!$mainCaseId ||
!$otherCaseId ||
2352 !$mainContactId ||
!$otherContactId
2357 // get all activities for other case.
2358 $otherCaseActivities = array();
2359 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2361 //for duplicate cases do not process singleton activities.
2362 $otherActivityIds = $singletonActivityIds = array();
2363 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2364 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2365 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2368 $otherActivityIds[] = $otherActId;
2370 if ($duplicateCases) {
2371 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2374 FROM civicrm_activity
2375 WHERE activity_type_id = $openCaseType
2376 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2377 $dao = CRM_Core_DAO
::executeQuery($sql);
2378 while ($dao->fetch()) {
2379 $singletonActivityIds[] = $dao->id
;
2385 // migrate all activities and connect to main contact.
2386 $copiedActivityIds = $activityMappingIds = array();
2387 sort($otherActivityIds);
2388 foreach ($otherActivityIds as $otherActivityId) {
2390 //for duplicate cases -
2391 //do not migrate singleton activities.
2392 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2396 //migrate activity record.
2397 $otherActivity = new CRM_Activity_DAO_Activity();
2398 $otherActivity->id
= $otherActivityId;
2399 if (!$otherActivity->find(TRUE)) {
2403 $mainActVals = array();
2404 $mainActivity = new CRM_Activity_DAO_Activity();
2405 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2406 $mainActivity->copyValues($mainActVals);
2407 $mainActivity->id
= NULL;
2408 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2409 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2413 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2417 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2420 $mainActivity->save();
2421 $mainActivityId = $mainActivity->id
;
2422 if (!$mainActivityId) {
2426 $activityMappingIds[$otherActivityId] = $mainActivityId;
2427 // insert log of all activities
2428 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2430 $otherActivity->free();
2431 $mainActivity->free();
2432 $copiedActivityIds[] = $otherActivityId;
2434 //create case activity record.
2435 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2436 $mainCaseActivity->case_id
= $mainCaseId;
2437 $mainCaseActivity->activity_id
= $mainActivityId;
2438 $mainCaseActivity->save();
2439 $mainCaseActivity->free();
2441 //migrate source activity.
2442 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2443 $otherSourceActivity->activity_id
= $otherActivityId;
2444 $otherSourceActivity->record_type_id
= $sourceID;
2445 $otherSourceActivity->find();
2446 while ($otherSourceActivity->fetch()) {
2447 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2448 $mainActivitySource->record_type_id
= $sourceID;
2449 $mainActivitySource->activity_id
= $mainActivityId;
2450 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2451 if ($mainActivitySource->contact_id
== $otherContactId) {
2452 $mainActivitySource->contact_id
= $mainContactId;
2454 //avoid duplicate object.
2455 if (!$mainActivitySource->find(TRUE)) {
2456 $mainActivitySource->save();
2458 $mainActivitySource->free();
2460 $otherSourceActivity->free();
2462 //migrate target activities.
2463 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2464 $otherTargetActivity->activity_id
= $otherActivityId;
2465 $otherTargetActivity->record_type_id
= $targetID;
2466 $otherTargetActivity->find();
2467 while ($otherTargetActivity->fetch()) {
2468 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2469 $mainActivityTarget->record_type_id
= $targetID;
2470 $mainActivityTarget->activity_id
= $mainActivityId;
2471 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2472 if ($mainActivityTarget->contact_id
== $otherContactId) {
2473 $mainActivityTarget->contact_id
= $mainContactId;
2475 //avoid duplicate object.
2476 if (!$mainActivityTarget->find(TRUE)) {
2477 $mainActivityTarget->save();
2479 $mainActivityTarget->free();
2481 $otherTargetActivity->free();
2483 //migrate assignee activities.
2484 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2485 $otherAssigneeActivity->activity_id
= $otherActivityId;
2486 $otherAssigneeActivity->record_type_id
= $assigneeID;
2487 $otherAssigneeActivity->find();
2488 while ($otherAssigneeActivity->fetch()) {
2489 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2490 $mainAssigneeActivity->activity_id
= $mainActivityId;
2491 $mainAssigneeActivity->record_type_id
= $assigneeID;
2492 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2493 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2494 $mainAssigneeActivity->contact_id
= $mainContactId;
2496 //avoid duplicate object.
2497 if (!$mainAssigneeActivity->find(TRUE)) {
2498 $mainAssigneeActivity->save();
2500 $mainAssigneeActivity->free();
2502 $otherAssigneeActivity->free();
2504 // copy custom fields and attachments
2506 'activityID' => $otherActivityId,
2507 'mainActivityId' => $mainActivityId,
2509 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2512 //copy case relationship.
2513 if ($duplicateContacts) {
2514 //migrate relationship records.
2515 $otherRelationship = new CRM_Contact_DAO_Relationship();
2516 $otherRelationship->case_id
= $otherCaseId;
2517 $otherRelationship->find();
2518 $otherRelationshipIds = array();
2519 while ($otherRelationship->fetch()) {
2520 $otherRelVals = array();
2521 $updateOtherRel = FALSE;
2522 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2524 $mainRelationship = new CRM_Contact_DAO_Relationship();
2525 $mainRelationship->copyValues($otherRelVals);
2526 $mainRelationship->id
= NULL;
2527 $mainRelationship->case_id
= $mainCaseId;
2528 if ($mainRelationship->contact_id_a
== $otherContactId) {
2529 $updateOtherRel = TRUE;
2530 $mainRelationship->contact_id_a
= $mainContactId;
2533 //case creator change only when we merge user contact.
2534 if ($mainRelationship->contact_id_b
== $otherContactId) {
2535 //do not change creator for change client.
2536 if (!$changeClient) {
2537 $updateOtherRel = TRUE;
2538 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2541 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2542 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2544 //avoid duplicate object.
2545 if (!$mainRelationship->find(TRUE)) {
2546 $mainRelationship->save();
2548 $mainRelationship->free();
2550 //get the other relationship ids to update end date.
2551 if ($updateOtherRel) {
2552 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2555 $otherRelationship->free();
2557 //update other relationships end dates
2558 if (!empty($otherRelationshipIds)) {
2559 $sql = 'UPDATE civicrm_relationship
2560 SET end_date = CURDATE()
2561 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2562 CRM_Core_DAO
::executeQuery($sql);
2566 //move other case to trash.
2567 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2572 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2573 if ($changeClient) {
2574 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2575 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2577 $mergeActType = array_search('Reassigned Case', $activityTypes);
2578 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2581 2 => $otherContactDisplayName,
2582 3 => $mainContactDisplayName,
2587 elseif ($duplicateContacts) {
2588 $mergeActType = array_search('Merge Case', $activityTypes);
2589 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2592 2 => $otherContactId,
2593 3 => $mainContactId,
2599 $mergeActType = array_search('Merge Case', $activityTypes);
2600 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2601 if (!empty($copiedActivityIds)) {
2603 SELECT id, subject, activity_date_time, activity_type_id
2604 FROM civicrm_activity
2605 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2606 $dao = CRM_Core_DAO
::executeQuery($sql);
2607 while ($dao->fetch()) {
2608 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2609 if ($dao->subject
) {
2610 $mergeActSubjectDetails .= " :: {$dao->subject}";
2612 $mergeActSubjectDetails .= "<br />";
2617 //create merge activity record.
2618 $activityParams = array(
2619 'subject' => $mergeActSubject,
2620 'details' => $mergeActSubjectDetails,
2621 'status_id' => array_search('Completed', $activityStatuses),
2622 'activity_type_id' => $mergeActType,
2623 'source_contact_id' => $mainContactId,
2624 'activity_date_time' => date('YmdHis'),
2627 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2628 $mergeActivityId = $mergeActivity->id
;
2629 if (!$mergeActivityId) {
2632 $mergeActivity->free();
2634 //connect merge activity to case.
2635 $mergeCaseAct = array(
2636 'case_id' => $mainCaseId,
2637 'activity_id' => $mergeActivityId,
2640 self
::processCaseActivity($mergeCaseAct);
2642 return $mainCaseIds;
2646 * Validate contact permission for
2647 * edit/view on activity record and build links.
2649 * @param array $tplParams params to be sent to template for sending email.
2650 * @param array $activityParams info of the activity.
2655 static function buildPermissionLinks(&$tplParams, $activityParams) {
2656 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2657 'activity_type_id', 'id'
2660 if (CRM_Utils_Array
::value('isCaseActivity', $tplParams)) {
2661 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2662 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2665 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2666 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2669 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2670 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2674 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2675 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2678 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2679 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2685 * Validate contact permission for
2686 * given operation on activity record.
2688 * @param int $activityId activity record id.
2689 * @param string $operation user operation.
2690 * @param int $actTypeId activity type id.
2691 * @param int $contactId contact id/if not pass consider logged in
2692 * @param boolean $checkComponent do we need to check component enabled.
2694 * @return boolean $allow true/false
2697 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2699 if (!$actTypeId && $activityId) {
2700 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2703 if (!$activityId ||
!$operation ||
!$actTypeId) {
2707 //do check for civicase component enabled.
2708 if ($checkComponent) {
2709 static $componentEnabled;
2710 if (!isset($componentEnabled)) {
2711 $config = CRM_Core_Config
::singleton();
2712 $componentEnabled = FALSE;
2713 if (in_array('CiviCase', $config->enableComponents
)) {
2714 $componentEnabled = TRUE;
2717 if (!$componentEnabled) {
2722 //do check for cases.
2723 $caseActOperations = array(
2730 if (in_array($operation, $caseActOperations)) {
2731 static $unclosedCases;
2732 if (!is_array($unclosedCases)) {
2733 $unclosedCases = self
::getUnclosedCases();
2735 if ($operation == 'File On Case') {
2736 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2739 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2743 $actionOperations = array('view', 'edit', 'delete');
2744 if (in_array($operation, $actionOperations)) {
2746 //do cache when user has non/supper permission.
2747 static $allowOperations;
2749 if (!is_array($allowOperations) ||
2750 !array_key_exists($operation, $allowOperations)
2754 $session = CRM_Core_Session
::singleton();
2755 $contactId = $session->get('userID');
2758 //check for permissions.
2759 $permissions = array(
2761 'access my cases and activities',
2762 'access all cases and activities',
2765 'access my cases and activities',
2766 'access all cases and activities',
2768 'delete' => array('delete activities'),
2771 //check for core permission.
2772 $hasPermissions = array();
2773 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2774 if (is_array($checkPermissions)) {
2775 foreach ($checkPermissions as $per) {
2776 if (CRM_Core_Permission
::check($per)) {
2777 $hasPermissions[$operation][] = $per;
2783 if (!empty($hasPermissions)) {
2784 //need to check activity object specific.
2785 if (in_array($operation, array(
2790 //do we have supper permission.
2791 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2792 $allowOperations[$operation] = $allow = TRUE;
2795 //user has only access to my cases and activity.
2796 //here object specific permmions come in picture.
2798 //edit - contact must be source or assignee
2799 //view - contact must be source/assignee/target
2800 $isTarget = $isAssignee = $isSource = FALSE;
2801 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2802 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2803 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2804 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2806 $target = new CRM_Activity_DAO_ActivityContact();
2807 $target->record_type_id
= $targetID;
2808 $target->activity_id
= $activityId;
2809 $target->contact_id
= $contactId;
2810 if ($target->find(TRUE)) {
2814 $assignee = new CRM_Activity_DAO_ActivityContact();
2815 $assignee->activity_id
= $activityId;
2816 $assignee->record_type_id
= $assigneeID;
2817 $assignee->contact_id
= $contactId;
2818 if ($assignee->find(TRUE)) {
2822 $source = new CRM_Activity_DAO_ActivityContact();
2823 $source->activity_id
= $activityId;
2824 $source->record_type_id
= $sourceID;
2825 $source->contact_id
= $contactId;
2826 if ($source->find(TRUE)) {
2830 if ($operation == 'edit') {
2831 if ($isAssignee ||
$isSource) {
2835 if ($operation == 'view') {
2836 if ($isTarget ||
$isAssignee ||
$isSource) {
2842 elseif (is_array($hasPermissions[$operation])) {
2843 $allowOperations[$operation] = $allow = TRUE;
2847 //contact do not have permission.
2848 $allowOperations[$operation] = FALSE;
2853 //here contact might have supper/non permission.
2854 $allow = $allowOperations[$operation];
2858 //do further only when operation is granted.
2860 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2862 //get the activity type name.
2863 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2865 //do not allow multiple copy / edit action.
2866 $singletonNames = array(
2876 //do not allow to delete these activities, CRM-4543
2877 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2879 //allow edit operation.
2880 $allowEditNames = array('Open Case');
2882 // do not allow File on Case
2883 $doNotFileNames = array(
2886 'Change Case Status',
2887 'Change Case Start Date',
2894 if (in_array($actTypeName, $singletonNames)) {
2896 if ($operation == 'File On Case') {
2897 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2899 if (in_array($operation, $actionOperations)) {
2901 if ($operation == 'edit') {
2902 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2904 elseif ($operation == 'delete') {
2905 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2909 if ($allow && ($operation == 'delete') &&
2910 in_array($actTypeName, $doNotDeleteNames)
2915 if ($allow && ($operation == 'File On Case') &&
2916 in_array($actTypeName, $doNotFileNames)
2921 //check settings file for masking actions
2922 //on the basis the activity types
2923 //hide Edit link if activity type is NOT editable
2924 //(special case activities).CRM-5871
2925 if ($allow && in_array($operation, $actionOperations)) {
2926 static $actionFilter = array();
2927 if (!array_key_exists($operation, $actionFilter)) {
2928 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2929 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2931 if (array_key_exists($operation, $actionFilter[$operation]) &&
2932 in_array($actTypeId, $actionFilter[$operation][$operation])
2943 * since we drop 'access CiviCase', allow access
2944 * if user has 'access my cases and activities'
2945 * or 'access all cases and activities'
2947 static function accessCiviCase() {
2948 static $componentEnabled;
2949 if (!isset($componentEnabled)) {
2950 $componentEnabled = FALSE;
2951 $config = CRM_Core_Config
::singleton();
2952 if (in_array('CiviCase', $config->enableComponents
)) {
2953 $componentEnabled = TRUE;
2956 if (!$componentEnabled) {
2960 if (CRM_Core_Permission
::check('access my cases and activities') ||
2961 CRM_Core_Permission
::check('access all cases and activities')
2970 * Function to check whether activity is a case Activity
2972 * @param int $activityID activity id
2974 * @return boolean $isCaseActivity true/false
2976 static function isCaseActivity($activityID) {
2977 $isCaseActivity = FALSE;
2979 $params = array(1 => array($activityID, 'Integer'));
2980 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2981 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2982 $isCaseActivity = TRUE;
2986 return $isCaseActivity;
2990 * Function to get all the case type ids currently in use
2993 * @return array $caseTypeIds
2995 static function getUsedCaseType() {
2996 static $caseTypeIds;
2998 if (!is_array($caseTypeIds)) {
2999 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3001 $dao = CRM_Core_DAO
::executeQuery($query);
3002 $caseTypeIds = array();
3003 while ($dao->fetch()) {
3004 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3007 $caseTypeIds[] = $typeId[1];
3011 return $caseTypeIds;
3015 * Function to get all the case status ids currently in use
3018 * @return array $caseStatusIds
3020 static function getUsedCaseStatuses() {
3021 static $caseStatusIds;
3023 if (!is_array($caseStatusIds)) {
3024 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3026 $dao = CRM_Core_DAO
::executeQuery($query);
3027 $caseStatusIds = array();
3028 while ($dao->fetch()) {
3029 $caseStatusIds[] = $dao->status_id
;
3033 return $caseStatusIds;
3037 * Function to get all the encounter medium ids currently in use
3040 static function getUsedEncounterMediums() {
3043 if (!is_array($mediumIds)) {
3044 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3046 $dao = CRM_Core_DAO
::executeQuery($query);
3047 $mediumIds = array();
3048 while ($dao->fetch()) {
3049 $mediumIds[] = $dao->medium_id
;
3057 * Function to check case configuration.
3059 * @return array $configured
3061 static function isCaseConfigured($contactId = NULL) {
3062 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3064 //lets check for case configured.
3065 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3066 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3067 if (!$configured['configured']) {
3068 //do check for case type and case status.
3069 $caseTypes = CRM_Case_PseudoConstant
::caseType('label', FALSE);
3070 if (!empty($caseTypes)) {
3071 $configured['configured'] = TRUE;
3072 if (!$configured['configured']) {
3073 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3074 if (!empty($caseStatuses)) {
3075 $configured['configured'] = TRUE;
3080 if ($configured['configured']) {
3081 //do check for active case type and case status.
3082 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3083 if (!empty($caseTypes)) {
3084 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3085 if (!empty($caseStatuses)) {
3086 $configured['allowToAddNewCase'] = TRUE;
3090 //do we need to redirect user to case admin.
3091 if (!$configured['allowToAddNewCase'] && $contactId) {
3092 //check for current contact case count.
3093 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3094 //redirect user to case admin page.
3095 if (!$currentContatCasesCount) {
3096 $configured['redirectToCaseAdmin'] = TRUE;
3105 * Used during case component enablement and during ugprade
3107 static function createCaseViews() {
3108 $dao = new CRM_Core_DAO();
3110 $sql = self
::createCaseViewsQuery('upcoming');
3111 CRM_Core_Error
::ignoreException();
3113 CRM_Core_Error
::setCallback();
3114 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3118 // Above error doesn't get caught?
3119 CRM_Core_Error
::ignoreException();
3120 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3121 CRM_Core_Error
::setCallback();
3122 if (is_null($doublecheck)) {
3126 $sql = self
::createCaseViewsQuery('recent');
3127 CRM_Core_Error
::ignoreException();
3129 CRM_Core_Error
::setCallback();
3130 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3134 // Above error doesn't get caught?
3135 CRM_Core_Error
::ignoreException();
3136 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3137 CRM_Core_Error
::setCallback();
3138 if (is_null($doublecheck)) {
3146 * helper function, also used by the upgrade in case of error
3148 static function createCaseViewsQuery($section = 'upcoming') {
3150 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3153 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3154 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3155 FROM civicrm_case_activity ca
3156 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3157 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3158 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3162 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3163 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3164 FROM civicrm_case_activity ca
3165 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3166 WHERE a.activity_date_time <= NOW()
3167 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3168 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3175 * Function to add/copy relationships, when new client is added for a case
3177 * @param int $caseId case id
3178 * @param int $contactId contact id / new client id
3182 static function addCaseRelationships($caseId, $contactId) {
3183 // get the case role / relationships for the case
3184 $caseRelationships = new CRM_Contact_DAO_Relationship();
3185 $caseRelationships->case_id
= $caseId;
3186 $caseRelationships->find();
3187 $relationshipTypes = array();
3189 // make sure we don't add duplicate relationships of same relationship type.
3190 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3192 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3194 // add relationship for new client.
3195 $newRelationship = new CRM_Contact_DAO_Relationship();
3196 $newRelationship->copyValues($values);
3197 $newRelationship->id
= NULL;
3198 $newRelationship->case_id
= $caseId;
3199 $newRelationship->contact_id_a
= $contactId;
3200 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3201 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3203 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3204 if (!$newRelationship->find(TRUE)) {
3205 $newRelationship->save();
3207 $newRelationship->free();
3209 // store relationship type of newly created relationship
3210 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3215 * Function to get the list of clients for a case
3217 * @param int $caseId
3219 * @return array $clients associated array with client ids
3222 static function getCaseClients($caseId) {
3224 $caseContact = new CRM_Case_DAO_CaseContact();
3225 $caseContact->case_id
= $caseId;
3226 $caseContact->find();
3228 while ($caseContact->fetch()) {
3229 $clients[] = $caseContact->contact_id
;
3236 * Get options for a given case field.
3237 * @see CRM_Core_DAO::buildOptions
3239 * @param String $fieldName
3240 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3241 * @param Array $props: whatever is known about this dao object
3243 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3244 $className = __CLASS__
;
3246 switch ($fieldName) {
3247 // This field is not part of this object but the api supports it
3249 $className = 'CRM_Activity_BAO_Activity';
3252 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);