3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 $orderBy = " ORDER BY {$sortname} {$sortorder}";
1077 if ($sortname != 'display_date') {
1078 $orderBy .= ', display_date DESC';
1082 $page = CRM_Utils_Array
::value('page', $params);
1083 $rp = CRM_Utils_Array
::value('rp', $params);
1092 $start = (($page - 1) * $rp);
1093 $query = $select . $from . $where . $groupBy . $orderBy;
1095 $params = array(1 => array($caseID, 'Integer'));
1096 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1097 $params['total'] = $dao->N
;
1099 //FIXME: need to optimize/cache these queries
1100 $limit = " LIMIT $start, $rp";
1104 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1107 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1108 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1109 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1111 $url = CRM_Utils_System
::url("civicrm/case/activity",
1112 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1116 if ($context == 'fulltext') {
1117 $contextUrl = "&context={$context}";
1119 $editUrl = "{$url}&action=update{$contextUrl}";
1120 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1121 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1122 $viewTitle = ts('View this activity.');
1123 $statusTitle = ts('Edit status');
1125 $emailActivityTypeIDs = array(
1126 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1130 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1136 $emailActivityTypeIDs = array(
1137 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1141 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1147 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1149 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1150 $compStatusValues = array();
1151 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1152 foreach ($compStatusNames as $name) {
1153 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1155 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1156 "reset=1&cid=", FALSE, NULL, FALSE
1158 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1159 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1162 $session = CRM_Core_Session
::singleton();
1163 $userID = $session->get('userID');
1166 while ($dao->fetch()) {
1168 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1169 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1170 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1172 //do not have sufficient permission
1173 //to access given case activity record.
1174 if (!$allowView && !$allowEdit && !$allowDelete) {
1178 $values[$dao->id
]['id'] = $dao->id
;
1179 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1181 $reporterName = $dao->reporter
;
1182 if ($hasViewContact) {
1183 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1185 $values[$dao->id
]['reporter'] = $reporterName;
1186 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1187 $targetContactUrls = $withContacts = array();
1188 foreach ($targetNames as $targetId => $targetName) {
1189 if (!in_array($targetId, $clientIds)) {
1190 $withContacts[$targetId] = $targetName;
1193 foreach ($withContacts as $cid => $name) {
1194 if ($hasViewContact) {
1195 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1197 $targetContactUrls[] = $name;
1199 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1201 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1202 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1204 //check for view activity.
1205 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1207 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id
. ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1209 $values[$dao->id
]['subject'] = $subject;
1211 // add activity assignee to activity selector. CRM-4485.
1212 if (isset($dao->assignee
)) {
1213 if ($dao->ismultiple
== 1) {
1214 if ($dao->reporter_id
!= $dao->assignee_id
) {
1215 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1217 $values[$dao->id
]['assignee'] = $dao->assignee
;
1220 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1224 $additionalUrl = "&id={$dao->id}";
1225 if (!$dao->deleted
) {
1226 //hide edit link of activity type email.CRM-4530.
1227 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1228 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1230 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1237 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1240 elseif (!$caseDeleted) {
1241 $url = '<a href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1242 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1245 //check for operations.
1246 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1247 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1249 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1250 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1252 // if there are file attachments we will return how many and, if only one, add a link to it
1253 if (!empty($dao->attachment_ids
)) {
1254 $attachmentIDs = explode(',', $dao->attachment_ids
);
1255 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1256 if ($values[$dao->id
]['no_attachments'] == 1) {
1257 // if there is only one it's easy to do a link - otherwise just flag it
1258 $attachmentViewUrl = CRM_Utils_System
::url(
1260 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1265 $url .= " | " . "<a href=$attachmentViewUrl >" . ts('View Attachment') . '</a> ';
1270 $values[$dao->id
]['links'] = $url;
1271 $values[$dao->id
]['class'] = "";
1273 if (!empty($dao->priority
)) {
1274 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1275 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1277 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1278 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1282 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1283 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1286 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1287 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1290 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1295 $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>';
1304 * Function to get Case Related Contacts
1306 * @param int $caseID case id
1307 * @param boolean $skipDetails if true include details of contacts
1309 * @return returns $searchRows array of returnproperties
1313 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1315 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1316 FROM civicrm_relationship cr
1317 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1318 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1319 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1320 WHERE cr.case_id = %1 AND ce.is_primary= 1
1323 $params = array(1 => array($caseID, 'Integer'));
1324 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1326 while ($dao->fetch()) {
1328 $values[$dao->id
] = 1;
1332 'contact_id' => $dao->id
,
1333 'display_name' => $dao->name
,
1334 'sort_name' => $dao->sort_name
,
1335 'role' => $dao->role
,
1336 'email' => $dao->email
,
1346 * Function that sends e-mail copy of activity
1348 * @param int $activityId activity Id
1349 * @param array $contacts array of related contact
1354 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1359 $tplParams = $activityInfo = array();
1360 //if its a case activity
1362 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1363 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1364 if (CRM_Utils_Array
::value($activityTypeId, $nonCaseActivityTypes)) {
1365 $anyActivity = TRUE;
1368 $anyActivity = FALSE;
1370 $tplParams['isCaseActivity'] = 1;
1371 $tplParams['client_id'] = $clientId;
1374 $anyActivity = TRUE;
1377 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1378 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1380 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1382 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1384 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1386 $tplParams['activity'] = $activityInfo;
1387 foreach ($tplParams['activity']['fields'] as $k => $val) {
1388 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1389 $activitySubject = $val['value'];
1393 $session = CRM_Core_Session
::singleton();
1394 // CRM-8926 If user is not logged in, use the activity creator as userID
1395 if (!($userID = $session->get('userID'))) {
1396 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1399 //also create activities simultaneously of this copy.
1400 $activityParams = array();
1402 $activityParams['source_record_id'] = $activityId;
1403 $activityParams['source_contact_id'] = $userID;
1404 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1405 $activityParams['activity_date_time'] = date('YmdHis');
1406 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1407 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1408 $activityParams['case_id'] = $caseId;
1409 $activityParams['is_auto'] = 0;
1410 $activityParams['target_id'] = $clientId;
1412 $tplParams['activitySubject'] = $activitySubject;
1414 // if it’s a case activity, add hashed id to the template (CRM-5916)
1416 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1420 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1422 $receiptFrom = "$name <$address>";
1424 $recordedActivityParams = array();
1426 foreach ($contacts as $mail => $info) {
1427 $tplParams['contact'] = $info;
1428 self
::buildPermissionLinks($tplParams, $activityParams);
1430 $displayName = CRM_Utils_Array
::value('display_name', $info);
1432 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplates
::sendTemplate(
1434 'groupName' => 'msg_tpl_workflow_case',
1435 'valueName' => 'case_activity',
1436 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1437 'tplParams' => $tplParams,
1438 'from' => $receiptFrom,
1439 'toName' => $displayName,
1441 'attachments' => $attachments,
1445 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1446 $activityParams['details'] = $message;
1448 if (!empty($result[$info['contact_id']])) {
1450 * Really only need to record one activity with all the targets combined.
1451 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1452 * but it's always the same content at the moment.
1454 if (empty($recordedActivityParams)) {
1455 $recordedActivityParams = $activityParams;
1458 $recordedActivityParams['subject'] .= "; $displayName";
1460 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1463 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1467 if (!empty($recordedActivityParams)) {
1468 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1470 //create case_activity record if its case activity.
1472 $caseParams = array(
1473 'activity_id' => $activity->id
,
1474 'case_id' => $caseId,
1476 self
::processCaseActivity($caseParams);
1484 * Retrieve count of activities having a particular type, and
1485 * associated with a particular case.
1487 * @param int $caseId ID of the case
1488 * @param int $activityTypeId ID of the activity type
1495 static function getCaseActivityCount($caseId, $activityTypeId) {
1496 $queryParam = array(
1497 1 => array($caseId, 'Integer'),
1498 2 => array($activityTypeId, 'Integer'),
1500 $query = "SELECT count(ca.id) as countact
1501 FROM civicrm_activity ca
1502 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1503 WHERE ca.activity_type_id = %2
1504 AND cca.case_id = %1
1505 AND ca.is_deleted = 0";
1507 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1508 if ($dao->fetch()) {
1509 return $dao->countact
;
1516 * Create an activity for a case via email
1518 * @param int $file email sent
1520 * @return $activity object of newly creted activity via email
1525 static function recordActivityViaEmail($file) {
1526 if (!file_exists($file) ||
1529 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1534 $result = CRM_Utils_Mail_Incoming
::parse($file);
1535 if ($result['is_error']) {
1539 foreach ($result['to'] as $to) {
1542 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1543 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1545 if ($replacement !== $to['email']) {
1546 $caseId = $replacement;
1547 //if caseId is invalid, return as error file
1548 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1549 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1558 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1559 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1560 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1562 if (CRM_Utils_Array
::value($result['from']['id'], $contactDetails)) {
1564 $params['subject'] = $result['subject'];
1565 $params['activity_date_time'] = $result['date'];
1566 $params['details'] = $result['body'];
1567 $params['source_contact_id'] = $result['from']['id'];
1568 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1573 $details = CRM_Case_PseudoConstant
::caseActivityType();
1575 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1576 $result['body'], $matches
1579 if (!empty($matches) && isset($matches[1])) {
1580 $activityType = trim($matches[1]);
1581 if (isset($details[$activityType])) {
1582 $params['activity_type_id'] = $details[$activityType]['id'];
1585 if (!isset($params['activity_type_id'])) {
1586 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1590 $activity = CRM_Activity_BAO_Activity
::create($params);
1592 $caseParams = array(
1593 'activity_id' => $activity->id
,
1594 'case_id' => $caseId,
1596 self
::processCaseActivity($caseParams);
1599 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1600 array(1 => $result['from']['email'])
1607 * Function to retrieve the scheduled activity type and date
1609 * @param array $cases Array of contact and case id
1611 * @return array $activityInfo Array of scheduled activity type and date
1617 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1618 $session = CRM_Core_Session
::singleton();
1619 $userID = $session->get('userID');
1621 $caseID = implode(',', $cases['case_id']);
1622 $contactID = implode(',', $cases['contact_id']);
1625 AND civicrm_case_contact.contact_id IN( {$contactID} )
1626 AND civicrm_case.id IN( {$caseID})
1627 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1629 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1631 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1633 $activityInfo = array();
1634 while ($res->fetch()) {
1635 if ($type == 'upcoming') {
1636 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1637 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1640 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1641 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1645 return $activityInfo;
1649 * combine all the exportable fields from the lower levels object
1651 * @return array array of exportable Fields
1655 static function &exportableFields() {
1656 if (!self
::$_exportableFields) {
1657 if (!self
::$_exportableFields) {
1658 self
::$_exportableFields = array();
1661 $fields = CRM_Case_DAO_Case
::export();
1662 $fields['case_role'] = array('title' => ts('Role in Case'));
1663 $fields['case_type'] = array(
1664 'title' => ts('Case Type'),
1665 'name' => 'case_type',
1667 $fields['case_status'] = array(
1668 'title' => ts('Case Status'),
1669 'name' => 'case_status',
1672 self
::$_exportableFields = $fields;
1674 return self
::$_exportableFields;
1678 * Restore the record that are associated with this case
1680 * @param int $caseId id of the case to restore
1682 * @return true if success.
1686 static function restoreCase($caseId) {
1687 //restore activities
1688 $activities = self
::getCaseActivityDates($caseId);
1690 foreach ($activities as $value) {
1691 CRM_Activity_BAO_Activity
::restoreActivity($value);
1695 $case = new CRM_Case_DAO_Case();
1696 $case->id
= $caseId;
1697 $case->is_deleted
= 0;
1700 //CRM-7364, enable relationships
1701 self
::enableDisableCaseRelationships($caseId, TRUE);
1705 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1706 $globalContacts = array();
1708 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1709 $settings = $settingsProcessor->run();
1710 if (!empty($settings)) {
1711 $groupInfo['name'] = $settings['groupname'];
1712 if ($groupInfo['name']) {
1713 $searchParams = array('name' => $groupInfo['name']);
1715 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1717 $groupInfo['id'] = $results['id'];
1718 $groupInfo['title'] = $results['title'];
1719 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1720 $return = array('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1721 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1722 list($globalContacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1724 if ($returnOnlyCount) {
1725 return $globalContacts;
1729 foreach ($globalContacts as $idx => $contact) {
1730 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1736 return $globalContacts;
1740 * Convenience function to get both case contacts and global in one array
1742 static function getRelatedAndGlobalContacts($caseId) {
1743 $relatedContacts = self
::getRelatedContacts($caseId);
1745 $groupInfo = array();
1746 $globalContacts = self
::getGlobalContacts($groupInfo);
1748 //unset values which are not required.
1749 foreach ($globalContacts as $k => & $v) {
1750 unset($v['email_id']);
1751 unset($v['group_contact_id']);
1752 unset($v['status']);
1754 $v['role'] = $groupInfo['title'];
1756 //include multiple listings for the same contact/different roles.
1757 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1758 return $relatedGlobalContacts;
1762 * Function to get Case ActivitiesDueDates with given criteria.
1764 * @param int $caseID case id
1765 * @param array $criteriaParams given criteria
1766 * @param boolean $latestDate if set newest or oldest date is selceted.
1768 * @return returns case activities due dates
1772 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1774 $selectDate = " ca.activity_date_time";
1775 $where = $groupBy = ' ';
1782 if (CRM_Utils_Array
::value('activity_type_id', $criteriaParams)) {
1783 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1784 $where .= " AND ca.is_current_revision = 1";
1785 $groupBy .= " GROUP BY ca.activity_type_id";
1788 if (CRM_Utils_Array
::value('newest', $criteriaParams)) {
1789 $selectDate = " max(ca.activity_date_time) ";
1792 $selectDate = " min(ca.activity_date_time) ";
1796 $query = "SELECT ca.id, {$selectDate} as activity_date
1797 FROM civicrm_activity ca
1798 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1799 WHERE cc.id = %1 {$where} {$groupBy}";
1801 $params = array(1 => array($caseID, 'Integer'));
1802 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1804 while ($dao->fetch()) {
1805 $values[$dao->id
]['id'] = $dao->id
;
1806 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1813 * Function to create activities when Case or Other roles assigned/modified/deleted.
1815 * @param int $caseID case id
1816 * @param int $relationshipId relationship id
1817 * @param int $relContactId case role assignee contactId.
1819 * @return void on success creates activity and case activity
1823 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1824 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1828 $queryParam = array();
1829 if (is_array($relationshipId)) {
1830 $relationshipId = implode(',', $relationshipId);
1831 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1834 $relationshipClause = " civicrm_relationship.id = %1";
1835 $queryParam[1] = array($relationshipId, 'Positive');
1839 SELECT cc.display_name as clientName,
1840 cca.display_name as assigneeContactName,
1841 civicrm_relationship.case_id as caseId,
1842 civicrm_relationship_type.label_a_b as relation_a_b,
1843 civicrm_relationship_type.label_b_a as relation_b_a,
1844 civicrm_relationship.contact_id_b as rel_contact_id,
1845 civicrm_relationship.contact_id_a as assign_contact_id
1846 FROM civicrm_relationship_type, civicrm_relationship
1847 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1848 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1849 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1851 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1853 while ($dao->fetch()) {
1854 //to get valid assignee contact(s).
1855 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1856 $caseRelationship = $dao->relation_a_b
;
1857 $assigneContactName = $dao->clientName
;
1858 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1861 $caseRelationship = $dao->relation_b_a
;
1862 $assigneContactName = $dao->assigneeContactName
;
1863 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1867 $session = CRM_Core_Session
::singleton();
1868 $activityParams = array(
1869 'source_contact_id' => $session->get('userID'),
1870 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1871 'activity_date_time' => date('YmdHis'),
1872 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1875 //if $relContactId is passed, role is added or modified.
1876 if (!empty($relContactId)) {
1877 $activityParams['assignee_contact_id'] = $assigneContactIds;
1879 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1885 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1891 $activityParams['activity_type_id'] = $activityTypeID;
1893 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1895 //create case_activity record.
1896 $caseParams = array(
1897 'activity_id' => $activity->id
,
1898 'case_id' => $caseId,
1901 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1905 * Function to get case manger
1906 * contact which is assigned a case role of case manager.
1908 * @param int $caseType case type
1909 * @param int $caseId case id
1911 * @return array $caseManagerContact array of contact on success otherwise empty
1915 static function getCaseManagerContact($caseType, $caseId) {
1916 if (!$caseType ||
!$caseId) {
1920 $caseManagerContact = array();
1921 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1923 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1925 if (!empty($managerRoleId)) {
1926 $managerRoleQuery = "
1927 SELECT civicrm_contact.id as casemanager_id,
1928 civicrm_contact.sort_name as casemanager
1929 FROM civicrm_contact
1930 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1931 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1932 WHERE civicrm_case.id = %2";
1934 $managerRoleParams = array(
1935 1 => array($managerRoleId, 'Integer'),
1936 2 => array($caseId, 'Integer'),
1939 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1940 if ($dao->fetch()) {
1941 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1942 $caseManagerContact['casemanager'] = $dao->casemanager
;
1946 return $caseManagerContact;
1950 * Get all cases with no end dates
1952 * @return array of case and related data keyed on case id
1954 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1955 //params from ajax call.
1956 $where = array('( ca.end_date is null )');
1957 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
1958 $where[] = "( ov.label LIKE '%$caseType%' )";
1960 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
1961 $config = CRM_Core_Config
::singleton();
1962 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
1963 $where[] = "( sort_name LIKE '$search' )";
1965 if (is_array($excludeCaseIds) &&
1966 !CRM_Utils_System
::isNull($excludeCaseIds)
1968 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
1970 if ($excludeDeleted) {
1971 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
1974 //filter for permissioned cases.
1975 $filterCases = array();
1976 $doFilterCases = FALSE;
1977 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1978 $doFilterCases = TRUE;
1979 $session = CRM_Core_Session
::singleton();
1980 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1982 $whereClause = implode(' AND ', $where);
1985 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
1986 $limitClause = "LIMIT 0, $limit";
1990 SELECT c.id as contact_id,
1993 ca.subject as case_subject,
1994 ov.label as case_type,
1995 ca.start_date as start_date
1996 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
1997 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
1998 INNER JOIN civicrm_option_group og ON og.name='case_type'
1999 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2000 WHERE {$whereClause}
2001 ORDER BY c.sort_name
2004 $dao = CRM_Core_DAO
::executeQuery($query);
2005 $unclosedCases = array();
2006 while ($dao->fetch()) {
2007 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2010 $unclosedCases[$dao->id
] = array(
2011 'sort_name' => $dao->sort_name
,
2012 'case_type' => $dao->case_type
,
2013 'contact_id' => $dao->contact_id
,
2014 'start_date' => $dao->start_date
,
2015 'case_subject' => $dao->case_subject
,
2020 return $unclosedCases;
2023 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2024 $whereConditions = array();
2025 if ($excludeDeleted) {
2026 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2029 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2031 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2032 static $accessibleCaseIds;
2033 if (!is_array($accessibleCaseIds)) {
2034 $session = CRM_Core_Session
::singleton();
2035 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID')));
2037 //no need of further processing.
2038 if (empty($accessibleCaseIds)) {
2041 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2045 if (!empty($whereConditions)) {
2046 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2050 SELECT count( civicrm_case.id )
2052 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2055 return CRM_Core_DAO
::singleValueQuery($query);
2059 * Retrieve cases related to particular contact.
2061 * @param int $contactId contact id
2062 * @param boolean $excludeDeleted do not include deleted cases.
2064 * @return an array of cases.
2068 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2074 $whereClause = "civicrm_case_contact.contact_id = %1";
2075 if ($excludeDeleted) {
2076 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2080 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2082 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2083 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2084 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2085 AND case_type_og.id = case_type_ov.option_group_id )
2086 WHERE {$whereClause}";
2088 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2089 while ($dao->fetch()) {
2090 $cases[$dao->id
] = array(
2091 'case_id' => $dao->id
,
2092 'case_type' => $dao->case_type
,
2093 'case_start_date' => $dao->start_date
,
2102 * Retrieve related cases for give case.
2104 * @param int $mainCaseId id of main case
2105 * @param int $contactId id of contact
2106 * @param boolean $excludeDeleted do not include deleted cases.
2108 * @return an array of related cases.
2112 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2113 //FIXME : do check for permissions.
2115 $relatedCases = array();
2116 if (!$mainCaseId ||
!$contactId) {
2117 return $relatedCases;
2120 $linkActType = array_search('Link Cases',
2121 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2123 if (!$linkActType) {
2124 return $relatedCases;
2127 $whereClause = "mainCase.id = %2";
2128 if ($excludeDeleted) {
2129 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2132 //1. first fetch related case ids.
2134 SELECT relCaseAct.case_id
2135 FROM civicrm_case mainCase
2136 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2137 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2138 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2139 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2140 WHERE $whereClause";
2142 $dao = CRM_Core_DAO
::executeQuery($query, array(
2143 1 => array($linkActType, 'Integer'),
2144 2 => array($mainCaseId, 'Integer'),
2146 $relatedCaseIds = array();
2147 while ($dao->fetch()) {
2148 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2152 // there are no related cases.
2153 if (empty($relatedCaseIds)) {
2154 return $relatedCases;
2157 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2158 if ($excludeDeleted) {
2159 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2162 //filter for permissioned cases.
2163 $filterCases = array();
2164 $doFilterCases = FALSE;
2165 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2166 $doFilterCases = TRUE;
2167 $session = CRM_Core_Session
::singleton();
2168 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2171 //2. fetch the details of related cases.
2173 SELECT relCase.id as id,
2174 case_type_ov.label as case_type,
2175 client.display_name as client_name,
2176 client.id as client_id
2177 FROM civicrm_case relCase
2178 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2179 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2180 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2181 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2182 AND case_type_og.id = case_type_ov.option_group_id )
2183 WHERE {$whereClause}";
2185 $dao = CRM_Core_DAO
::executeQuery($query);
2186 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2187 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2189 while ($dao->fetch()) {
2191 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2192 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2193 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2194 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2196 $clientView = $dao->client_name
;
2197 if ($hasViewContact) {
2198 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2201 $relatedCases[$dao->id
] = array(
2202 'case_id' => $dao->id
,
2203 'case_type' => $dao->case_type
,
2204 'client_name' => $clientView,
2205 'links' => $caseView,
2210 return $relatedCases;
2214 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2216 * @see CRM_Dedupe_Merger::cpTables()
2218 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2220 static function mergeContacts($mainContactId, $otherContactId) {
2221 self
::mergeCases($mainContactId, NULL, $otherContactId);
2225 * Function perform two task.
2226 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2227 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2229 * @param int $mainContactId contact id of main contact record.
2230 * @param int $mainCaseId case id of main case record.
2231 * @param int $otherContactId contact id of record which is going to merge.
2232 * @param int $otherCaseId case id of record which is going to merge.
2237 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2238 $otherCaseId = NULL, $changeClient = FALSE) {
2239 $moveToTrash = TRUE;
2241 $duplicateContacts = FALSE;
2242 if ($mainContactId && $otherContactId &&
2243 $mainContactId != $otherContactId
2245 $duplicateContacts = TRUE;
2248 $duplicateCases = FALSE;
2249 if ($mainCaseId && $otherCaseId &&
2250 $mainCaseId != $otherCaseId
2252 $duplicateCases = TRUE;
2255 $mainCaseIds = array();
2256 if (!$duplicateContacts && !$duplicateCases) {
2257 return $mainCaseIds;
2260 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2261 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2262 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2263 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2264 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2265 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2267 $processCaseIds = array($otherCaseId);
2268 if ($duplicateContacts && !$duplicateCases) {
2269 if ($changeClient) {
2270 $processCaseIds = array($mainCaseId);
2273 //get all case ids for other contact.
2274 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2276 if (!is_array($processCaseIds)) {
2281 $session = CRM_Core_Session
::singleton();
2282 $currentUserId = $session->get('userID');
2284 // copy all cases and connect to main contact id.
2285 foreach ($processCaseIds as $otherCaseId) {
2286 if ($duplicateContacts) {
2287 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2288 $mainCaseId = $mainCase->id
;
2293 // CRM-11662 Copy Case custom data
2294 $extends = array('case');
2295 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2297 foreach ($groupTree as $groupID => $group) {
2298 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2299 foreach ($group['fields'] as $fieldID => $field) {
2300 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2304 foreach ($table as $tableName => $tableColumns) {
2305 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2306 $tableColumns[0] = $mainCaseId;
2307 $select = 'SELECT ' . implode(', ', $tableColumns);
2308 $from = ' FROM ' . $tableName;
2309 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2310 $query = $insert . $select . $from . $where;
2311 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2317 $mainCaseIds[] = $mainCaseId;
2318 //insert record for case contact.
2319 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2320 $otherCaseContact->case_id
= $otherCaseId;
2321 $otherCaseContact->find();
2322 while ($otherCaseContact->fetch()) {
2323 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2324 $mainCaseContact->case_id
= $mainCaseId;
2325 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2326 if ($mainCaseContact->contact_id
== $otherContactId) {
2327 $mainCaseContact->contact_id
= $mainContactId;
2329 //avoid duplicate object.
2330 if (!$mainCaseContact->find(TRUE)) {
2331 $mainCaseContact->save();
2333 $mainCaseContact->free();
2335 $otherCaseContact->free();
2337 elseif (!$otherContactId) {
2338 $otherContactId = $mainContactId;
2341 if (!$mainCaseId ||
!$otherCaseId ||
2342 !$mainContactId ||
!$otherContactId
2347 // get all activities for other case.
2348 $otherCaseActivities = array();
2349 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2351 //for duplicate cases do not process singleton activities.
2352 $otherActivityIds = $singletonActivityIds = array();
2353 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2354 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2355 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2358 $otherActivityIds[] = $otherActId;
2360 if ($duplicateCases) {
2361 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2364 FROM civicrm_activity
2365 WHERE activity_type_id = $openCaseType
2366 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2367 $dao = CRM_Core_DAO
::executeQuery($sql);
2368 while ($dao->fetch()) {
2369 $singletonActivityIds[] = $dao->id
;
2375 // migrate all activities and connect to main contact.
2376 $copiedActivityIds = $activityMappingIds = array();
2377 sort($otherActivityIds);
2378 foreach ($otherActivityIds as $otherActivityId) {
2380 //for duplicate cases -
2381 //do not migrate singleton activities.
2382 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2386 //migrate activity record.
2387 $otherActivity = new CRM_Activity_DAO_Activity();
2388 $otherActivity->id
= $otherActivityId;
2389 if (!$otherActivity->find(TRUE)) {
2393 $mainActVals = array();
2394 $mainActivity = new CRM_Activity_DAO_Activity();
2395 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2396 $mainActivity->copyValues($mainActVals);
2397 $mainActivity->id
= NULL;
2398 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2399 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2403 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2407 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2410 $mainActivity->save();
2411 $mainActivityId = $mainActivity->id
;
2412 if (!$mainActivityId) {
2416 $activityMappingIds[$otherActivityId] = $mainActivityId;
2417 // insert log of all activities
2418 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2420 $otherActivity->free();
2421 $mainActivity->free();
2422 $copiedActivityIds[] = $otherActivityId;
2424 //create case activity record.
2425 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2426 $mainCaseActivity->case_id
= $mainCaseId;
2427 $mainCaseActivity->activity_id
= $mainActivityId;
2428 $mainCaseActivity->save();
2429 $mainCaseActivity->free();
2431 //migrate source activity.
2432 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2433 $otherSourceActivity->activity_id
= $otherActivityId;
2434 $otherSourceActivity->record_type_id
= $sourceID;
2435 $otherSourceActivity->find();
2436 while ($otherSourceActivity->fetch()) {
2437 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2438 $mainActivitySource->record_type_id
= $sourceID;
2439 $mainActivitySource->activity_id
= $mainActivityId;
2440 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2441 if ($mainActivitySource->contact_id
== $otherContactId) {
2442 $mainActivitySource->contact_id
= $mainContactId;
2444 //avoid duplicate object.
2445 if (!$mainActivitySource->find(TRUE)) {
2446 $mainActivitySource->save();
2448 $mainActivitySource->free();
2450 $otherSourceActivity->free();
2452 //migrate target activities.
2453 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2454 $otherTargetActivity->activity_id
= $otherActivityId;
2455 $otherTargetActivity->record_type_id
= $targetID;
2456 $otherTargetActivity->find();
2457 while ($otherTargetActivity->fetch()) {
2458 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2459 $mainActivityTarget->record_type_id
= $targetID;
2460 $mainActivityTarget->activity_id
= $mainActivityId;
2461 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2462 if ($mainActivityTarget->contact_id
== $otherContactId) {
2463 $mainActivityTarget->contact_id
= $mainContactId;
2465 //avoid duplicate object.
2466 if (!$mainActivityTarget->find(TRUE)) {
2467 $mainActivityTarget->save();
2469 $mainActivityTarget->free();
2471 $otherTargetActivity->free();
2473 //migrate assignee activities.
2474 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2475 $otherAssigneeActivity->activity_id
= $otherActivityId;
2476 $otherAssigneeActivity->record_type_id
= $assigneeID;
2477 $otherAssigneeActivity->find();
2478 while ($otherAssigneeActivity->fetch()) {
2479 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2480 $mainAssigneeActivity->activity_id
= $mainActivityId;
2481 $mainAssigneeActivity->record_type_id
= $assigneeID;
2482 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2483 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2484 $mainAssigneeActivity->contact_id
= $mainContactId;
2486 //avoid duplicate object.
2487 if (!$mainAssigneeActivity->find(TRUE)) {
2488 $mainAssigneeActivity->save();
2490 $mainAssigneeActivity->free();
2492 $otherAssigneeActivity->free();
2494 // copy custom fields and attachments
2496 'activityID' => $otherActivityId,
2497 'mainActivityId' => $mainActivityId,
2499 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2502 //copy case relationship.
2503 if ($duplicateContacts) {
2504 //migrate relationship records.
2505 $otherRelationship = new CRM_Contact_DAO_Relationship();
2506 $otherRelationship->case_id
= $otherCaseId;
2507 $otherRelationship->find();
2508 $otherRelationshipIds = array();
2509 while ($otherRelationship->fetch()) {
2510 $otherRelVals = array();
2511 $updateOtherRel = FALSE;
2512 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2514 $mainRelationship = new CRM_Contact_DAO_Relationship();
2515 $mainRelationship->copyValues($otherRelVals);
2516 $mainRelationship->id
= NULL;
2517 $mainRelationship->case_id
= $mainCaseId;
2518 if ($mainRelationship->contact_id_a
== $otherContactId) {
2519 $updateOtherRel = TRUE;
2520 $mainRelationship->contact_id_a
= $mainContactId;
2523 //case creator change only when we merge user contact.
2524 if ($mainRelationship->contact_id_b
== $otherContactId) {
2525 //do not change creator for change client.
2526 if (!$changeClient) {
2527 $updateOtherRel = TRUE;
2528 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2531 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2532 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2534 //avoid duplicate object.
2535 if (!$mainRelationship->find(TRUE)) {
2536 $mainRelationship->save();
2538 $mainRelationship->free();
2540 //get the other relationship ids to update end date.
2541 if ($updateOtherRel) {
2542 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2545 $otherRelationship->free();
2547 //update other relationships end dates
2548 if (!empty($otherRelationshipIds)) {
2549 $sql = 'UPDATE civicrm_relationship
2550 SET end_date = CURDATE()
2551 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2552 CRM_Core_DAO
::executeQuery($sql);
2556 //move other case to trash.
2557 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2562 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2563 if ($changeClient) {
2564 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2565 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2567 $mergeActType = array_search('Reassigned Case', $activityTypes);
2568 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2571 2 => $otherContactDisplayName,
2572 3 => $mainContactDisplayName,
2577 elseif ($duplicateContacts) {
2578 $mergeActType = array_search('Merge Case', $activityTypes);
2579 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2582 2 => $otherContactId,
2583 3 => $mainContactId,
2589 $mergeActType = array_search('Merge Case', $activityTypes);
2590 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2591 if (!empty($copiedActivityIds)) {
2593 SELECT id, subject, activity_date_time, activity_type_id
2594 FROM civicrm_activity
2595 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2596 $dao = CRM_Core_DAO
::executeQuery($sql);
2597 while ($dao->fetch()) {
2598 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2599 if ($dao->subject
) {
2600 $mergeActSubjectDetails .= " :: {$dao->subject}";
2602 $mergeActSubjectDetails .= "<br />";
2607 //create merge activity record.
2608 $activityParams = array(
2609 'subject' => $mergeActSubject,
2610 'details' => $mergeActSubjectDetails,
2611 'status_id' => array_search('Completed', $activityStatuses),
2612 'activity_type_id' => $mergeActType,
2613 'source_contact_id' => $mainContactId,
2614 'activity_date_time' => date('YmdHis'),
2617 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2618 $mergeActivityId = $mergeActivity->id
;
2619 if (!$mergeActivityId) {
2622 $mergeActivity->free();
2624 //connect merge activity to case.
2625 $mergeCaseAct = array(
2626 'case_id' => $mainCaseId,
2627 'activity_id' => $mergeActivityId,
2630 self
::processCaseActivity($mergeCaseAct);
2632 return $mainCaseIds;
2636 * Validate contact permission for
2637 * edit/view on activity record and build links.
2639 * @param array $tplParams params to be sent to template for sending email.
2640 * @param array $activityParams info of the activity.
2645 static function buildPermissionLinks(&$tplParams, $activityParams) {
2646 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2647 'activity_type_id', 'id'
2650 if (CRM_Utils_Array
::value('isCaseActivity', $tplParams)) {
2651 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2652 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2655 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2656 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2659 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2660 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2664 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2665 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2668 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2669 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2675 * Validate contact permission for
2676 * given operation on activity record.
2678 * @param int $activityId activity record id.
2679 * @param string $operation user operation.
2680 * @param int $actTypeId activity type id.
2681 * @param int $contactId contact id/if not pass consider logged in
2682 * @param boolean $checkComponent do we need to check component enabled.
2684 * @return boolean $allow true/false
2687 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2689 if (!$actTypeId && $activityId) {
2690 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2693 if (!$activityId ||
!$operation ||
!$actTypeId) {
2697 //do check for civicase component enabled.
2698 if ($checkComponent) {
2699 static $componentEnabled;
2700 if (!isset($componentEnabled)) {
2701 $config = CRM_Core_Config
::singleton();
2702 $componentEnabled = FALSE;
2703 if (in_array('CiviCase', $config->enableComponents
)) {
2704 $componentEnabled = TRUE;
2707 if (!$componentEnabled) {
2712 //do check for cases.
2713 $caseActOperations = array(
2720 if (in_array($operation, $caseActOperations)) {
2721 static $unclosedCases;
2722 if (!is_array($unclosedCases)) {
2723 $unclosedCases = self
::getUnclosedCases();
2725 if ($operation == 'File On Case') {
2726 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2729 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2733 $actionOperations = array('view', 'edit', 'delete');
2734 if (in_array($operation, $actionOperations)) {
2736 //do cache when user has non/supper permission.
2737 static $allowOperations;
2739 if (!is_array($allowOperations) ||
2740 !array_key_exists($operation, $allowOperations)
2744 $session = CRM_Core_Session
::singleton();
2745 $contactId = $session->get('userID');
2748 //check for permissions.
2749 $permissions = array(
2751 'access my cases and activities',
2752 'access all cases and activities',
2755 'access my cases and activities',
2756 'access all cases and activities',
2758 'delete' => array('delete activities'),
2761 //check for core permission.
2762 $hasPermissions = array();
2763 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2764 if (is_array($checkPermissions)) {
2765 foreach ($checkPermissions as $per) {
2766 if (CRM_Core_Permission
::check($per)) {
2767 $hasPermissions[$operation][] = $per;
2773 if (!empty($hasPermissions)) {
2774 //need to check activity object specific.
2775 if (in_array($operation, array(
2780 //do we have supper permission.
2781 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2782 $allowOperations[$operation] = $allow = TRUE;
2785 //user has only access to my cases and activity.
2786 //here object specific permmions come in picture.
2788 //edit - contact must be source or assignee
2789 //view - contact must be source/assignee/target
2790 $isTarget = $isAssignee = $isSource = FALSE;
2791 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
2792 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2793 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2794 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2796 $target = new CRM_Activity_DAO_ActivityContact();
2797 $target->record_type_id
= $targetID;
2798 $target->activity_id
= $activityId;
2799 $target->contact_id
= $contactId;
2800 if ($target->find(TRUE)) {
2804 $assignee = new CRM_Activity_DAO_ActivityContact();
2805 $assignee->activity_id
= $activityId;
2806 $assignee->record_type_id
= $assigneeID;
2807 $assignee->contact_id
= $contactId;
2808 if ($assignee->find(TRUE)) {
2812 $source = new CRM_Activity_DAO_ActivityContact();
2813 $source->activity_id
= $activityId;
2814 $source->record_type_id
= $sourceID;
2815 $source->contact_id
= $contactId;
2816 if ($source->find(TRUE)) {
2820 if ($operation == 'edit') {
2821 if ($isAssignee ||
$isSource) {
2825 if ($operation == 'view') {
2826 if ($isTarget ||
$isAssignee ||
$isSource) {
2832 elseif (is_array($hasPermissions[$operation])) {
2833 $allowOperations[$operation] = $allow = TRUE;
2837 //contact do not have permission.
2838 $allowOperations[$operation] = FALSE;
2843 //here contact might have supper/non permission.
2844 $allow = $allowOperations[$operation];
2848 //do further only when operation is granted.
2850 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2852 //get the activity type name.
2853 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2855 //do not allow multiple copy / edit action.
2856 $singletonNames = array(
2866 //do not allow to delete these activities, CRM-4543
2867 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2869 //allow edit operation.
2870 $allowEditNames = array('Open Case');
2872 // do not allow File on Case
2873 $doNotFileNames = array(
2876 'Change Case Status',
2877 'Change Case Start Date',
2884 if (in_array($actTypeName, $singletonNames)) {
2886 if ($operation == 'File On Case') {
2887 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2889 if (in_array($operation, $actionOperations)) {
2891 if ($operation == 'edit') {
2892 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2894 elseif ($operation == 'delete') {
2895 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2899 if ($allow && ($operation == 'delete') &&
2900 in_array($actTypeName, $doNotDeleteNames)
2905 if ($allow && ($operation == 'File On Case') &&
2906 in_array($actTypeName, $doNotFileNames)
2911 //check settings file for masking actions
2912 //on the basis the activity types
2913 //hide Edit link if activity type is NOT editable
2914 //(special case activities).CRM-5871
2915 if ($allow && in_array($operation, $actionOperations)) {
2916 static $actionFilter = array();
2917 if (!array_key_exists($operation, $actionFilter)) {
2918 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2919 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2921 if (array_key_exists($operation, $actionFilter[$operation]) &&
2922 in_array($actTypeId, $actionFilter[$operation][$operation])
2933 * since we drop 'access CiviCase', allow access
2934 * if user has 'access my cases and activities'
2935 * or 'access all cases and activities'
2937 static function accessCiviCase() {
2938 static $componentEnabled;
2939 if (!isset($componentEnabled)) {
2940 $componentEnabled = FALSE;
2941 $config = CRM_Core_Config
::singleton();
2942 if (in_array('CiviCase', $config->enableComponents
)) {
2943 $componentEnabled = TRUE;
2946 if (!$componentEnabled) {
2950 if (CRM_Core_Permission
::check('access my cases and activities') ||
2951 CRM_Core_Permission
::check('access all cases and activities')
2960 * Function to check whether activity is a case Activity
2962 * @param int $activityID activity id
2964 * @return boolean $isCaseActivity true/false
2966 static function isCaseActivity($activityID) {
2967 $isCaseActivity = FALSE;
2969 $params = array(1 => array($activityID, 'Integer'));
2970 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2971 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2972 $isCaseActivity = TRUE;
2976 return $isCaseActivity;
2980 * Function to get all the case type ids currently in use
2983 * @return array $caseTypeIds
2985 static function getUsedCaseType() {
2986 static $caseTypeIds;
2988 if (!is_array($caseTypeIds)) {
2989 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2991 $dao = CRM_Core_DAO
::executeQuery($query);
2992 $caseTypeIds = array();
2993 while ($dao->fetch()) {
2994 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2997 $caseTypeIds[] = $typeId[1];
3001 return $caseTypeIds;
3005 * Function to get all the case status ids currently in use
3008 * @return array $caseStatusIds
3010 static function getUsedCaseStatuses() {
3011 static $caseStatusIds;
3013 if (!is_array($caseStatusIds)) {
3014 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3016 $dao = CRM_Core_DAO
::executeQuery($query);
3017 $caseStatusIds = array();
3018 while ($dao->fetch()) {
3019 $caseStatusIds[] = $dao->status_id
;
3023 return $caseStatusIds;
3027 * Function to get all the encounter medium ids currently in use
3030 static function getUsedEncounterMediums() {
3033 if (!is_array($mediumIds)) {
3034 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3036 $dao = CRM_Core_DAO
::executeQuery($query);
3037 $mediumIds = array();
3038 while ($dao->fetch()) {
3039 $mediumIds[] = $dao->medium_id
;
3047 * Function to check case configuration.
3049 * @return array $configured
3051 static function isCaseConfigured($contactId = NULL) {
3052 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3054 //lets check for case configured.
3055 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3056 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3057 if (!$configured['configured']) {
3058 //do check for case type and case status.
3059 $caseTypes = CRM_Case_PseudoConstant
::caseType('label', FALSE);
3060 if (!empty($caseTypes)) {
3061 $configured['configured'] = TRUE;
3062 if (!$configured['configured']) {
3063 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3064 if (!empty($caseStatuses)) {
3065 $configured['configured'] = TRUE;
3070 if ($configured['configured']) {
3071 //do check for active case type and case status.
3072 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3073 if (!empty($caseTypes)) {
3074 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3075 if (!empty($caseStatuses)) {
3076 $configured['allowToAddNewCase'] = TRUE;
3080 //do we need to redirect user to case admin.
3081 if (!$configured['allowToAddNewCase'] && $contactId) {
3082 //check for current contact case count.
3083 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3084 //redirect user to case admin page.
3085 if (!$currentContatCasesCount) {
3086 $configured['redirectToCaseAdmin'] = TRUE;
3095 * Used during case component enablement and during ugprade
3097 static function createCaseViews() {
3098 $sql = self
::createCaseViewsQuery('upcoming');
3099 CRM_Core_Error
::ignoreException();
3100 $dao = new CRM_Core_DAO();
3102 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3103 CRM_Core_Error
::setCallback();
3107 // Above error doesn't get caught?
3108 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3109 if (is_null($doublecheck)) {
3113 $sql = self
::createCaseViewsQuery('recent');
3114 CRM_Core_Error
::ignoreException();
3116 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3117 CRM_Core_Error
::setCallback();
3121 // Above error doesn't get caught?
3122 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3123 if (is_null($doublecheck)) {
3131 * helper function, also used by the upgrade in case of error
3133 static function createCaseViewsQuery($section = 'upcoming') {
3135 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3138 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3139 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3140 FROM civicrm_case_activity ca
3141 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3142 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3143 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3147 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3148 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3149 FROM civicrm_case_activity ca
3150 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3151 WHERE a.activity_date_time <= NOW()
3152 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3153 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3160 * Function to add/copy relationships, when new client is added for a case
3162 * @param int $caseId case id
3163 * @param int $contactId contact id / new client id
3167 static function addCaseRelationships($caseId, $contactId) {
3168 // get the case role / relationships for the case
3169 $caseRelationships = new CRM_Contact_DAO_Relationship();
3170 $caseRelationships->case_id
= $caseId;
3171 $caseRelationships->find();
3172 $relationshipTypes = array();
3174 // make sure we don't add duplicate relationships of same relationship type.
3175 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3177 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3179 // add relationship for new client.
3180 $newRelationship = new CRM_Contact_DAO_Relationship();
3181 $newRelationship->copyValues($values);
3182 $newRelationship->id
= NULL;
3183 $newRelationship->case_id
= $caseId;
3184 $newRelationship->contact_id_a
= $contactId;
3185 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3186 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3188 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3189 if (!$newRelationship->find(TRUE)) {
3190 $newRelationship->save();
3192 $newRelationship->free();
3194 // store relationship type of newly created relationship
3195 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3200 * Function to get the list of clients for a case
3202 * @param int $caseId
3204 * @return array $clients associated array with client ids
3207 static function getCaseClients($caseId) {
3209 $caseContact = new CRM_Case_DAO_CaseContact();
3210 $caseContact->case_id
= $caseId;
3211 $caseContact->find();
3213 while ($caseContact->fetch()) {
3214 $clients[] = $caseContact->contact_id
;