3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class contains the functions for Case Management
40 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
43 * static field for all the case information that we can potentially export
48 static $_exportableFields = NULL;
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 (!empty($params['id'])) {
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 (!empty($params['custom']) &&
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 (!empty($params['id'])) {
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, $caseType = NULL) {
521 FROM civicrm_case_contact cc
522 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
524 if (isset($caseType)) {
526 "INNER JOIN civicrm_option_value cov ON (cov.value = ca.case_type_id)
527 INNER JOIN civicrm_option_group cog ON (cog.id = cov.option_group_id and cog.name = 'case_type')
528 WHERE cc.contact_id = %1 AND cov.name = '{$caseType}'";
530 if (!isset($caseType)) {
531 $query .= "WHERE cc.contact_id = %1";
533 if (!$includeDeleted) {
534 $query .= " AND ca.is_deleted = 0";
537 $params = array(1 => array($contactID, 'Integer'));
538 $dao = CRM_Core_DAO
::executeQuery($query, $params);
540 $caseArray = array();
541 while ($dao->fetch()) {
542 $caseArray[] = $dao->id
;
549 static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL, $isDeleted = 0) {
551 $session = CRM_Core_Session
::singleton();
552 $userID = $session->get('userID');
555 $actStatus = array_flip(CRM_Core_PseudoConstant
::activityStatus('name'));
556 $scheduledStatusId = $actStatus['Scheduled'];
559 civicrm_case.id as case_id,
560 civicrm_case.subject as case_subject,
561 civicrm_contact.id as contact_id,
562 civicrm_contact.sort_name as sort_name,
563 civicrm_phone.phone as phone,
564 civicrm_contact.contact_type as contact_type,
565 civicrm_contact.contact_sub_type as contact_sub_type,
566 t_act.activity_type_id,
567 cov_type.label as case_type,
568 cov_type.name as case_type_name,
569 cov_status.label as case_status,
570 cov_status.label as case_status_name,
572 civicrm_case.start_date as case_start_date,
573 case_relation_type.label_b_a as case_role, ";
575 if ($type == 'upcoming') {
577 t_act.desired_date as case_scheduled_activity_date,
578 t_act.id as case_scheduled_activity_id,
579 t_act.act_type_name as case_scheduled_activity_type_name,
580 t_act.act_type AS case_scheduled_activity_type ";
582 elseif ($type == 'recent') {
584 t_act.desired_date as case_recent_activity_date,
585 t_act.id as case_recent_activity_id,
586 t_act.act_type_name as case_recent_activity_type_name,
587 t_act.act_type AS case_recent_activity_type ";
589 elseif ( $type == 'any' ) {
591 t_act.desired_date as case_activity_date,
592 t_act.id as case_activity_id,
593 t_act.act_type_name as case_activity_type_name,
594 t_act.act_type AS case_activity_type ";
597 $query .= " FROM civicrm_case
598 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
599 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
601 if ($type == 'upcoming') {
602 // This gets the earliest activity per case that's scheduled within 14 days from now.
603 // 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.
604 // In this case we don't really care which one, so min(id) works.
605 // optimized in CRM-11837
606 $query .= " INNER JOIN
608 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
613 FROM civicrm_view_case_activity_upcoming
614 ORDER BY activity_date_time ASC, id ASC
618 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
619 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
623 elseif ($type == 'recent') {
624 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
625 //improve query performance - CRM-10598
626 $query .= " INNER JOIN
628 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
633 FROM civicrm_view_case_activity_recent
634 ORDER BY activity_date_time DESC, id ASC
638 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
639 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
642 elseif ( $type == 'any' ) {
643 $query .= " LEFT JOIN
645 SELECT ca4.case_id, act4.id AS id, act4.activity_date_time AS desired_date, act4.activity_type_id, act4.status_id, aov.name AS act_type_name, aov.label AS act_type
646 FROM civicrm_activity act4
647 LEFT JOIN civicrm_case_activity ca4
648 ON ca4.activity_id = act4.id
649 AND act4.is_current_revision = 1
650 LEFT JOIN civicrm_option_group aog
651 ON aog.name='activity_type'
652 LEFT JOIN civicrm_option_value aov
653 ON aov.option_group_id = aog.id
654 AND aov.value = act4.activity_type_id
659 ON t_act.case_id = civicrm_case.id
660 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
661 LEFT JOIN civicrm_relationship case_relationship
662 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
663 AND case_relationship.case_id = civicrm_case.id )
665 LEFT JOIN civicrm_relationship_type case_relation_type
666 ON ( case_relation_type.id = case_relationship.relationship_type_id
667 AND case_relation_type.id = case_relationship.relationship_type_id )
669 LEFT JOIN civicrm_option_group cog_type
670 ON cog_type.name = 'case_type'
672 LEFT JOIN civicrm_option_value cov_type
673 ON ( civicrm_case.case_type_id = cov_type.value
674 AND cog_type.id = cov_type.option_group_id )
676 LEFT JOIN civicrm_option_group cog_status
677 ON cog_status.name = 'case_status'
679 LEFT JOIN civicrm_option_value cov_status
680 ON ( civicrm_case.status_id = cov_status.value
681 AND cog_status.id = cov_status.option_group_id )
685 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
686 $query .= " WHERE (1) $condition ";
689 if ($type == 'upcoming') {
690 $query .= " ORDER BY case_scheduled_activity_date ASC ";
692 elseif ($type == 'recent') {
693 $query .= " ORDER BY case_recent_activity_date ASC ";
695 elseif ( $type == 'any' ) {
696 $query .= " ORDER BY case_activity_date ASC ";
703 * Retrieve cases related to particular contact or whole contact
704 * used in Dashboad and Tab
706 * @param boolean $allCases
710 * @param String $type /upcoming,recent,all/
712 * @return array Array of Cases
717 static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
719 $casesList = array();
721 //validate access for own cases.
722 if (!self
::accessCiviCase()) {
727 $session = CRM_Core_Session
::singleton();
728 $userID = $session->get('userID');
731 //validate access for all cases.
732 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
737 $condition = " AND civicrm_case.is_deleted = 0 ";
740 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
742 if ( $type == 'upcoming' ||
$type == 'any' ) {
743 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
745 AND civicrm_case.status_id != $closedId";
748 $query = self
::getCaseActivityQuery($type, $userID, $condition);
750 $queryParams = array();
751 $result = CRM_Core_DAO
::executeQuery($query,
755 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
757 $resultFields = array(
774 if ($type == 'upcoming') {
775 $resultFields[] = 'case_scheduled_activity_date';
776 $resultFields[] = 'case_scheduled_activity_type_name';
777 $resultFields[] = 'case_scheduled_activity_type';
778 $resultFields[] = 'case_scheduled_activity_id';
780 elseif ($type == 'recent') {
781 $resultFields[] = 'case_recent_activity_date';
782 $resultFields[] = 'case_recent_activity_type_name';
783 $resultFields[] = 'case_recent_activity_type';
784 $resultFields[] = 'case_recent_activity_id';
786 elseif ( $type == 'any' ) {
787 $resultFields[] = 'case_activity_date';
788 $resultFields[] = 'case_activity_type_name';
789 $resultFields[] = 'case_activity_type';
790 $resultFields[] = 'case_activity_id';
793 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
794 $actions = CRM_Case_Selector_Search
::links();
797 // check is the user has view/edit signer permission
798 $permissions = array(CRM_Core_Permission
::VIEW
);
799 if (CRM_Core_Permission
::check('access all cases and activities') ||
800 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
802 $permissions[] = CRM_Core_Permission
::EDIT
;
804 if (CRM_Core_Permission
::check('delete in CiviCase')) {
805 $permissions[] = CRM_Core_Permission
::DELETE
;
807 $mask = CRM_Core_Action
::mask($permissions);
809 while ($result->fetch()) {
810 foreach ($resultFields as $donCare => $field) {
811 $casesList[$result->case_id
][$field] = $result->$field;
812 if ($field == 'contact_type') {
813 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
814 $result->contact_sub_type
: $result->contact_type
816 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
818 'id' => $result->case_id
,
819 'cid' => $result->contact_id
,
824 'case.actions.primary',
828 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
831 'id' => $result->case_id
,
832 'cid' => $result->contact_id
,
842 elseif ($field == 'case_status') {
843 if (in_array($result->$field, $caseStatus)) {
844 $casesList[$result->case_id
]['class'] = "status-urgent";
847 $casesList[$result->case_id
]['class'] = "status-normal";
852 $caseManagerContact = self
::getCaseManagerContact($result->case_type_name
, $result->case_id
);
853 if (!empty($caseManagerContact)) {
854 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
855 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
858 //do check user permissions for edit/view activity.
859 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
860 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
862 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
864 $casesList[$result->case_id
]['activity_type_id'], $userID
866 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
868 $casesList[$result->case_id
]['activity_type_id'], $userID
877 * Function to get the summary of cases counts by type and status.
879 static function getCasesSummary($allCases = TRUE, $userID) {
880 $caseSummary = array();
882 //validate access for civicase.
883 if (!self
::accessCiviCase()) {
887 //validate access for all cases.
888 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
892 $caseTypes = CRM_Case_PseudoConstant
::caseType();
893 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
894 $caseTypes = array_flip($caseTypes);
896 // get statuses as headers for the table
897 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
898 foreach ($caseStatuses as $key => $name) {
899 $caseSummary['headers'][$key]['status'] = $name;
900 $caseSummary['headers'][$key]['url'] = $url . $key;
903 // build rows with actual data
905 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
915 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
916 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
919 $seperator = CRM_Core_DAO
::VALUE_SEPARATOR
;
922 SELECT case_status.label AS case_status, status_id, case_type.label AS case_type,
923 REPLACE(case_type_id,'{$seperator}','') AS case_type_id, case_relationship.contact_id_b
925 LEFT JOIN civicrm_option_group option_group_case_type ON ( option_group_case_type.name = 'case_type' )
926 LEFT JOIN civicrm_option_value case_type ON ( civicrm_case.case_type_id = case_type.value
927 AND option_group_case_type.id = case_type.option_group_id )
928 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
929 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
930 AND option_group_case_status.id = case_status.option_group_id )
931 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
932 AND case_relationship.contact_id_b = {$userID})
934 {$myCaseWhereClause} {$myGroupByClause}";
936 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
937 while ($res->fetch()) {
938 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
939 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
942 $rows[$res->case_type
][$res->case_status
] = array(
944 'url' => CRM_Utils_System
::url('civicrm/case/search',
945 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
950 $caseSummary['rows'] = array_merge($caseTypes, $rows);
956 * Function to get Case roles
958 * @param int $contactID contact id
959 * @param int $caseID case id
960 * @return returns case role / relationships
964 static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
966 SELECT civicrm_relationship.id as civicrm_relationship_id,
967 civicrm_contact.sort_name as sort_name,
968 civicrm_email.email as email,
969 civicrm_phone.phone as phone,
970 civicrm_relationship.contact_id_b as civicrm_contact_id,
971 civicrm_relationship.contact_id_a as client_id,
972 civicrm_relationship_type.label_a_b as relation,
973 civicrm_relationship_type.id as relation_type
974 FROM civicrm_relationship
975 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
976 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
977 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
978 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
979 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
983 1 => array($contactID, 'Positive'),
984 2 => array($caseID, 'Positive'),
987 if ($relationshipID) {
988 $query .= ' AND civicrm_relationship.id = %3 ';
989 $params[3] = array($relationshipID, 'Integer');
991 $dao = CRM_Core_DAO
::executeQuery($query, $params);
994 while ($dao->fetch()) {
995 $rid = $dao->civicrm_relationship_id
;
996 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
997 $values[$rid]['relation'] = $dao->relation
;
998 $values[$rid]['name'] = $dao->sort_name
;
999 $values[$rid]['email'] = $dao->email
;
1000 $values[$rid]['phone'] = $dao->phone
;
1001 $values[$rid]['relation_type'] = $dao->relation_type
;
1002 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
1003 $values[$rid]['client_id'] = $dao->client_id
;
1011 * Function to get Case Activities
1013 * @param int $caseID case id
1014 * @param array $params posted params
1015 * @param int $contactID contact id
1017 * @return returns case activities
1021 static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
1024 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1025 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1026 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1027 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1029 // CRM-5081 - formatting the dates to omit seconds.
1030 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
1031 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
1032 ca.activity_type_id as type,
1033 ca.activity_type_id as activity_type_id,
1034 cc.sort_name as reporter,
1035 cc.id as reporter_id,
1036 acc.sort_name AS assignee,
1037 acc.id AS assignee_id,
1038 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1039 ca.activity_date_time,
1040 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1041 ), '%Y%m%d%H%i00') as overdue_date,
1042 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
1043 ca.status_id as status,
1044 ca.subject as subject,
1045 ca.is_deleted as deleted,
1046 ca.priority_id as priority,
1047 ca.weight as weight,
1048 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1051 FROM civicrm_case_activity cca
1052 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1053 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1054 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1055 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1056 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1057 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1058 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1059 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1060 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1061 LEFT JOIN civicrm_activity_contact caa
1062 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1063 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1065 $where = 'WHERE cca.case_id= %1
1066 AND ca.is_current_revision = 1';
1068 if (!empty($params['reporter_id'])) {
1069 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1072 if (!empty($params['status_id'])) {
1073 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1076 if (!empty($params['activity_deleted'])) {
1077 $where .= " AND ca.is_deleted = 1";
1080 $where .= " AND ca.is_deleted = 0";
1083 if (!empty($params['activity_type_id'])) {
1084 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1087 if (!empty($params['activity_date_low'])) {
1088 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1090 if (!empty($params['activity_date_high'])) {
1091 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1092 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1095 if (!empty($fromActivityDate)) {
1096 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1099 if (!empty($toActivityDate)) {
1100 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1103 // hack to handle to allow initial sorting to be done by query
1104 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1105 $params['sortname'] = NULL;
1108 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1109 $params['sortorder'] = NULL;
1112 $sortname = CRM_Utils_Array
::value('sortname', $params);
1113 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1115 $groupBy = " GROUP BY ca.id ";
1117 if (!$sortname AND !$sortorder) {
1118 // CRM-5081 - added id to act like creation date
1119 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1122 $sort = "{$sortname} {$sortorder}";
1123 $sort = CRM_Utils_Type
::escape($sort, 'String');
1124 $orderBy = " ORDER BY $sort ";
1125 if ($sortname != 'display_date') {
1126 $orderBy .= ', display_date DESC';
1130 $page = CRM_Utils_Array
::value('page', $params);
1131 $rp = CRM_Utils_Array
::value('rp', $params);
1140 $start = (($page - 1) * $rp);
1141 $query = $select . $from . $where . $groupBy . $orderBy;
1143 $params = array(1 => array($caseID, 'Integer'));
1144 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1145 $params['total'] = $dao->N
;
1147 //FIXME: need to optimize/cache these queries
1148 $limit = " LIMIT $start, $rp";
1152 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1155 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1156 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1157 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1159 $url = CRM_Utils_System
::url("civicrm/case/activity",
1160 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1164 if ($context == 'fulltext') {
1165 $contextUrl = "&context={$context}";
1167 $editUrl = "{$url}&action=update{$contextUrl}";
1168 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1169 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1170 $viewTitle = ts('View this activity.');
1171 $statusTitle = ts('Edit status');
1173 $emailActivityTypeIDs = array(
1174 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1178 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1184 $emailActivityTypeIDs = array(
1185 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1189 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1195 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1197 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1198 $compStatusValues = array();
1199 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1200 foreach ($compStatusNames as $name) {
1201 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1203 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1204 "reset=1&cid=", FALSE, NULL, FALSE
1206 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1207 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1210 $session = CRM_Core_Session
::singleton();
1211 $userID = $session->get('userID');
1214 while ($dao->fetch()) {
1216 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1217 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1218 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1220 //do not have sufficient permission
1221 //to access given case activity record.
1222 if (!$allowView && !$allowEdit && !$allowDelete) {
1226 $values[$dao->id
]['id'] = $dao->id
;
1227 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1229 $reporterName = $dao->reporter
;
1230 if ($hasViewContact) {
1231 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1233 $values[$dao->id
]['reporter'] = $reporterName;
1234 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1235 $targetContactUrls = $withContacts = array();
1236 foreach ($targetNames as $targetId => $targetName) {
1237 if (!in_array($targetId, $clientIds)) {
1238 $withContacts[$targetId] = $targetName;
1241 foreach ($withContacts as $cid => $name) {
1242 if ($hasViewContact) {
1243 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1245 $targetContactUrls[] = $name;
1247 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1249 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1250 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1252 //check for view activity.
1253 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1255 $url = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $dao->id
));
1256 $subject = '<a class="crm-popup medium-popup" href="' . $url . '" title="' . $viewTitle . '">' . $subject . '</a>';
1258 $values[$dao->id
]['subject'] = $subject;
1260 // add activity assignee to activity selector. CRM-4485.
1261 if (isset($dao->assignee
)) {
1262 if ($dao->ismultiple
== 1) {
1263 if ($dao->reporter_id
!= $dao->assignee_id
) {
1264 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1266 $values[$dao->id
]['assignee'] = $dao->assignee
;
1269 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1272 // FIXME: Why are we not using CRM_Core_Action for these links? This is too much manual work and likely to get out-of-sync with core markup.
1274 $css = 'class="action-item crm-hover-button"';
1275 $additionalUrl = "&id={$dao->id}";
1276 if (!$dao->deleted
) {
1277 //hide edit link of activity type email.CRM-4530.
1278 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1279 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1281 $url = '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1285 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1288 elseif (!$caseDeleted) {
1289 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1290 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1293 //check for operations.
1294 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1295 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1297 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1298 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1300 // if there are file attachments we will return how many and, if only one, add a link to it
1301 if (!empty($dao->attachment_ids
)) {
1302 $attachmentIDs = explode(',', $dao->attachment_ids
);
1303 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1304 if ($values[$dao->id
]['no_attachments'] == 1) {
1305 // if there is only one it's easy to do a link - otherwise just flag it
1306 $attachmentViewUrl = CRM_Utils_System
::url(
1308 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1313 $url .= " <a href='$attachmentViewUrl' ><span class='icon paper-icon'></span></a>";
1318 $values[$dao->id
]['links'] = $url;
1319 $values[$dao->id
]['class'] = "";
1321 if (!empty($dao->priority
)) {
1322 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1323 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1325 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1326 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1330 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1331 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1334 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1335 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1338 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1343 $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>';
1352 * Function to get Case Related Contacts
1354 * @param int $caseID case id
1355 * @param boolean $skipDetails if true include details of contacts
1357 * @return returns $searchRows array of returnproperties
1361 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1363 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1364 FROM civicrm_relationship cr
1365 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1366 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1367 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1368 WHERE cr.case_id = %1 AND ce.is_primary= 1
1371 $params = array(1 => array($caseID, 'Integer'));
1372 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1374 while ($dao->fetch()) {
1376 $values[$dao->id
] = 1;
1380 'contact_id' => $dao->id
,
1381 'display_name' => $dao->name
,
1382 'sort_name' => $dao->sort_name
,
1383 'role' => $dao->role
,
1384 'email' => $dao->email
,
1394 * Function that sends e-mail copy of activity
1396 * @param int $activityId activity Id
1397 * @param array $contacts array of related contact
1402 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1407 $tplParams = $activityInfo = array();
1408 //if its a case activity
1410 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1411 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1412 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1413 $anyActivity = TRUE;
1416 $anyActivity = FALSE;
1418 $tplParams['isCaseActivity'] = 1;
1419 $tplParams['client_id'] = $clientId;
1422 $anyActivity = TRUE;
1425 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1426 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1428 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1430 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1432 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1434 $tplParams['activity'] = $activityInfo;
1435 foreach ($tplParams['activity']['fields'] as $k => $val) {
1436 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1437 $activitySubject = $val['value'];
1441 $session = CRM_Core_Session
::singleton();
1442 // CRM-8926 If user is not logged in, use the activity creator as userID
1443 if (!($userID = $session->get('userID'))) {
1444 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1447 //also create activities simultaneously of this copy.
1448 $activityParams = array();
1450 $activityParams['source_record_id'] = $activityId;
1451 $activityParams['source_contact_id'] = $userID;
1452 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1453 $activityParams['activity_date_time'] = date('YmdHis');
1454 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1455 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1456 $activityParams['case_id'] = $caseId;
1457 $activityParams['is_auto'] = 0;
1458 $activityParams['target_id'] = $clientId;
1460 $tplParams['activitySubject'] = $activitySubject;
1462 // if it’s a case activity, add hashed id to the template (CRM-5916)
1464 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1468 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1470 $receiptFrom = "$name <$address>";
1472 $recordedActivityParams = array();
1474 foreach ($contacts as $mail => $info) {
1475 $tplParams['contact'] = $info;
1476 self
::buildPermissionLinks($tplParams, $activityParams);
1478 $displayName = CRM_Utils_Array
::value('display_name', $info);
1480 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1482 'groupName' => 'msg_tpl_workflow_case',
1483 'valueName' => 'case_activity',
1484 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1485 'tplParams' => $tplParams,
1486 'from' => $receiptFrom,
1487 'toName' => $displayName,
1489 'attachments' => $attachments,
1493 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1494 $activityParams['details'] = $message;
1496 if (!empty($result[$info['contact_id']])) {
1498 * Really only need to record one activity with all the targets combined.
1499 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1500 * but it's always the same content at the moment.
1502 if (empty($recordedActivityParams)) {
1503 $recordedActivityParams = $activityParams;
1506 $recordedActivityParams['subject'] .= "; $displayName";
1508 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1511 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1515 if (!empty($recordedActivityParams)) {
1516 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1518 //create case_activity record if its case activity.
1520 $caseParams = array(
1521 'activity_id' => $activity->id
,
1522 'case_id' => $caseId,
1524 self
::processCaseActivity($caseParams);
1532 * Retrieve count of activities having a particular type, and
1533 * associated with a particular case.
1535 * @param int $caseId ID of the case
1536 * @param int $activityTypeId ID of the activity type
1543 static function getCaseActivityCount($caseId, $activityTypeId) {
1544 $queryParam = array(
1545 1 => array($caseId, 'Integer'),
1546 2 => array($activityTypeId, 'Integer'),
1548 $query = "SELECT count(ca.id) as countact
1549 FROM civicrm_activity ca
1550 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1551 WHERE ca.activity_type_id = %2
1552 AND cca.case_id = %1
1553 AND ca.is_deleted = 0";
1555 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1556 if ($dao->fetch()) {
1557 return $dao->countact
;
1564 * Create an activity for a case via email
1566 * @param int $file email sent
1568 * @return $activity object of newly creted activity via email
1573 static function recordActivityViaEmail($file) {
1574 if (!file_exists($file) ||
1577 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1582 $result = CRM_Utils_Mail_Incoming
::parse($file);
1583 if ($result['is_error']) {
1587 foreach ($result['to'] as $to) {
1590 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1591 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1593 if ($replacement !== $to['email']) {
1594 $caseId = $replacement;
1595 //if caseId is invalid, return as error file
1596 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1597 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1606 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1607 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1608 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1610 if (!empty($contactDetails[$result['from']['id']])) {
1612 $params['subject'] = $result['subject'];
1613 $params['activity_date_time'] = $result['date'];
1614 $params['details'] = $result['body'];
1615 $params['source_contact_id'] = $result['from']['id'];
1616 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1621 $details = CRM_Case_PseudoConstant
::caseActivityType();
1623 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1624 $result['body'], $matches
1627 if (!empty($matches) && isset($matches[1])) {
1628 $activityType = trim($matches[1]);
1629 if (isset($details[$activityType])) {
1630 $params['activity_type_id'] = $details[$activityType]['id'];
1633 if (!isset($params['activity_type_id'])) {
1634 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1638 $activity = CRM_Activity_BAO_Activity
::create($params);
1640 $caseParams = array(
1641 'activity_id' => $activity->id
,
1642 'case_id' => $caseId,
1644 self
::processCaseActivity($caseParams);
1647 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1648 array(1 => $result['from']['email'])
1655 * Function to retrieve the scheduled activity type and date
1657 * @param array $cases Array of contact and case id
1659 * @return array $activityInfo Array of scheduled activity type and date
1665 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1666 $session = CRM_Core_Session
::singleton();
1667 $userID = $session->get('userID');
1669 $caseID = implode(',', $cases['case_id']);
1670 $contactID = implode(',', $cases['contact_id']);
1673 AND civicrm_case_contact.contact_id IN( {$contactID} )
1674 AND civicrm_case.id IN( {$caseID})
1675 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1677 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1679 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1681 $activityInfo = array();
1682 while ($res->fetch()) {
1683 if ($type == 'upcoming') {
1684 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1685 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1688 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1689 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1693 return $activityInfo;
1697 * combine all the exportable fields from the lower levels object
1699 * @return array array of exportable Fields
1703 static function &exportableFields() {
1704 if (!self
::$_exportableFields) {
1705 if (!self
::$_exportableFields) {
1706 self
::$_exportableFields = array();
1709 $fields = CRM_Case_DAO_Case
::export();
1710 $fields['case_role'] = array('title' => ts('Role in Case'));
1711 $fields['case_type'] = array(
1712 'title' => ts('Case Type'),
1713 'name' => 'case_type',
1715 $fields['case_status'] = array(
1716 'title' => ts('Case Status'),
1717 'name' => 'case_status',
1720 self
::$_exportableFields = $fields;
1722 return self
::$_exportableFields;
1726 * Restore the record that are associated with this case
1728 * @param int $caseId id of the case to restore
1730 * @return true if success.
1734 static function restoreCase($caseId) {
1735 //restore activities
1736 $activities = self
::getCaseActivityDates($caseId);
1738 foreach ($activities as $value) {
1739 CRM_Activity_BAO_Activity
::restoreActivity($value);
1743 $case = new CRM_Case_DAO_Case();
1744 $case->id
= $caseId;
1745 $case->is_deleted
= 0;
1748 //CRM-7364, enable relationships
1749 self
::enableDisableCaseRelationships($caseId, TRUE);
1753 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1754 $globalContacts = array();
1756 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1757 $settings = $settingsProcessor->run();
1758 if (!empty($settings)) {
1759 $groupInfo['name'] = $settings['groupname'];
1760 if ($groupInfo['name']) {
1761 $searchParams = array('name' => $groupInfo['name']);
1763 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1765 $groupInfo['id'] = $results['id'];
1766 $groupInfo['title'] = $results['title'];
1767 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1768 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1769 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1771 if ($returnOnlyCount) {
1772 return $globalContacts;
1776 foreach ($globalContacts as $idx => $contact) {
1777 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1783 return $globalContacts;
1787 * Convenience function to get both case contacts and global in one array
1789 static function getRelatedAndGlobalContacts($caseId) {
1790 $relatedContacts = self
::getRelatedContacts($caseId);
1792 $groupInfo = array();
1793 $globalContacts = self
::getGlobalContacts($groupInfo);
1795 //unset values which are not required.
1796 foreach ($globalContacts as $k => & $v) {
1797 unset($v['email_id']);
1798 unset($v['group_contact_id']);
1799 unset($v['status']);
1801 $v['role'] = $groupInfo['title'];
1803 //include multiple listings for the same contact/different roles.
1804 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1805 return $relatedGlobalContacts;
1809 * Function to get Case ActivitiesDueDates with given criteria.
1811 * @param int $caseID case id
1812 * @param array $criteriaParams given criteria
1813 * @param boolean $latestDate if set newest or oldest date is selceted.
1815 * @return returns case activities due dates
1819 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1821 $selectDate = " ca.activity_date_time";
1822 $where = $groupBy = ' ';
1829 if (!empty($criteriaParams['activity_type_id'])) {
1830 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1831 $where .= " AND ca.is_current_revision = 1";
1832 $groupBy .= " GROUP BY ca.activity_type_id";
1835 if (!empty($criteriaParams['newest'])) {
1836 $selectDate = " max(ca.activity_date_time) ";
1839 $selectDate = " min(ca.activity_date_time) ";
1843 $query = "SELECT ca.id, {$selectDate} as activity_date
1844 FROM civicrm_activity ca
1845 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1846 WHERE cc.id = %1 {$where} {$groupBy}";
1848 $params = array(1 => array($caseID, 'Integer'));
1849 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1851 while ($dao->fetch()) {
1852 $values[$dao->id
]['id'] = $dao->id
;
1853 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1860 * Function to create activities when Case or Other roles assigned/modified/deleted.
1862 * @param int $caseID case id
1863 * @param int $relationshipId relationship id
1864 * @param int $relContactId case role assignee contactId.
1866 * @return void on success creates activity and case activity
1870 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1871 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1875 $queryParam = array();
1876 if (is_array($relationshipId)) {
1877 $relationshipId = implode(',', $relationshipId);
1878 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1881 $relationshipClause = " civicrm_relationship.id = %1";
1882 $queryParam[1] = array($relationshipId, 'Positive');
1886 SELECT cc.display_name as clientName,
1887 cca.display_name as assigneeContactName,
1888 civicrm_relationship.case_id as caseId,
1889 civicrm_relationship_type.label_a_b as relation_a_b,
1890 civicrm_relationship_type.label_b_a as relation_b_a,
1891 civicrm_relationship.contact_id_b as rel_contact_id,
1892 civicrm_relationship.contact_id_a as assign_contact_id
1893 FROM civicrm_relationship_type, civicrm_relationship
1894 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1895 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1896 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1898 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1900 while ($dao->fetch()) {
1901 //to get valid assignee contact(s).
1902 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1903 $caseRelationship = $dao->relation_a_b
;
1904 $assigneContactName = $dao->clientName
;
1905 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1908 $caseRelationship = $dao->relation_b_a
;
1909 $assigneContactName = $dao->assigneeContactName
;
1910 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1914 $session = CRM_Core_Session
::singleton();
1915 $activityParams = array(
1916 'source_contact_id' => $session->get('userID'),
1917 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1918 'activity_date_time' => date('YmdHis'),
1919 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1922 //if $relContactId is passed, role is added or modified.
1923 if (!empty($relContactId)) {
1924 $activityParams['assignee_contact_id'] = $assigneContactIds;
1926 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1932 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1938 $activityParams['activity_type_id'] = $activityTypeID;
1940 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1942 //create case_activity record.
1943 $caseParams = array(
1944 'activity_id' => $activity->id
,
1945 'case_id' => $caseId,
1948 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1952 * Function to get case manger
1953 * contact which is assigned a case role of case manager.
1955 * @param int $caseType case type
1956 * @param int $caseId case id
1958 * @return array $caseManagerContact array of contact on success otherwise empty
1962 static function getCaseManagerContact($caseType, $caseId) {
1963 if (!$caseType ||
!$caseId) {
1967 $caseManagerContact = array();
1968 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1970 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1972 if (!empty($managerRoleId)) {
1973 $managerRoleQuery = "
1974 SELECT civicrm_contact.id as casemanager_id,
1975 civicrm_contact.sort_name as casemanager
1976 FROM civicrm_contact
1977 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1978 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1979 WHERE civicrm_case.id = %2";
1981 $managerRoleParams = array(
1982 1 => array($managerRoleId, 'Integer'),
1983 2 => array($caseId, 'Integer'),
1986 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1987 if ($dao->fetch()) {
1988 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1989 $caseManagerContact['casemanager'] = $dao->casemanager
;
1993 return $caseManagerContact;
1997 * Get all cases with no end dates
1999 * @return array of case and related data keyed on case id
2001 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
2002 //params from ajax call.
2003 $where = array('( ca.end_date is null )');
2004 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
2005 $where[] = "( ov.label LIKE '%$caseType%' )";
2007 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
2008 $config = CRM_Core_Config
::singleton();
2009 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
2010 $where[] = "( sort_name LIKE '$search' )";
2012 if (is_array($excludeCaseIds) &&
2013 !CRM_Utils_System
::isNull($excludeCaseIds)
2015 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2017 if ($excludeDeleted) {
2018 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2021 //filter for permissioned cases.
2022 $filterCases = array();
2023 $doFilterCases = FALSE;
2024 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2025 $doFilterCases = TRUE;
2026 $session = CRM_Core_Session
::singleton();
2027 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2029 $whereClause = implode(' AND ', $where);
2032 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
2033 $limitClause = "LIMIT 0, $limit";
2037 SELECT c.id as contact_id,
2040 ca.subject as case_subject,
2041 ov.label as case_type,
2042 ca.start_date as start_date
2043 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2044 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2045 INNER JOIN civicrm_option_group og ON og.name='case_type'
2046 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2047 WHERE {$whereClause}
2048 ORDER BY c.sort_name
2051 $dao = CRM_Core_DAO
::executeQuery($query);
2052 $unclosedCases = array();
2053 while ($dao->fetch()) {
2054 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2057 $unclosedCases[$dao->id
] = array(
2058 'sort_name' => $dao->sort_name
,
2059 'case_type' => $dao->case_type
,
2060 'contact_id' => $dao->contact_id
,
2061 'start_date' => $dao->start_date
,
2062 'case_subject' => $dao->case_subject
,
2067 return $unclosedCases;
2070 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2071 $whereConditions = array();
2072 if ($excludeDeleted) {
2073 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2076 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2078 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2079 static $accessibleCaseIds;
2080 if (!is_array($accessibleCaseIds)) {
2081 $session = CRM_Core_Session
::singleton();
2082 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID'), 'any'));
2084 //no need of further processing.
2085 if (empty($accessibleCaseIds)) {
2088 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2092 if (!empty($whereConditions)) {
2093 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2097 SELECT count( civicrm_case.id )
2099 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2102 return CRM_Core_DAO
::singleValueQuery($query);
2106 * Retrieve cases related to particular contact.
2108 * @param int $contactId contact id
2109 * @param boolean $excludeDeleted do not include deleted cases.
2111 * @return an array of cases.
2115 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2121 $whereClause = "civicrm_case_contact.contact_id = %1";
2122 if ($excludeDeleted) {
2123 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2127 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2129 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2130 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2131 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2132 AND case_type_og.id = case_type_ov.option_group_id )
2133 WHERE {$whereClause}";
2135 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2136 while ($dao->fetch()) {
2137 $cases[$dao->id
] = array(
2138 'case_id' => $dao->id
,
2139 'case_type' => $dao->case_type
,
2140 'case_start_date' => $dao->start_date
,
2149 * Retrieve related cases for give case.
2151 * @param int $mainCaseId id of main case
2152 * @param int $contactId id of contact
2153 * @param boolean $excludeDeleted do not include deleted cases.
2155 * @return an array of related cases.
2159 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2160 //FIXME : do check for permissions.
2162 $relatedCases = array();
2163 if (!$mainCaseId ||
!$contactId) {
2164 return $relatedCases;
2167 $linkActType = array_search('Link Cases',
2168 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2170 if (!$linkActType) {
2171 return $relatedCases;
2174 $whereClause = "mainCase.id = %2";
2175 if ($excludeDeleted) {
2176 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2179 //1. first fetch related case ids.
2181 SELECT relCaseAct.case_id
2182 FROM civicrm_case mainCase
2183 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2184 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2185 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2186 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2187 WHERE $whereClause";
2189 $dao = CRM_Core_DAO
::executeQuery($query, array(
2190 1 => array($linkActType, 'Integer'),
2191 2 => array($mainCaseId, 'Integer'),
2193 $relatedCaseIds = array();
2194 while ($dao->fetch()) {
2195 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2199 // there are no related cases.
2200 if (empty($relatedCaseIds)) {
2201 return $relatedCases;
2204 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2205 if ($excludeDeleted) {
2206 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2209 //filter for permissioned cases.
2210 $filterCases = array();
2211 $doFilterCases = FALSE;
2212 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2213 $doFilterCases = TRUE;
2214 $session = CRM_Core_Session
::singleton();
2215 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2218 //2. fetch the details of related cases.
2220 SELECT relCase.id as id,
2221 case_type_ov.label as case_type,
2222 client.display_name as client_name,
2223 client.id as client_id
2224 FROM civicrm_case relCase
2225 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2226 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2227 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2228 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2229 AND case_type_og.id = case_type_ov.option_group_id )
2230 WHERE {$whereClause}";
2232 $dao = CRM_Core_DAO
::executeQuery($query);
2233 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2234 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2236 while ($dao->fetch()) {
2238 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2239 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2240 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2241 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2243 $clientView = $dao->client_name
;
2244 if ($hasViewContact) {
2245 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2248 $relatedCases[$dao->id
] = array(
2249 'case_id' => $dao->id
,
2250 'case_type' => $dao->case_type
,
2251 'client_name' => $clientView,
2252 'links' => $caseView,
2257 return $relatedCases;
2261 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2263 * @see CRM_Dedupe_Merger::cpTables()
2265 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2267 static function mergeContacts($mainContactId, $otherContactId) {
2268 self
::mergeCases($mainContactId, NULL, $otherContactId);
2272 * Function perform two task.
2273 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2274 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2276 * @param int $mainContactId contact id of main contact record.
2277 * @param int $mainCaseId case id of main case record.
2278 * @param int $otherContactId contact id of record which is going to merge.
2279 * @param int $otherCaseId case id of record which is going to merge.
2284 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2285 $otherCaseId = NULL, $changeClient = FALSE) {
2286 $moveToTrash = TRUE;
2288 $duplicateContacts = FALSE;
2289 if ($mainContactId && $otherContactId &&
2290 $mainContactId != $otherContactId
2292 $duplicateContacts = TRUE;
2295 $duplicateCases = FALSE;
2296 if ($mainCaseId && $otherCaseId &&
2297 $mainCaseId != $otherCaseId
2299 $duplicateCases = TRUE;
2302 $mainCaseIds = array();
2303 if (!$duplicateContacts && !$duplicateCases) {
2304 return $mainCaseIds;
2307 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2308 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2309 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2310 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2311 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2312 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2314 $processCaseIds = array($otherCaseId);
2315 if ($duplicateContacts && !$duplicateCases) {
2316 if ($changeClient) {
2317 $processCaseIds = array($mainCaseId);
2320 //get all case ids for other contact.
2321 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2323 if (!is_array($processCaseIds)) {
2328 $session = CRM_Core_Session
::singleton();
2329 $currentUserId = $session->get('userID');
2331 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2333 // copy all cases and connect to main contact id.
2334 foreach ($processCaseIds as $otherCaseId) {
2335 if ($duplicateContacts) {
2336 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2337 $mainCaseId = $mainCase->id
;
2342 // CRM-11662 Copy Case custom data
2343 $extends = array('case');
2344 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2346 foreach ($groupTree as $groupID => $group) {
2347 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2348 foreach ($group['fields'] as $fieldID => $field) {
2349 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2353 foreach ($table as $tableName => $tableColumns) {
2354 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2355 $tableColumns[0] = $mainCaseId;
2356 $select = 'SELECT ' . implode(', ', $tableColumns);
2357 $from = ' FROM ' . $tableName;
2358 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2359 $query = $insert . $select . $from . $where;
2360 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2366 $mainCaseIds[] = $mainCaseId;
2367 //insert record for case contact.
2368 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2369 $otherCaseContact->case_id
= $otherCaseId;
2370 $otherCaseContact->find();
2371 while ($otherCaseContact->fetch()) {
2372 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2373 $mainCaseContact->case_id
= $mainCaseId;
2374 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2375 if ($mainCaseContact->contact_id
== $otherContactId) {
2376 $mainCaseContact->contact_id
= $mainContactId;
2378 //avoid duplicate object.
2379 if (!$mainCaseContact->find(TRUE)) {
2380 $mainCaseContact->save();
2382 $mainCaseContact->free();
2384 $otherCaseContact->free();
2386 elseif (!$otherContactId) {
2387 $otherContactId = $mainContactId;
2390 if (!$mainCaseId ||
!$otherCaseId ||
2391 !$mainContactId ||
!$otherContactId
2396 // get all activities for other case.
2397 $otherCaseActivities = array();
2398 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2400 //for duplicate cases do not process singleton activities.
2401 $otherActivityIds = $singletonActivityIds = array();
2402 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2403 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2404 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2407 $otherActivityIds[] = $otherActId;
2409 if ($duplicateCases) {
2410 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2413 FROM civicrm_activity
2414 WHERE activity_type_id = $openCaseType
2415 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2416 $dao = CRM_Core_DAO
::executeQuery($sql);
2417 while ($dao->fetch()) {
2418 $singletonActivityIds[] = $dao->id
;
2424 // migrate all activities and connect to main contact.
2425 $copiedActivityIds = $activityMappingIds = array();
2426 sort($otherActivityIds);
2427 foreach ($otherActivityIds as $otherActivityId) {
2429 //for duplicate cases -
2430 //do not migrate singleton activities.
2431 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2435 //migrate activity record.
2436 $otherActivity = new CRM_Activity_DAO_Activity();
2437 $otherActivity->id
= $otherActivityId;
2438 if (!$otherActivity->find(TRUE)) {
2442 $mainActVals = array();
2443 $mainActivity = new CRM_Activity_DAO_Activity();
2444 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2445 $mainActivity->copyValues($mainActVals);
2446 $mainActivity->id
= NULL;
2447 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2448 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2452 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2456 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2459 $mainActivity->save();
2460 $mainActivityId = $mainActivity->id
;
2461 if (!$mainActivityId) {
2465 $activityMappingIds[$otherActivityId] = $mainActivityId;
2466 // insert log of all activities
2467 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2469 $otherActivity->free();
2470 $mainActivity->free();
2471 $copiedActivityIds[] = $otherActivityId;
2473 //create case activity record.
2474 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2475 $mainCaseActivity->case_id
= $mainCaseId;
2476 $mainCaseActivity->activity_id
= $mainActivityId;
2477 $mainCaseActivity->save();
2478 $mainCaseActivity->free();
2480 //migrate source activity.
2481 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2482 $otherSourceActivity->activity_id
= $otherActivityId;
2483 $otherSourceActivity->record_type_id
= $sourceID;
2484 $otherSourceActivity->find();
2485 while ($otherSourceActivity->fetch()) {
2486 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2487 $mainActivitySource->record_type_id
= $sourceID;
2488 $mainActivitySource->activity_id
= $mainActivityId;
2489 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2490 if ($mainActivitySource->contact_id
== $otherContactId) {
2491 $mainActivitySource->contact_id
= $mainContactId;
2493 //avoid duplicate object.
2494 if (!$mainActivitySource->find(TRUE)) {
2495 $mainActivitySource->save();
2497 $mainActivitySource->free();
2499 $otherSourceActivity->free();
2501 //migrate target activities.
2502 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2503 $otherTargetActivity->activity_id
= $otherActivityId;
2504 $otherTargetActivity->record_type_id
= $targetID;
2505 $otherTargetActivity->find();
2506 while ($otherTargetActivity->fetch()) {
2507 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2508 $mainActivityTarget->record_type_id
= $targetID;
2509 $mainActivityTarget->activity_id
= $mainActivityId;
2510 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2511 if ($mainActivityTarget->contact_id
== $otherContactId) {
2512 $mainActivityTarget->contact_id
= $mainContactId;
2514 //avoid duplicate object.
2515 if (!$mainActivityTarget->find(TRUE)) {
2516 $mainActivityTarget->save();
2518 $mainActivityTarget->free();
2520 $otherTargetActivity->free();
2522 //migrate assignee activities.
2523 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2524 $otherAssigneeActivity->activity_id
= $otherActivityId;
2525 $otherAssigneeActivity->record_type_id
= $assigneeID;
2526 $otherAssigneeActivity->find();
2527 while ($otherAssigneeActivity->fetch()) {
2528 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2529 $mainAssigneeActivity->activity_id
= $mainActivityId;
2530 $mainAssigneeActivity->record_type_id
= $assigneeID;
2531 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2532 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2533 $mainAssigneeActivity->contact_id
= $mainContactId;
2535 //avoid duplicate object.
2536 if (!$mainAssigneeActivity->find(TRUE)) {
2537 $mainAssigneeActivity->save();
2539 $mainAssigneeActivity->free();
2541 $otherAssigneeActivity->free();
2543 // copy custom fields and attachments
2545 'activityID' => $otherActivityId,
2546 'mainActivityId' => $mainActivityId,
2548 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2551 //copy case relationship.
2552 if ($duplicateContacts) {
2553 //migrate relationship records.
2554 $otherRelationship = new CRM_Contact_DAO_Relationship();
2555 $otherRelationship->case_id
= $otherCaseId;
2556 $otherRelationship->find();
2557 $otherRelationshipIds = array();
2558 while ($otherRelationship->fetch()) {
2559 $otherRelVals = array();
2560 $updateOtherRel = FALSE;
2561 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2563 $mainRelationship = new CRM_Contact_DAO_Relationship();
2564 $mainRelationship->copyValues($otherRelVals);
2565 $mainRelationship->id
= NULL;
2566 $mainRelationship->case_id
= $mainCaseId;
2567 if ($mainRelationship->contact_id_a
== $otherContactId) {
2568 $updateOtherRel = TRUE;
2569 $mainRelationship->contact_id_a
= $mainContactId;
2572 //case creator change only when we merge user contact.
2573 if ($mainRelationship->contact_id_b
== $otherContactId) {
2574 //do not change creator for change client.
2575 if (!$changeClient) {
2576 $updateOtherRel = TRUE;
2577 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2580 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2581 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2583 //avoid duplicate object.
2584 if (!$mainRelationship->find(TRUE)) {
2585 $mainRelationship->save();
2587 $mainRelationship->free();
2589 //get the other relationship ids to update end date.
2590 if ($updateOtherRel) {
2591 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2594 $otherRelationship->free();
2596 //update other relationships end dates
2597 if (!empty($otherRelationshipIds)) {
2598 $sql = 'UPDATE civicrm_relationship
2599 SET end_date = CURDATE()
2600 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2601 CRM_Core_DAO
::executeQuery($sql);
2605 //move other case to trash.
2606 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2611 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2612 if ($changeClient) {
2613 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2614 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2616 $mergeActType = array_search('Reassigned Case', $activityTypes);
2617 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2620 2 => $otherContactDisplayName,
2621 3 => $mainContactDisplayName,
2626 elseif ($duplicateContacts) {
2627 $mergeActType = array_search('Merge Case', $activityTypes);
2628 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2631 2 => $otherContactId,
2632 3 => $mainContactId,
2638 $mergeActType = array_search('Merge Case', $activityTypes);
2639 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2640 if (!empty($copiedActivityIds)) {
2642 SELECT id, subject, activity_date_time, activity_type_id
2643 FROM civicrm_activity
2644 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2645 $dao = CRM_Core_DAO
::executeQuery($sql);
2646 while ($dao->fetch()) {
2647 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2648 if ($dao->subject
) {
2649 $mergeActSubjectDetails .= " :: {$dao->subject}";
2651 $mergeActSubjectDetails .= "<br />";
2656 //create merge activity record.
2657 $activityParams = array(
2658 'subject' => $mergeActSubject,
2659 'details' => $mergeActSubjectDetails,
2660 'status_id' => array_search('Completed', $activityStatuses),
2661 'activity_type_id' => $mergeActType,
2662 'source_contact_id' => $mainContactId,
2663 'activity_date_time' => date('YmdHis'),
2666 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2667 $mergeActivityId = $mergeActivity->id
;
2668 if (!$mergeActivityId) {
2671 $mergeActivity->free();
2673 //connect merge activity to case.
2674 $mergeCaseAct = array(
2675 'case_id' => $mainCaseId,
2676 'activity_id' => $mergeActivityId,
2679 self
::processCaseActivity($mergeCaseAct);
2682 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2684 return $mainCaseIds;
2688 * Validate contact permission for
2689 * edit/view on activity record and build links.
2691 * @param array $tplParams params to be sent to template for sending email.
2692 * @param array $activityParams info of the activity.
2697 static function buildPermissionLinks(&$tplParams, $activityParams) {
2698 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2699 'activity_type_id', 'id'
2702 if (!empty($tplParams['isCaseActivity'])) {
2703 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2704 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2707 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2708 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2711 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2712 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2716 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2717 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2720 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2721 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2727 * Validate contact permission for
2728 * given operation on activity record.
2730 * @param int $activityId activity record id.
2731 * @param string $operation user operation.
2732 * @param int $actTypeId activity type id.
2733 * @param int $contactId contact id/if not pass consider logged in
2734 * @param boolean $checkComponent do we need to check component enabled.
2736 * @return boolean $allow true/false
2739 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2741 if (!$actTypeId && $activityId) {
2742 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2745 if (!$activityId ||
!$operation ||
!$actTypeId) {
2749 //do check for civicase component enabled.
2750 if ($checkComponent) {
2751 static $componentEnabled;
2752 if (!isset($componentEnabled)) {
2753 $config = CRM_Core_Config
::singleton();
2754 $componentEnabled = FALSE;
2755 if (in_array('CiviCase', $config->enableComponents
)) {
2756 $componentEnabled = TRUE;
2759 if (!$componentEnabled) {
2764 //do check for cases.
2765 $caseActOperations = array(
2772 if (in_array($operation, $caseActOperations)) {
2773 static $unclosedCases;
2774 if (!is_array($unclosedCases)) {
2775 $unclosedCases = self
::getUnclosedCases();
2777 if ($operation == 'File On Case') {
2778 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2781 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2785 $actionOperations = array('view', 'edit', 'delete');
2786 if (in_array($operation, $actionOperations)) {
2788 //do cache when user has non/supper permission.
2789 static $allowOperations;
2791 if (!is_array($allowOperations) ||
2792 !array_key_exists($operation, $allowOperations)
2796 $session = CRM_Core_Session
::singleton();
2797 $contactId = $session->get('userID');
2800 //check for permissions.
2801 $permissions = array(
2803 'access my cases and activities',
2804 'access all cases and activities',
2807 'access my cases and activities',
2808 'access all cases and activities',
2810 'delete' => array('delete activities'),
2813 //check for core permission.
2814 $hasPermissions = array();
2815 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2816 if (is_array($checkPermissions)) {
2817 foreach ($checkPermissions as $per) {
2818 if (CRM_Core_Permission
::check($per)) {
2819 $hasPermissions[$operation][] = $per;
2825 if (!empty($hasPermissions)) {
2826 //need to check activity object specific.
2827 if (in_array($operation, array(
2832 //do we have supper permission.
2833 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2834 $allowOperations[$operation] = $allow = TRUE;
2837 //user has only access to my cases and activity.
2838 //here object specific permmions come in picture.
2840 //edit - contact must be source or assignee
2841 //view - contact must be source/assignee/target
2842 $isTarget = $isAssignee = $isSource = FALSE;
2843 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2844 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2845 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2846 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2848 $target = new CRM_Activity_DAO_ActivityContact();
2849 $target->record_type_id
= $targetID;
2850 $target->activity_id
= $activityId;
2851 $target->contact_id
= $contactId;
2852 if ($target->find(TRUE)) {
2856 $assignee = new CRM_Activity_DAO_ActivityContact();
2857 $assignee->activity_id
= $activityId;
2858 $assignee->record_type_id
= $assigneeID;
2859 $assignee->contact_id
= $contactId;
2860 if ($assignee->find(TRUE)) {
2864 $source = new CRM_Activity_DAO_ActivityContact();
2865 $source->activity_id
= $activityId;
2866 $source->record_type_id
= $sourceID;
2867 $source->contact_id
= $contactId;
2868 if ($source->find(TRUE)) {
2872 if ($operation == 'edit') {
2873 if ($isAssignee ||
$isSource) {
2877 if ($operation == 'view') {
2878 if ($isTarget ||
$isAssignee ||
$isSource) {
2884 elseif (is_array($hasPermissions[$operation])) {
2885 $allowOperations[$operation] = $allow = TRUE;
2889 //contact do not have permission.
2890 $allowOperations[$operation] = FALSE;
2895 //here contact might have supper/non permission.
2896 $allow = $allowOperations[$operation];
2900 //do further only when operation is granted.
2902 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2904 //get the activity type name.
2905 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2907 //do not allow multiple copy / edit action.
2908 $singletonNames = array(
2918 //do not allow to delete these activities, CRM-4543
2919 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2921 //allow edit operation.
2922 $allowEditNames = array('Open Case');
2924 // do not allow File on Case
2925 $doNotFileNames = array(
2928 'Change Case Status',
2929 'Change Case Start Date',
2936 if (in_array($actTypeName, $singletonNames)) {
2938 if ($operation == 'File On Case') {
2939 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2941 if (in_array($operation, $actionOperations)) {
2943 if ($operation == 'edit') {
2944 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2946 elseif ($operation == 'delete') {
2947 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2951 if ($allow && ($operation == 'delete') &&
2952 in_array($actTypeName, $doNotDeleteNames)
2957 if ($allow && ($operation == 'File On Case') &&
2958 in_array($actTypeName, $doNotFileNames)
2963 //check settings file for masking actions
2964 //on the basis the activity types
2965 //hide Edit link if activity type is NOT editable
2966 //(special case activities).CRM-5871
2967 if ($allow && in_array($operation, $actionOperations)) {
2968 static $actionFilter = array();
2969 if (!array_key_exists($operation, $actionFilter)) {
2970 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2971 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2973 if (array_key_exists($operation, $actionFilter[$operation]) &&
2974 in_array($actTypeId, $actionFilter[$operation][$operation])
2985 * since we drop 'access CiviCase', allow access
2986 * if user has 'access my cases and activities'
2987 * or 'access all cases and activities'
2989 static function accessCiviCase() {
2990 static $componentEnabled;
2991 if (!isset($componentEnabled)) {
2992 $componentEnabled = FALSE;
2993 $config = CRM_Core_Config
::singleton();
2994 if (in_array('CiviCase', $config->enableComponents
)) {
2995 $componentEnabled = TRUE;
2998 if (!$componentEnabled) {
3002 if (CRM_Core_Permission
::check('access my cases and activities') ||
3003 CRM_Core_Permission
::check('access all cases and activities')
3012 * Function to check whether activity is a case Activity
3014 * @param int $activityID activity id
3016 * @return boolean $isCaseActivity true/false
3018 static function isCaseActivity($activityID) {
3019 $isCaseActivity = FALSE;
3021 $params = array(1 => array($activityID, 'Integer'));
3022 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3023 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
3024 $isCaseActivity = TRUE;
3028 return $isCaseActivity;
3032 * Function to get all the case type ids currently in use
3035 * @return array $caseTypeIds
3037 static function getUsedCaseType() {
3038 static $caseTypeIds;
3040 if (!is_array($caseTypeIds)) {
3041 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3043 $dao = CRM_Core_DAO
::executeQuery($query);
3044 $caseTypeIds = array();
3045 while ($dao->fetch()) {
3046 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3049 $caseTypeIds[] = $typeId[1];
3053 return $caseTypeIds;
3057 * Function to get all the case status ids currently in use
3060 * @return array $caseStatusIds
3062 static function getUsedCaseStatuses() {
3063 static $caseStatusIds;
3065 if (!is_array($caseStatusIds)) {
3066 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3068 $dao = CRM_Core_DAO
::executeQuery($query);
3069 $caseStatusIds = array();
3070 while ($dao->fetch()) {
3071 $caseStatusIds[] = $dao->status_id
;
3075 return $caseStatusIds;
3079 * Function to get all the encounter medium ids currently in use
3082 static function getUsedEncounterMediums() {
3085 if (!is_array($mediumIds)) {
3086 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3088 $dao = CRM_Core_DAO
::executeQuery($query);
3089 $mediumIds = array();
3090 while ($dao->fetch()) {
3091 $mediumIds[] = $dao->medium_id
;
3099 * Function to check case configuration.
3101 * @return array $configured
3103 static function isCaseConfigured($contactId = NULL) {
3104 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3106 //lets check for case configured.
3107 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3108 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3109 if (!$configured['configured']) {
3110 //do check for case type and case status.
3111 $caseTypes = CRM_Case_PseudoConstant
::caseType('label', FALSE);
3112 if (!empty($caseTypes)) {
3113 $configured['configured'] = TRUE;
3114 if (!$configured['configured']) {
3115 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3116 if (!empty($caseStatuses)) {
3117 $configured['configured'] = TRUE;
3122 if ($configured['configured']) {
3123 //do check for active case type and case status.
3124 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3125 if (!empty($caseTypes)) {
3126 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3127 if (!empty($caseStatuses)) {
3128 $configured['allowToAddNewCase'] = TRUE;
3132 //do we need to redirect user to case admin.
3133 if (!$configured['allowToAddNewCase'] && $contactId) {
3134 //check for current contact case count.
3135 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3136 //redirect user to case admin page.
3137 if (!$currentContatCasesCount) {
3138 $configured['redirectToCaseAdmin'] = TRUE;
3147 * Used during case component enablement and during ugprade
3149 static function createCaseViews() {
3150 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
3151 $dao = new CRM_Core_DAO();
3153 $sql = self
::createCaseViewsQuery('upcoming');
3155 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3159 // Above error doesn't get caught?
3160 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3161 if (is_null($doublecheck)) {
3165 $sql = self
::createCaseViewsQuery('recent');
3167 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3171 // Above error doesn't get caught?
3172 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3173 if (is_null($doublecheck)) {
3181 * helper function, also used by the upgrade in case of error
3183 static function createCaseViewsQuery($section = 'upcoming') {
3185 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3188 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3189 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3190 FROM civicrm_case_activity ca
3191 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3192 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3193 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3197 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3198 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3199 FROM civicrm_case_activity ca
3200 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3201 WHERE a.activity_date_time <= NOW()
3202 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3203 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3210 * Function to add/copy relationships, when new client is added for a case
3212 * @param int $caseId case id
3213 * @param int $contactId contact id / new client id
3217 static function addCaseRelationships($caseId, $contactId) {
3218 // get the case role / relationships for the case
3219 $caseRelationships = new CRM_Contact_DAO_Relationship();
3220 $caseRelationships->case_id
= $caseId;
3221 $caseRelationships->find();
3222 $relationshipTypes = array();
3224 // make sure we don't add duplicate relationships of same relationship type.
3225 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3227 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3229 // add relationship for new client.
3230 $newRelationship = new CRM_Contact_DAO_Relationship();
3231 $newRelationship->copyValues($values);
3232 $newRelationship->id
= NULL;
3233 $newRelationship->case_id
= $caseId;
3234 $newRelationship->contact_id_a
= $contactId;
3235 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3236 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3238 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3239 if (!$newRelationship->find(TRUE)) {
3240 $newRelationship->save();
3242 $newRelationship->free();
3244 // store relationship type of newly created relationship
3245 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3250 * Function to get the list of clients for a case
3252 * @param int $caseId
3254 * @return array $clients associated array with client ids
3257 static function getCaseClients($caseId) {
3259 $caseContact = new CRM_Case_DAO_CaseContact();
3260 $caseContact->case_id
= $caseId;
3261 $caseContact->find();
3263 while ($caseContact->fetch()) {
3264 $clients[] = $caseContact->contact_id
;
3271 * Get options for a given case field.
3272 * @see CRM_Core_DAO::buildOptions
3274 * @param String $fieldName
3275 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3276 * @param Array $props: whatever is known about this dao object
3278 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3279 $className = __CLASS__
;
3281 switch ($fieldName) {
3282 // This field is not part of this object but the api supports it
3284 $className = 'CRM_Activity_BAO_Activity';
3287 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);