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
,
785 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
788 'id' => $result->case_id
,
789 'cid' => $result->contact_id
,
796 elseif ($field == 'case_status') {
797 if (in_array($result->$field, $caseStatus)) {
798 $casesList[$result->case_id
]['class'] = "status-urgent";
801 $casesList[$result->case_id
]['class'] = "status-normal";
806 $caseManagerContact = self
::getCaseManagerContact($result->case_type_name
, $result->case_id
);
807 if (!empty($caseManagerContact)) {
808 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
809 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
812 //do check user permissions for edit/view activity.
813 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
814 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
816 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
818 $casesList[$result->case_id
]['activity_type_id'], $userID
820 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
822 $casesList[$result->case_id
]['activity_type_id'], $userID
831 * Function to get the summary of cases counts by type and status.
833 static function getCasesSummary($allCases = TRUE, $userID) {
834 $caseSummary = array();
836 //validate access for civicase.
837 if (!self
::accessCiviCase()) {
841 //validate access for all cases.
842 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
846 $caseTypes = CRM_Case_PseudoConstant
::caseType();
847 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
848 $caseTypes = array_flip($caseTypes);
850 // get statuses as headers for the table
851 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
852 foreach ($caseStatuses as $key => $name) {
853 $caseSummary['headers'][$key]['status'] = $name;
854 $caseSummary['headers'][$key]['url'] = $url . $key;
857 // build rows with actual data
859 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
869 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
870 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
873 $seperator = CRM_Core_DAO
::VALUE_SEPARATOR
;
876 SELECT case_status.label AS case_status, status_id, case_type.label AS case_type,
877 REPLACE(case_type_id,'{$seperator}','') AS case_type_id, case_relationship.contact_id_b
879 LEFT JOIN civicrm_option_group option_group_case_type ON ( option_group_case_type.name = 'case_type' )
880 LEFT JOIN civicrm_option_value case_type ON ( civicrm_case.case_type_id = case_type.value
881 AND option_group_case_type.id = case_type.option_group_id )
882 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
883 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
884 AND option_group_case_status.id = case_status.option_group_id )
885 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
886 AND case_relationship.contact_id_b = {$userID})
888 {$myCaseWhereClause} {$myGroupByClause}";
890 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
891 while ($res->fetch()) {
892 if (CRM_Utils_Array
::value($res->case_type
, $rows) && CRM_Utils_Array
::value($res->case_status
, $rows[$res->case_type
])) {
893 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
896 $rows[$res->case_type
][$res->case_status
] = array(
898 'url' => CRM_Utils_System
::url('civicrm/case/search',
899 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
904 $caseSummary['rows'] = array_merge($caseTypes, $rows);
910 * Function to get Case roles
912 * @param int $contactID contact id
913 * @param int $caseID case id
914 * @return returns case role / relationships
918 static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
920 SELECT civicrm_relationship.id as civicrm_relationship_id,
921 civicrm_contact.sort_name as sort_name,
922 civicrm_email.email as email,
923 civicrm_phone.phone as phone,
924 civicrm_relationship.contact_id_b as civicrm_contact_id,
925 civicrm_relationship.contact_id_a as client_id,
926 civicrm_relationship_type.label_a_b as relation,
927 civicrm_relationship_type.id as relation_type
928 FROM civicrm_relationship
929 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
930 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
931 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
932 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
933 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
937 1 => array($contactID, 'Positive'),
938 2 => array($caseID, 'Positive'),
941 if ($relationshipID) {
942 $query .= ' AND civicrm_relationship.id = %3 ';
943 $params[3] = array($relationshipID, 'Integer');
945 $dao = CRM_Core_DAO
::executeQuery($query, $params);
948 while ($dao->fetch()) {
949 $rid = $dao->civicrm_relationship_id
;
950 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
951 $values[$rid]['relation'] = $dao->relation
;
952 $values[$rid]['name'] = $dao->sort_name
;
953 $values[$rid]['email'] = $dao->email
;
954 $values[$rid]['phone'] = $dao->phone
;
955 $values[$rid]['relation_type'] = $dao->relation_type
;
956 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
957 $values[$rid]['client_id'] = $dao->client_id
;
965 * Function to get Case Activities
967 * @param int $caseID case id
968 * @param array $params posted params
969 * @param int $contactID contact id
971 * @return returns case activities
975 static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
978 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
979 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
980 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
981 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
983 // CRM-5081 - formatting the dates to omit seconds.
984 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
985 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
986 ca.activity_type_id as type,
987 ca.activity_type_id as activity_type_id,
988 cc.sort_name as reporter,
989 cc.id as reporter_id,
990 acc.sort_name AS assignee,
991 acc.id AS assignee_id,
992 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
993 ca.activity_date_time,
994 DATE_ADD(NOW(), INTERVAL 1 YEAR)
995 ), '%Y%m%d%H%i00') as overdue_date,
996 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
997 ca.status_id as status,
998 ca.subject as subject,
999 ca.is_deleted as deleted,
1000 ca.priority_id as priority,
1001 ca.weight as weight,
1002 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1005 FROM civicrm_case_activity cca
1006 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1007 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1008 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1009 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1010 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1011 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1012 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1013 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1014 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1015 LEFT JOIN civicrm_activity_contact caa
1016 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1017 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1019 $where = 'WHERE cca.case_id= %1
1020 AND ca.is_current_revision = 1';
1022 if (CRM_Utils_Array
::value('reporter_id', $params)) {
1023 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1026 if (CRM_Utils_Array
::value('status_id', $params)) {
1027 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1030 if (CRM_Utils_Array
::value('activity_deleted', $params)) {
1031 $where .= " AND ca.is_deleted = 1";
1034 $where .= " AND ca.is_deleted = 0";
1037 if (CRM_Utils_Array
::value('activity_type_id', $params)) {
1038 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1041 if (CRM_Utils_Array
::value('activity_date_low', $params)) {
1042 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1044 if (CRM_Utils_Array
::value('activity_date_high', $params)) {
1045 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1046 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1049 if (!empty($fromActivityDate)) {
1050 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1053 if (!empty($toActivityDate)) {
1054 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1057 // hack to handle to allow initial sorting to be done by query
1058 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1059 $params['sortname'] = NULL;
1062 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1063 $params['sortorder'] = NULL;
1066 $sortname = CRM_Utils_Array
::value('sortname', $params);
1067 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1069 $groupBy = " GROUP BY ca.id ";
1071 if (!$sortname AND !$sortorder) {
1072 // CRM-5081 - added id to act like creation date
1073 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1076 $sort = "{$sortname} {$sortorder}";
1077 $sort = CRM_Utils_Type
::escape($sort, 'String');
1078 $orderBy = " ORDER BY $sort ";
1079 if ($sortname != 'display_date') {
1080 $orderBy .= ', display_date DESC';
1084 $page = CRM_Utils_Array
::value('page', $params);
1085 $rp = CRM_Utils_Array
::value('rp', $params);
1094 $start = (($page - 1) * $rp);
1095 $query = $select . $from . $where . $groupBy . $orderBy;
1097 $params = array(1 => array($caseID, 'Integer'));
1098 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1099 $params['total'] = $dao->N
;
1101 //FIXME: need to optimize/cache these queries
1102 $limit = " LIMIT $start, $rp";
1106 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1109 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1110 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1111 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1113 $url = CRM_Utils_System
::url("civicrm/case/activity",
1114 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1118 if ($context == 'fulltext') {
1119 $contextUrl = "&context={$context}";
1121 $editUrl = "{$url}&action=update{$contextUrl}";
1122 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1123 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1124 $viewTitle = ts('View this activity.');
1125 $statusTitle = ts('Edit status');
1127 $emailActivityTypeIDs = array(
1128 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1132 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1138 $emailActivityTypeIDs = array(
1139 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1143 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1149 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1151 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1152 $compStatusValues = array();
1153 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1154 foreach ($compStatusNames as $name) {
1155 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1157 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1158 "reset=1&cid=", FALSE, NULL, FALSE
1160 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1161 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1164 $session = CRM_Core_Session
::singleton();
1165 $userID = $session->get('userID');
1168 while ($dao->fetch()) {
1170 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1171 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1172 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1174 //do not have sufficient permission
1175 //to access given case activity record.
1176 if (!$allowView && !$allowEdit && !$allowDelete) {
1180 $values[$dao->id
]['id'] = $dao->id
;
1181 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1183 $reporterName = $dao->reporter
;
1184 if ($hasViewContact) {
1185 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1187 $values[$dao->id
]['reporter'] = $reporterName;
1188 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1189 $targetContactUrls = $withContacts = array();
1190 foreach ($targetNames as $targetId => $targetName) {
1191 if (!in_array($targetId, $clientIds)) {
1192 $withContacts[$targetId] = $targetName;
1195 foreach ($withContacts as $cid => $name) {
1196 if ($hasViewContact) {
1197 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1199 $targetContactUrls[] = $name;
1201 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1203 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1204 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1206 //check for view activity.
1207 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1209 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id
. ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1211 $values[$dao->id
]['subject'] = $subject;
1213 // add activity assignee to activity selector. CRM-4485.
1214 if (isset($dao->assignee
)) {
1215 if ($dao->ismultiple
== 1) {
1216 if ($dao->reporter_id
!= $dao->assignee_id
) {
1217 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1219 $values[$dao->id
]['assignee'] = $dao->assignee
;
1222 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1226 $additionalUrl = "&id={$dao->id}";
1227 if (!$dao->deleted
) {
1228 //hide edit link of activity type email.CRM-4530.
1229 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1230 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1232 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1239 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1242 elseif (!$caseDeleted) {
1243 $url = '<a href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1244 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1247 //check for operations.
1248 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1249 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1251 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1252 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1254 // if there are file attachments we will return how many and, if only one, add a link to it
1255 if (!empty($dao->attachment_ids
)) {
1256 $attachmentIDs = explode(',', $dao->attachment_ids
);
1257 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1258 if ($values[$dao->id
]['no_attachments'] == 1) {
1259 // if there is only one it's easy to do a link - otherwise just flag it
1260 $attachmentViewUrl = CRM_Utils_System
::url(
1262 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1267 $url .= " | " . "<a href=$attachmentViewUrl >" . ts('View Attachment') . '</a> ';
1272 $values[$dao->id
]['links'] = $url;
1273 $values[$dao->id
]['class'] = "";
1275 if (!empty($dao->priority
)) {
1276 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1277 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1279 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1280 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1284 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1285 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1288 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1289 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1292 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1297 $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>';
1306 * Function to get Case Related Contacts
1308 * @param int $caseID case id
1309 * @param boolean $skipDetails if true include details of contacts
1311 * @return returns $searchRows array of returnproperties
1315 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1317 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1318 FROM civicrm_relationship cr
1319 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1320 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1321 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1322 WHERE cr.case_id = %1 AND ce.is_primary= 1
1325 $params = array(1 => array($caseID, 'Integer'));
1326 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1328 while ($dao->fetch()) {
1330 $values[$dao->id
] = 1;
1334 'contact_id' => $dao->id
,
1335 'display_name' => $dao->name
,
1336 'sort_name' => $dao->sort_name
,
1337 'role' => $dao->role
,
1338 'email' => $dao->email
,
1348 * Function that sends e-mail copy of activity
1350 * @param int $activityId activity Id
1351 * @param array $contacts array of related contact
1356 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1361 $tplParams = $activityInfo = array();
1362 //if its a case activity
1364 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1365 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1366 if (CRM_Utils_Array
::value($activityTypeId, $nonCaseActivityTypes)) {
1367 $anyActivity = TRUE;
1370 $anyActivity = FALSE;
1372 $tplParams['isCaseActivity'] = 1;
1373 $tplParams['client_id'] = $clientId;
1376 $anyActivity = TRUE;
1379 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1380 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1382 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1384 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1386 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1388 $tplParams['activity'] = $activityInfo;
1389 foreach ($tplParams['activity']['fields'] as $k => $val) {
1390 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1391 $activitySubject = $val['value'];
1395 $session = CRM_Core_Session
::singleton();
1396 // CRM-8926 If user is not logged in, use the activity creator as userID
1397 if (!($userID = $session->get('userID'))) {
1398 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1401 //also create activities simultaneously of this copy.
1402 $activityParams = array();
1404 $activityParams['source_record_id'] = $activityId;
1405 $activityParams['source_contact_id'] = $userID;
1406 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1407 $activityParams['activity_date_time'] = date('YmdHis');
1408 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1409 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1410 $activityParams['case_id'] = $caseId;
1411 $activityParams['is_auto'] = 0;
1412 $activityParams['target_id'] = $clientId;
1414 $tplParams['activitySubject'] = $activitySubject;
1416 // if it’s a case activity, add hashed id to the template (CRM-5916)
1418 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1422 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1424 $receiptFrom = "$name <$address>";
1426 $recordedActivityParams = array();
1428 foreach ($contacts as $mail => $info) {
1429 $tplParams['contact'] = $info;
1430 self
::buildPermissionLinks($tplParams, $activityParams);
1432 $displayName = CRM_Utils_Array
::value('display_name', $info);
1434 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1436 'groupName' => 'msg_tpl_workflow_case',
1437 'valueName' => 'case_activity',
1438 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1439 'tplParams' => $tplParams,
1440 'from' => $receiptFrom,
1441 'toName' => $displayName,
1443 'attachments' => $attachments,
1447 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1448 $activityParams['details'] = $message;
1450 if (!empty($result[$info['contact_id']])) {
1452 * Really only need to record one activity with all the targets combined.
1453 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1454 * but it's always the same content at the moment.
1456 if (empty($recordedActivityParams)) {
1457 $recordedActivityParams = $activityParams;
1460 $recordedActivityParams['subject'] .= "; $displayName";
1462 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1465 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1469 if (!empty($recordedActivityParams)) {
1470 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1472 //create case_activity record if its case activity.
1474 $caseParams = array(
1475 'activity_id' => $activity->id
,
1476 'case_id' => $caseId,
1478 self
::processCaseActivity($caseParams);
1486 * Retrieve count of activities having a particular type, and
1487 * associated with a particular case.
1489 * @param int $caseId ID of the case
1490 * @param int $activityTypeId ID of the activity type
1497 static function getCaseActivityCount($caseId, $activityTypeId) {
1498 $queryParam = array(
1499 1 => array($caseId, 'Integer'),
1500 2 => array($activityTypeId, 'Integer'),
1502 $query = "SELECT count(ca.id) as countact
1503 FROM civicrm_activity ca
1504 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1505 WHERE ca.activity_type_id = %2
1506 AND cca.case_id = %1
1507 AND ca.is_deleted = 0";
1509 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1510 if ($dao->fetch()) {
1511 return $dao->countact
;
1518 * Create an activity for a case via email
1520 * @param int $file email sent
1522 * @return $activity object of newly creted activity via email
1527 static function recordActivityViaEmail($file) {
1528 if (!file_exists($file) ||
1531 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1536 $result = CRM_Utils_Mail_Incoming
::parse($file);
1537 if ($result['is_error']) {
1541 foreach ($result['to'] as $to) {
1544 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1545 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1547 if ($replacement !== $to['email']) {
1548 $caseId = $replacement;
1549 //if caseId is invalid, return as error file
1550 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1551 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1560 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1561 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1562 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1564 if (CRM_Utils_Array
::value($result['from']['id'], $contactDetails)) {
1566 $params['subject'] = $result['subject'];
1567 $params['activity_date_time'] = $result['date'];
1568 $params['details'] = $result['body'];
1569 $params['source_contact_id'] = $result['from']['id'];
1570 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1575 $details = CRM_Case_PseudoConstant
::caseActivityType();
1577 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1578 $result['body'], $matches
1581 if (!empty($matches) && isset($matches[1])) {
1582 $activityType = trim($matches[1]);
1583 if (isset($details[$activityType])) {
1584 $params['activity_type_id'] = $details[$activityType]['id'];
1587 if (!isset($params['activity_type_id'])) {
1588 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1592 $activity = CRM_Activity_BAO_Activity
::create($params);
1594 $caseParams = array(
1595 'activity_id' => $activity->id
,
1596 'case_id' => $caseId,
1598 self
::processCaseActivity($caseParams);
1601 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1602 array(1 => $result['from']['email'])
1609 * Function to retrieve the scheduled activity type and date
1611 * @param array $cases Array of contact and case id
1613 * @return array $activityInfo Array of scheduled activity type and date
1619 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1620 $session = CRM_Core_Session
::singleton();
1621 $userID = $session->get('userID');
1623 $caseID = implode(',', $cases['case_id']);
1624 $contactID = implode(',', $cases['contact_id']);
1627 AND civicrm_case_contact.contact_id IN( {$contactID} )
1628 AND civicrm_case.id IN( {$caseID})
1629 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1631 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1633 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1635 $activityInfo = array();
1636 while ($res->fetch()) {
1637 if ($type == 'upcoming') {
1638 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1639 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1642 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1643 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1647 return $activityInfo;
1651 * combine all the exportable fields from the lower levels object
1653 * @return array array of exportable Fields
1657 static function &exportableFields() {
1658 if (!self
::$_exportableFields) {
1659 if (!self
::$_exportableFields) {
1660 self
::$_exportableFields = array();
1663 $fields = CRM_Case_DAO_Case
::export();
1664 $fields['case_role'] = array('title' => ts('Role in Case'));
1665 $fields['case_type'] = array(
1666 'title' => ts('Case Type'),
1667 'name' => 'case_type',
1669 $fields['case_status'] = array(
1670 'title' => ts('Case Status'),
1671 'name' => 'case_status',
1674 self
::$_exportableFields = $fields;
1676 return self
::$_exportableFields;
1680 * Restore the record that are associated with this case
1682 * @param int $caseId id of the case to restore
1684 * @return true if success.
1688 static function restoreCase($caseId) {
1689 //restore activities
1690 $activities = self
::getCaseActivityDates($caseId);
1692 foreach ($activities as $value) {
1693 CRM_Activity_BAO_Activity
::restoreActivity($value);
1697 $case = new CRM_Case_DAO_Case();
1698 $case->id
= $caseId;
1699 $case->is_deleted
= 0;
1702 //CRM-7364, enable relationships
1703 self
::enableDisableCaseRelationships($caseId, TRUE);
1707 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1708 $globalContacts = array();
1710 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1711 $settings = $settingsProcessor->run();
1712 if (!empty($settings)) {
1713 $groupInfo['name'] = $settings['groupname'];
1714 if ($groupInfo['name']) {
1715 $searchParams = array('name' => $groupInfo['name']);
1717 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1719 $groupInfo['id'] = $results['id'];
1720 $groupInfo['title'] = $results['title'];
1721 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1722 $return = array('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1723 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1724 list($globalContacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1726 if ($returnOnlyCount) {
1727 return $globalContacts;
1731 foreach ($globalContacts as $idx => $contact) {
1732 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1738 return $globalContacts;
1742 * Convenience function to get both case contacts and global in one array
1744 static function getRelatedAndGlobalContacts($caseId) {
1745 $relatedContacts = self
::getRelatedContacts($caseId);
1747 $groupInfo = array();
1748 $globalContacts = self
::getGlobalContacts($groupInfo);
1750 //unset values which are not required.
1751 foreach ($globalContacts as $k => & $v) {
1752 unset($v['email_id']);
1753 unset($v['group_contact_id']);
1754 unset($v['status']);
1756 $v['role'] = $groupInfo['title'];
1758 //include multiple listings for the same contact/different roles.
1759 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1760 return $relatedGlobalContacts;
1764 * Function to get Case ActivitiesDueDates with given criteria.
1766 * @param int $caseID case id
1767 * @param array $criteriaParams given criteria
1768 * @param boolean $latestDate if set newest or oldest date is selceted.
1770 * @return returns case activities due dates
1774 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1776 $selectDate = " ca.activity_date_time";
1777 $where = $groupBy = ' ';
1784 if (CRM_Utils_Array
::value('activity_type_id', $criteriaParams)) {
1785 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1786 $where .= " AND ca.is_current_revision = 1";
1787 $groupBy .= " GROUP BY ca.activity_type_id";
1790 if (CRM_Utils_Array
::value('newest', $criteriaParams)) {
1791 $selectDate = " max(ca.activity_date_time) ";
1794 $selectDate = " min(ca.activity_date_time) ";
1798 $query = "SELECT ca.id, {$selectDate} as activity_date
1799 FROM civicrm_activity ca
1800 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1801 WHERE cc.id = %1 {$where} {$groupBy}";
1803 $params = array(1 => array($caseID, 'Integer'));
1804 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1806 while ($dao->fetch()) {
1807 $values[$dao->id
]['id'] = $dao->id
;
1808 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1815 * Function to create activities when Case or Other roles assigned/modified/deleted.
1817 * @param int $caseID case id
1818 * @param int $relationshipId relationship id
1819 * @param int $relContactId case role assignee contactId.
1821 * @return void on success creates activity and case activity
1825 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1826 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1830 $queryParam = array();
1831 if (is_array($relationshipId)) {
1832 $relationshipId = implode(',', $relationshipId);
1833 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1836 $relationshipClause = " civicrm_relationship.id = %1";
1837 $queryParam[1] = array($relationshipId, 'Positive');
1841 SELECT cc.display_name as clientName,
1842 cca.display_name as assigneeContactName,
1843 civicrm_relationship.case_id as caseId,
1844 civicrm_relationship_type.label_a_b as relation_a_b,
1845 civicrm_relationship_type.label_b_a as relation_b_a,
1846 civicrm_relationship.contact_id_b as rel_contact_id,
1847 civicrm_relationship.contact_id_a as assign_contact_id
1848 FROM civicrm_relationship_type, civicrm_relationship
1849 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1850 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1851 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1853 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1855 while ($dao->fetch()) {
1856 //to get valid assignee contact(s).
1857 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1858 $caseRelationship = $dao->relation_a_b
;
1859 $assigneContactName = $dao->clientName
;
1860 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1863 $caseRelationship = $dao->relation_b_a
;
1864 $assigneContactName = $dao->assigneeContactName
;
1865 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1869 $session = CRM_Core_Session
::singleton();
1870 $activityParams = array(
1871 'source_contact_id' => $session->get('userID'),
1872 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1873 'activity_date_time' => date('YmdHis'),
1874 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1877 //if $relContactId is passed, role is added or modified.
1878 if (!empty($relContactId)) {
1879 $activityParams['assignee_contact_id'] = $assigneContactIds;
1881 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1887 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1893 $activityParams['activity_type_id'] = $activityTypeID;
1895 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1897 //create case_activity record.
1898 $caseParams = array(
1899 'activity_id' => $activity->id
,
1900 'case_id' => $caseId,
1903 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1907 * Function to get case manger
1908 * contact which is assigned a case role of case manager.
1910 * @param int $caseType case type
1911 * @param int $caseId case id
1913 * @return array $caseManagerContact array of contact on success otherwise empty
1917 static function getCaseManagerContact($caseType, $caseId) {
1918 if (!$caseType ||
!$caseId) {
1922 $caseManagerContact = array();
1923 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1925 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1927 if (!empty($managerRoleId)) {
1928 $managerRoleQuery = "
1929 SELECT civicrm_contact.id as casemanager_id,
1930 civicrm_contact.sort_name as casemanager
1931 FROM civicrm_contact
1932 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1933 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1934 WHERE civicrm_case.id = %2";
1936 $managerRoleParams = array(
1937 1 => array($managerRoleId, 'Integer'),
1938 2 => array($caseId, 'Integer'),
1941 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1942 if ($dao->fetch()) {
1943 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1944 $caseManagerContact['casemanager'] = $dao->casemanager
;
1948 return $caseManagerContact;
1952 * Get all cases with no end dates
1954 * @return array of case and related data keyed on case id
1956 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1957 //params from ajax call.
1958 $where = array('( ca.end_date is null )');
1959 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
1960 $where[] = "( ov.label LIKE '%$caseType%' )";
1962 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
1963 $config = CRM_Core_Config
::singleton();
1964 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
1965 $where[] = "( sort_name LIKE '$search' )";
1967 if (is_array($excludeCaseIds) &&
1968 !CRM_Utils_System
::isNull($excludeCaseIds)
1970 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
1972 if ($excludeDeleted) {
1973 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
1976 //filter for permissioned cases.
1977 $filterCases = array();
1978 $doFilterCases = FALSE;
1979 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1980 $doFilterCases = TRUE;
1981 $session = CRM_Core_Session
::singleton();
1982 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1984 $whereClause = implode(' AND ', $where);
1987 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
1988 $limitClause = "LIMIT 0, $limit";
1992 SELECT c.id as contact_id,
1995 ca.subject as case_subject,
1996 ov.label as case_type,
1997 ca.start_date as start_date
1998 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
1999 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2000 INNER JOIN civicrm_option_group og ON og.name='case_type'
2001 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2002 WHERE {$whereClause}
2003 ORDER BY c.sort_name
2006 $dao = CRM_Core_DAO
::executeQuery($query);
2007 $unclosedCases = array();
2008 while ($dao->fetch()) {
2009 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2012 $unclosedCases[$dao->id
] = array(
2013 'sort_name' => $dao->sort_name
,
2014 'case_type' => $dao->case_type
,
2015 'contact_id' => $dao->contact_id
,
2016 'start_date' => $dao->start_date
,
2017 'case_subject' => $dao->case_subject
,
2022 return $unclosedCases;
2025 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2026 $whereConditions = array();
2027 if ($excludeDeleted) {
2028 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2031 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2033 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2034 static $accessibleCaseIds;
2035 if (!is_array($accessibleCaseIds)) {
2036 $session = CRM_Core_Session
::singleton();
2037 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID')));
2039 //no need of further processing.
2040 if (empty($accessibleCaseIds)) {
2043 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2047 if (!empty($whereConditions)) {
2048 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2052 SELECT count( civicrm_case.id )
2054 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2057 return CRM_Core_DAO
::singleValueQuery($query);
2061 * Retrieve cases related to particular contact.
2063 * @param int $contactId contact id
2064 * @param boolean $excludeDeleted do not include deleted cases.
2066 * @return an array of cases.
2070 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2076 $whereClause = "civicrm_case_contact.contact_id = %1";
2077 if ($excludeDeleted) {
2078 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2082 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2084 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2085 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2086 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2087 AND case_type_og.id = case_type_ov.option_group_id )
2088 WHERE {$whereClause}";
2090 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2091 while ($dao->fetch()) {
2092 $cases[$dao->id
] = array(
2093 'case_id' => $dao->id
,
2094 'case_type' => $dao->case_type
,
2095 'case_start_date' => $dao->start_date
,
2104 * Retrieve related cases for give case.
2106 * @param int $mainCaseId id of main case
2107 * @param int $contactId id of contact
2108 * @param boolean $excludeDeleted do not include deleted cases.
2110 * @return an array of related cases.
2114 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2115 //FIXME : do check for permissions.
2117 $relatedCases = array();
2118 if (!$mainCaseId ||
!$contactId) {
2119 return $relatedCases;
2122 $linkActType = array_search('Link Cases',
2123 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2125 if (!$linkActType) {
2126 return $relatedCases;
2129 $whereClause = "mainCase.id = %2";
2130 if ($excludeDeleted) {
2131 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2134 //1. first fetch related case ids.
2136 SELECT relCaseAct.case_id
2137 FROM civicrm_case mainCase
2138 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2139 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2140 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2141 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2142 WHERE $whereClause";
2144 $dao = CRM_Core_DAO
::executeQuery($query, array(
2145 1 => array($linkActType, 'Integer'),
2146 2 => array($mainCaseId, 'Integer'),
2148 $relatedCaseIds = array();
2149 while ($dao->fetch()) {
2150 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2154 // there are no related cases.
2155 if (empty($relatedCaseIds)) {
2156 return $relatedCases;
2159 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2160 if ($excludeDeleted) {
2161 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2164 //filter for permissioned cases.
2165 $filterCases = array();
2166 $doFilterCases = FALSE;
2167 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2168 $doFilterCases = TRUE;
2169 $session = CRM_Core_Session
::singleton();
2170 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2173 //2. fetch the details of related cases.
2175 SELECT relCase.id as id,
2176 case_type_ov.label as case_type,
2177 client.display_name as client_name,
2178 client.id as client_id
2179 FROM civicrm_case relCase
2180 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2181 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2182 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2183 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2184 AND case_type_og.id = case_type_ov.option_group_id )
2185 WHERE {$whereClause}";
2187 $dao = CRM_Core_DAO
::executeQuery($query);
2188 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2189 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2191 while ($dao->fetch()) {
2193 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2194 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2195 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2196 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2198 $clientView = $dao->client_name
;
2199 if ($hasViewContact) {
2200 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2203 $relatedCases[$dao->id
] = array(
2204 'case_id' => $dao->id
,
2205 'case_type' => $dao->case_type
,
2206 'client_name' => $clientView,
2207 'links' => $caseView,
2212 return $relatedCases;
2216 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2218 * @see CRM_Dedupe_Merger::cpTables()
2220 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2222 static function mergeContacts($mainContactId, $otherContactId) {
2223 self
::mergeCases($mainContactId, NULL, $otherContactId);
2227 * Function perform two task.
2228 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2229 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2231 * @param int $mainContactId contact id of main contact record.
2232 * @param int $mainCaseId case id of main case record.
2233 * @param int $otherContactId contact id of record which is going to merge.
2234 * @param int $otherCaseId case id of record which is going to merge.
2239 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2240 $otherCaseId = NULL, $changeClient = FALSE) {
2241 $moveToTrash = TRUE;
2243 $duplicateContacts = FALSE;
2244 if ($mainContactId && $otherContactId &&
2245 $mainContactId != $otherContactId
2247 $duplicateContacts = TRUE;
2250 $duplicateCases = FALSE;
2251 if ($mainCaseId && $otherCaseId &&
2252 $mainCaseId != $otherCaseId
2254 $duplicateCases = TRUE;
2257 $mainCaseIds = array();
2258 if (!$duplicateContacts && !$duplicateCases) {
2259 return $mainCaseIds;
2262 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2263 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2264 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2265 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2266 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2267 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2269 $processCaseIds = array($otherCaseId);
2270 if ($duplicateContacts && !$duplicateCases) {
2271 if ($changeClient) {
2272 $processCaseIds = array($mainCaseId);
2275 //get all case ids for other contact.
2276 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2278 if (!is_array($processCaseIds)) {
2283 $session = CRM_Core_Session
::singleton();
2284 $currentUserId = $session->get('userID');
2286 // copy all cases and connect to main contact id.
2287 foreach ($processCaseIds as $otherCaseId) {
2288 if ($duplicateContacts) {
2289 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2290 $mainCaseId = $mainCase->id
;
2295 // CRM-11662 Copy Case custom data
2296 $extends = array('case');
2297 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2299 foreach ($groupTree as $groupID => $group) {
2300 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2301 foreach ($group['fields'] as $fieldID => $field) {
2302 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2306 foreach ($table as $tableName => $tableColumns) {
2307 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2308 $tableColumns[0] = $mainCaseId;
2309 $select = 'SELECT ' . implode(', ', $tableColumns);
2310 $from = ' FROM ' . $tableName;
2311 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2312 $query = $insert . $select . $from . $where;
2313 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2319 $mainCaseIds[] = $mainCaseId;
2320 //insert record for case contact.
2321 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2322 $otherCaseContact->case_id
= $otherCaseId;
2323 $otherCaseContact->find();
2324 while ($otherCaseContact->fetch()) {
2325 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2326 $mainCaseContact->case_id
= $mainCaseId;
2327 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2328 if ($mainCaseContact->contact_id
== $otherContactId) {
2329 $mainCaseContact->contact_id
= $mainContactId;
2331 //avoid duplicate object.
2332 if (!$mainCaseContact->find(TRUE)) {
2333 $mainCaseContact->save();
2335 $mainCaseContact->free();
2337 $otherCaseContact->free();
2339 elseif (!$otherContactId) {
2340 $otherContactId = $mainContactId;
2343 if (!$mainCaseId ||
!$otherCaseId ||
2344 !$mainContactId ||
!$otherContactId
2349 // get all activities for other case.
2350 $otherCaseActivities = array();
2351 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2353 //for duplicate cases do not process singleton activities.
2354 $otherActivityIds = $singletonActivityIds = array();
2355 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2356 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2357 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2360 $otherActivityIds[] = $otherActId;
2362 if ($duplicateCases) {
2363 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2366 FROM civicrm_activity
2367 WHERE activity_type_id = $openCaseType
2368 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2369 $dao = CRM_Core_DAO
::executeQuery($sql);
2370 while ($dao->fetch()) {
2371 $singletonActivityIds[] = $dao->id
;
2377 // migrate all activities and connect to main contact.
2378 $copiedActivityIds = $activityMappingIds = array();
2379 sort($otherActivityIds);
2380 foreach ($otherActivityIds as $otherActivityId) {
2382 //for duplicate cases -
2383 //do not migrate singleton activities.
2384 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2388 //migrate activity record.
2389 $otherActivity = new CRM_Activity_DAO_Activity();
2390 $otherActivity->id
= $otherActivityId;
2391 if (!$otherActivity->find(TRUE)) {
2395 $mainActVals = array();
2396 $mainActivity = new CRM_Activity_DAO_Activity();
2397 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2398 $mainActivity->copyValues($mainActVals);
2399 $mainActivity->id
= NULL;
2400 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2401 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2405 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2409 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2412 $mainActivity->save();
2413 $mainActivityId = $mainActivity->id
;
2414 if (!$mainActivityId) {
2418 $activityMappingIds[$otherActivityId] = $mainActivityId;
2419 // insert log of all activities
2420 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2422 $otherActivity->free();
2423 $mainActivity->free();
2424 $copiedActivityIds[] = $otherActivityId;
2426 //create case activity record.
2427 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2428 $mainCaseActivity->case_id
= $mainCaseId;
2429 $mainCaseActivity->activity_id
= $mainActivityId;
2430 $mainCaseActivity->save();
2431 $mainCaseActivity->free();
2433 //migrate source activity.
2434 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2435 $otherSourceActivity->activity_id
= $otherActivityId;
2436 $otherSourceActivity->record_type_id
= $sourceID;
2437 $otherSourceActivity->find();
2438 while ($otherSourceActivity->fetch()) {
2439 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2440 $mainActivitySource->record_type_id
= $sourceID;
2441 $mainActivitySource->activity_id
= $mainActivityId;
2442 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2443 if ($mainActivitySource->contact_id
== $otherContactId) {
2444 $mainActivitySource->contact_id
= $mainContactId;
2446 //avoid duplicate object.
2447 if (!$mainActivitySource->find(TRUE)) {
2448 $mainActivitySource->save();
2450 $mainActivitySource->free();
2452 $otherSourceActivity->free();
2454 //migrate target activities.
2455 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2456 $otherTargetActivity->activity_id
= $otherActivityId;
2457 $otherTargetActivity->record_type_id
= $targetID;
2458 $otherTargetActivity->find();
2459 while ($otherTargetActivity->fetch()) {
2460 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2461 $mainActivityTarget->record_type_id
= $targetID;
2462 $mainActivityTarget->activity_id
= $mainActivityId;
2463 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2464 if ($mainActivityTarget->contact_id
== $otherContactId) {
2465 $mainActivityTarget->contact_id
= $mainContactId;
2467 //avoid duplicate object.
2468 if (!$mainActivityTarget->find(TRUE)) {
2469 $mainActivityTarget->save();
2471 $mainActivityTarget->free();
2473 $otherTargetActivity->free();
2475 //migrate assignee activities.
2476 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2477 $otherAssigneeActivity->activity_id
= $otherActivityId;
2478 $otherAssigneeActivity->record_type_id
= $assigneeID;
2479 $otherAssigneeActivity->find();
2480 while ($otherAssigneeActivity->fetch()) {
2481 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2482 $mainAssigneeActivity->activity_id
= $mainActivityId;
2483 $mainAssigneeActivity->record_type_id
= $assigneeID;
2484 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2485 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2486 $mainAssigneeActivity->contact_id
= $mainContactId;
2488 //avoid duplicate object.
2489 if (!$mainAssigneeActivity->find(TRUE)) {
2490 $mainAssigneeActivity->save();
2492 $mainAssigneeActivity->free();
2494 $otherAssigneeActivity->free();
2496 // copy custom fields and attachments
2498 'activityID' => $otherActivityId,
2499 'mainActivityId' => $mainActivityId,
2501 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2504 //copy case relationship.
2505 if ($duplicateContacts) {
2506 //migrate relationship records.
2507 $otherRelationship = new CRM_Contact_DAO_Relationship();
2508 $otherRelationship->case_id
= $otherCaseId;
2509 $otherRelationship->find();
2510 $otherRelationshipIds = array();
2511 while ($otherRelationship->fetch()) {
2512 $otherRelVals = array();
2513 $updateOtherRel = FALSE;
2514 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2516 $mainRelationship = new CRM_Contact_DAO_Relationship();
2517 $mainRelationship->copyValues($otherRelVals);
2518 $mainRelationship->id
= NULL;
2519 $mainRelationship->case_id
= $mainCaseId;
2520 if ($mainRelationship->contact_id_a
== $otherContactId) {
2521 $updateOtherRel = TRUE;
2522 $mainRelationship->contact_id_a
= $mainContactId;
2525 //case creator change only when we merge user contact.
2526 if ($mainRelationship->contact_id_b
== $otherContactId) {
2527 //do not change creator for change client.
2528 if (!$changeClient) {
2529 $updateOtherRel = TRUE;
2530 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2533 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2534 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2536 //avoid duplicate object.
2537 if (!$mainRelationship->find(TRUE)) {
2538 $mainRelationship->save();
2540 $mainRelationship->free();
2542 //get the other relationship ids to update end date.
2543 if ($updateOtherRel) {
2544 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2547 $otherRelationship->free();
2549 //update other relationships end dates
2550 if (!empty($otherRelationshipIds)) {
2551 $sql = 'UPDATE civicrm_relationship
2552 SET end_date = CURDATE()
2553 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2554 CRM_Core_DAO
::executeQuery($sql);
2558 //move other case to trash.
2559 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2564 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2565 if ($changeClient) {
2566 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2567 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2569 $mergeActType = array_search('Reassigned Case', $activityTypes);
2570 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2573 2 => $otherContactDisplayName,
2574 3 => $mainContactDisplayName,
2579 elseif ($duplicateContacts) {
2580 $mergeActType = array_search('Merge Case', $activityTypes);
2581 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2584 2 => $otherContactId,
2585 3 => $mainContactId,
2591 $mergeActType = array_search('Merge Case', $activityTypes);
2592 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2593 if (!empty($copiedActivityIds)) {
2595 SELECT id, subject, activity_date_time, activity_type_id
2596 FROM civicrm_activity
2597 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2598 $dao = CRM_Core_DAO
::executeQuery($sql);
2599 while ($dao->fetch()) {
2600 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2601 if ($dao->subject
) {
2602 $mergeActSubjectDetails .= " :: {$dao->subject}";
2604 $mergeActSubjectDetails .= "<br />";
2609 //create merge activity record.
2610 $activityParams = array(
2611 'subject' => $mergeActSubject,
2612 'details' => $mergeActSubjectDetails,
2613 'status_id' => array_search('Completed', $activityStatuses),
2614 'activity_type_id' => $mergeActType,
2615 'source_contact_id' => $mainContactId,
2616 'activity_date_time' => date('YmdHis'),
2619 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2620 $mergeActivityId = $mergeActivity->id
;
2621 if (!$mergeActivityId) {
2624 $mergeActivity->free();
2626 //connect merge activity to case.
2627 $mergeCaseAct = array(
2628 'case_id' => $mainCaseId,
2629 'activity_id' => $mergeActivityId,
2632 self
::processCaseActivity($mergeCaseAct);
2634 return $mainCaseIds;
2638 * Validate contact permission for
2639 * edit/view on activity record and build links.
2641 * @param array $tplParams params to be sent to template for sending email.
2642 * @param array $activityParams info of the activity.
2647 static function buildPermissionLinks(&$tplParams, $activityParams) {
2648 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2649 'activity_type_id', 'id'
2652 if (CRM_Utils_Array
::value('isCaseActivity', $tplParams)) {
2653 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2654 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2657 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2658 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2661 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2662 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2666 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2667 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2670 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2671 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2677 * Validate contact permission for
2678 * given operation on activity record.
2680 * @param int $activityId activity record id.
2681 * @param string $operation user operation.
2682 * @param int $actTypeId activity type id.
2683 * @param int $contactId contact id/if not pass consider logged in
2684 * @param boolean $checkComponent do we need to check component enabled.
2686 * @return boolean $allow true/false
2689 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2691 if (!$actTypeId && $activityId) {
2692 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2695 if (!$activityId ||
!$operation ||
!$actTypeId) {
2699 //do check for civicase component enabled.
2700 if ($checkComponent) {
2701 static $componentEnabled;
2702 if (!isset($componentEnabled)) {
2703 $config = CRM_Core_Config
::singleton();
2704 $componentEnabled = FALSE;
2705 if (in_array('CiviCase', $config->enableComponents
)) {
2706 $componentEnabled = TRUE;
2709 if (!$componentEnabled) {
2714 //do check for cases.
2715 $caseActOperations = array(
2722 if (in_array($operation, $caseActOperations)) {
2723 static $unclosedCases;
2724 if (!is_array($unclosedCases)) {
2725 $unclosedCases = self
::getUnclosedCases();
2727 if ($operation == 'File On Case') {
2728 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2731 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2735 $actionOperations = array('view', 'edit', 'delete');
2736 if (in_array($operation, $actionOperations)) {
2738 //do cache when user has non/supper permission.
2739 static $allowOperations;
2741 if (!is_array($allowOperations) ||
2742 !array_key_exists($operation, $allowOperations)
2746 $session = CRM_Core_Session
::singleton();
2747 $contactId = $session->get('userID');
2750 //check for permissions.
2751 $permissions = array(
2753 'access my cases and activities',
2754 'access all cases and activities',
2757 'access my cases and activities',
2758 'access all cases and activities',
2760 'delete' => array('delete activities'),
2763 //check for core permission.
2764 $hasPermissions = array();
2765 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2766 if (is_array($checkPermissions)) {
2767 foreach ($checkPermissions as $per) {
2768 if (CRM_Core_Permission
::check($per)) {
2769 $hasPermissions[$operation][] = $per;
2775 if (!empty($hasPermissions)) {
2776 //need to check activity object specific.
2777 if (in_array($operation, array(
2782 //do we have supper permission.
2783 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2784 $allowOperations[$operation] = $allow = TRUE;
2787 //user has only access to my cases and activity.
2788 //here object specific permmions come in picture.
2790 //edit - contact must be source or assignee
2791 //view - contact must be source/assignee/target
2792 $isTarget = $isAssignee = $isSource = FALSE;
2793 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2794 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2795 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2796 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2798 $target = new CRM_Activity_DAO_ActivityContact();
2799 $target->record_type_id
= $targetID;
2800 $target->activity_id
= $activityId;
2801 $target->contact_id
= $contactId;
2802 if ($target->find(TRUE)) {
2806 $assignee = new CRM_Activity_DAO_ActivityContact();
2807 $assignee->activity_id
= $activityId;
2808 $assignee->record_type_id
= $assigneeID;
2809 $assignee->contact_id
= $contactId;
2810 if ($assignee->find(TRUE)) {
2814 $source = new CRM_Activity_DAO_ActivityContact();
2815 $source->activity_id
= $activityId;
2816 $source->record_type_id
= $sourceID;
2817 $source->contact_id
= $contactId;
2818 if ($source->find(TRUE)) {
2822 if ($operation == 'edit') {
2823 if ($isAssignee ||
$isSource) {
2827 if ($operation == 'view') {
2828 if ($isTarget ||
$isAssignee ||
$isSource) {
2834 elseif (is_array($hasPermissions[$operation])) {
2835 $allowOperations[$operation] = $allow = TRUE;
2839 //contact do not have permission.
2840 $allowOperations[$operation] = FALSE;
2845 //here contact might have supper/non permission.
2846 $allow = $allowOperations[$operation];
2850 //do further only when operation is granted.
2852 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2854 //get the activity type name.
2855 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2857 //do not allow multiple copy / edit action.
2858 $singletonNames = array(
2868 //do not allow to delete these activities, CRM-4543
2869 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2871 //allow edit operation.
2872 $allowEditNames = array('Open Case');
2874 // do not allow File on Case
2875 $doNotFileNames = array(
2878 'Change Case Status',
2879 'Change Case Start Date',
2886 if (in_array($actTypeName, $singletonNames)) {
2888 if ($operation == 'File On Case') {
2889 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2891 if (in_array($operation, $actionOperations)) {
2893 if ($operation == 'edit') {
2894 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2896 elseif ($operation == 'delete') {
2897 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2901 if ($allow && ($operation == 'delete') &&
2902 in_array($actTypeName, $doNotDeleteNames)
2907 if ($allow && ($operation == 'File On Case') &&
2908 in_array($actTypeName, $doNotFileNames)
2913 //check settings file for masking actions
2914 //on the basis the activity types
2915 //hide Edit link if activity type is NOT editable
2916 //(special case activities).CRM-5871
2917 if ($allow && in_array($operation, $actionOperations)) {
2918 static $actionFilter = array();
2919 if (!array_key_exists($operation, $actionFilter)) {
2920 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2921 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2923 if (array_key_exists($operation, $actionFilter[$operation]) &&
2924 in_array($actTypeId, $actionFilter[$operation][$operation])
2935 * since we drop 'access CiviCase', allow access
2936 * if user has 'access my cases and activities'
2937 * or 'access all cases and activities'
2939 static function accessCiviCase() {
2940 static $componentEnabled;
2941 if (!isset($componentEnabled)) {
2942 $componentEnabled = FALSE;
2943 $config = CRM_Core_Config
::singleton();
2944 if (in_array('CiviCase', $config->enableComponents
)) {
2945 $componentEnabled = TRUE;
2948 if (!$componentEnabled) {
2952 if (CRM_Core_Permission
::check('access my cases and activities') ||
2953 CRM_Core_Permission
::check('access all cases and activities')
2962 * Function to check whether activity is a case Activity
2964 * @param int $activityID activity id
2966 * @return boolean $isCaseActivity true/false
2968 static function isCaseActivity($activityID) {
2969 $isCaseActivity = FALSE;
2971 $params = array(1 => array($activityID, 'Integer'));
2972 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2973 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2974 $isCaseActivity = TRUE;
2978 return $isCaseActivity;
2982 * Function to get all the case type ids currently in use
2985 * @return array $caseTypeIds
2987 static function getUsedCaseType() {
2988 static $caseTypeIds;
2990 if (!is_array($caseTypeIds)) {
2991 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2993 $dao = CRM_Core_DAO
::executeQuery($query);
2994 $caseTypeIds = array();
2995 while ($dao->fetch()) {
2996 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2999 $caseTypeIds[] = $typeId[1];
3003 return $caseTypeIds;
3007 * Function to get all the case status ids currently in use
3010 * @return array $caseStatusIds
3012 static function getUsedCaseStatuses() {
3013 static $caseStatusIds;
3015 if (!is_array($caseStatusIds)) {
3016 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3018 $dao = CRM_Core_DAO
::executeQuery($query);
3019 $caseStatusIds = array();
3020 while ($dao->fetch()) {
3021 $caseStatusIds[] = $dao->status_id
;
3025 return $caseStatusIds;
3029 * Function to get all the encounter medium ids currently in use
3032 static function getUsedEncounterMediums() {
3035 if (!is_array($mediumIds)) {
3036 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3038 $dao = CRM_Core_DAO
::executeQuery($query);
3039 $mediumIds = array();
3040 while ($dao->fetch()) {
3041 $mediumIds[] = $dao->medium_id
;
3049 * Function to check case configuration.
3051 * @return array $configured
3053 static function isCaseConfigured($contactId = NULL) {
3054 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3056 //lets check for case configured.
3057 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3058 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3059 if (!$configured['configured']) {
3060 //do check for case type and case status.
3061 $caseTypes = CRM_Case_PseudoConstant
::caseType('label', FALSE);
3062 if (!empty($caseTypes)) {
3063 $configured['configured'] = TRUE;
3064 if (!$configured['configured']) {
3065 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3066 if (!empty($caseStatuses)) {
3067 $configured['configured'] = TRUE;
3072 if ($configured['configured']) {
3073 //do check for active case type and case status.
3074 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3075 if (!empty($caseTypes)) {
3076 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3077 if (!empty($caseStatuses)) {
3078 $configured['allowToAddNewCase'] = TRUE;
3082 //do we need to redirect user to case admin.
3083 if (!$configured['allowToAddNewCase'] && $contactId) {
3084 //check for current contact case count.
3085 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3086 //redirect user to case admin page.
3087 if (!$currentContatCasesCount) {
3088 $configured['redirectToCaseAdmin'] = TRUE;
3097 * Used during case component enablement and during ugprade
3099 static function createCaseViews() {
3100 $dao = new CRM_Core_DAO();
3102 $sql = self
::createCaseViewsQuery('upcoming');
3103 CRM_Core_Error
::ignoreException();
3105 CRM_Core_Error
::setCallback();
3106 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3110 // Above error doesn't get caught?
3111 CRM_Core_Error
::ignoreException();
3112 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3113 CRM_Core_Error
::setCallback();
3114 if (is_null($doublecheck)) {
3118 $sql = self
::createCaseViewsQuery('recent');
3119 CRM_Core_Error
::ignoreException();
3121 CRM_Core_Error
::setCallback();
3122 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3126 // Above error doesn't get caught?
3127 CRM_Core_Error
::ignoreException();
3128 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3129 CRM_Core_Error
::setCallback();
3130 if (is_null($doublecheck)) {
3138 * helper function, also used by the upgrade in case of error
3140 static function createCaseViewsQuery($section = 'upcoming') {
3142 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3145 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3146 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3147 FROM civicrm_case_activity ca
3148 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3149 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3150 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3154 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3155 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3156 FROM civicrm_case_activity ca
3157 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3158 WHERE a.activity_date_time <= NOW()
3159 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3160 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3167 * Function to add/copy relationships, when new client is added for a case
3169 * @param int $caseId case id
3170 * @param int $contactId contact id / new client id
3174 static function addCaseRelationships($caseId, $contactId) {
3175 // get the case role / relationships for the case
3176 $caseRelationships = new CRM_Contact_DAO_Relationship();
3177 $caseRelationships->case_id
= $caseId;
3178 $caseRelationships->find();
3179 $relationshipTypes = array();
3181 // make sure we don't add duplicate relationships of same relationship type.
3182 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3184 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3186 // add relationship for new client.
3187 $newRelationship = new CRM_Contact_DAO_Relationship();
3188 $newRelationship->copyValues($values);
3189 $newRelationship->id
= NULL;
3190 $newRelationship->case_id
= $caseId;
3191 $newRelationship->contact_id_a
= $contactId;
3192 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3193 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3195 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3196 if (!$newRelationship->find(TRUE)) {
3197 $newRelationship->save();
3199 $newRelationship->free();
3201 // store relationship type of newly created relationship
3202 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3207 * Function to get the list of clients for a case
3209 * @param int $caseId
3211 * @return array $clients associated array with client ids
3214 static function getCaseClients($caseId) {
3216 $caseContact = new CRM_Case_DAO_CaseContact();
3217 $caseContact->case_id
= $caseId;
3218 $caseContact->find();
3220 while ($caseContact->fetch()) {
3221 $clients[] = $caseContact->contact_id
;
3228 * Get options for a given case field.
3229 * @see CRM_Core_DAO::buildOptions
3231 * @param String $fieldName
3232 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3233 * @param Array $props: whatever is known about this dao object
3235 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3236 $className = __CLASS__
;
3238 switch ($fieldName) {
3239 // This field is not part of this object but the api supports it
3241 $className = 'CRM_Activity_BAO_Activity';
3244 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);