3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class contains the functions for Case Management
40 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
43 * static field for all the case information that we can potentially export
48 static $_exportableFields = NULL;
50 function __construct() {
51 parent
::__construct();
55 * takes an associative array and creates a case object
57 * the function extract all the params it needs to initialize the create a
58 * case object. the params array could contain additional unused name/value
61 * @param array $params (reference ) an assoc array of name/value pairs
62 * @param array $ids the array that holds all the db ids
64 * @return object CRM_Case_BAO_Case object
68 static function add(&$params) {
69 $caseDAO = new CRM_Case_DAO_Case();
70 $caseDAO->copyValues($params);
71 return $caseDAO->save();
75 * Given the list of params in the params array, fetch the object
76 * and store the values in the values array
78 * @param array $params input parameters to find object
79 * @param array $values output values of the object
80 * @param array $ids the array that holds all the db ids
82 * @return CRM_Case_BAO_Case|null the found object or null
86 static function &getValues(&$params, &$values, &$ids) {
87 $case = new CRM_Case_BAO_Case();
89 $case->copyValues($params);
91 if ($case->find(TRUE)) {
92 $ids['case'] = $case->id
;
93 CRM_Core_DAO
::storeValues($case, $values);
100 * takes an associative array and creates a case object
102 * @param array $params (reference ) an assoc array of name/value pairs
103 * @param array $ids the array that holds all the db ids
105 * @return object CRM_Case_BAO_Case object
109 static function &create(&$params) {
110 $transaction = new CRM_Core_Transaction();
112 if (CRM_Utils_Array
::value('id', $params)) {
113 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
116 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
119 $case = self
::add($params);
121 if (CRM_Utils_Array
::value('custom', $params) &&
122 is_array($params['custom'])
124 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
127 if (is_a($case, 'CRM_Core_Error')) {
128 $transaction->rollback();
132 if (CRM_Utils_Array
::value('id', $params)) {
133 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
136 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
138 $transaction->commit();
140 //we are not creating log for case
141 //since case log can be tracked using log for activity.
146 * Create case contact record
148 * @param array case_id, contact_id
153 static function addCaseToContact($params) {
154 $caseContact = new CRM_Case_DAO_CaseContact();
155 $caseContact->case_id
= $params['case_id'];
156 $caseContact->contact_id
= $params['contact_id'];
157 $caseContact->find(TRUE);
158 $caseContact->save();
160 // add to recently viewed
161 $caseType = CRM_Case_PseudoConstant
::caseTypeName($caseContact->case_id
, 'label');
162 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
163 "action=view&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
166 $title = CRM_Contact_BAO_Contact
::displayName($caseContact->contact_id
) . ' - ' . $caseType['name'];
168 $recentOther = array();
169 if (CRM_Core_Permission
::checkActionPermission('CiviCase', CRM_Core_Action
::DELETE
)) {
170 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/case',
171 "action=delete&reset=1&id={$caseContact->case_id}&cid={$caseContact->contact_id}&context=home"
175 // add the recently created case
176 CRM_Utils_Recent
::add($title,
178 $caseContact->case_id
,
180 $params['contact_id'],
189 * Delet case contact record
196 static function deleteCaseContact($caseID) {
197 $caseContact = new CRM_Case_DAO_CaseContact();
198 $caseContact->case_id
= $caseID;
199 $caseContact->delete();
201 // delete the recently created Case
206 CRM_Utils_Recent
::del($caseRecent);
210 * This function is used to convert associative array names to values
213 * This function is used by both the web form layer and the api. Note that
214 * the api needs the name => value conversion, also the view layer typically
215 * requires value => name conversion
217 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
218 $id = $property . '_id';
220 $src = $reverse ?
$property : $id;
221 $dst = $reverse ?
$id : $property;
223 if (!array_key_exists($src, $defaults)) {
227 $look = $reverse ?
array_flip($lookup) : $lookup;
229 if (is_array($look)) {
230 if (!array_key_exists($defaults[$src], $look)) {
234 $defaults[$dst] = $look[$defaults[$src]];
239 * Takes a bunch of params that are needed to match certain criteria and
240 * retrieves the relevant objects. We'll tweak this function to be more
241 * full featured over a period of time. This is the inverse function of
242 * create. It also stores all the retrieved values in the default array
244 * @param array $params (reference ) an assoc array of name/value pairs
245 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
246 * in a hierarchical manner
247 * @param array $ids (reference) the array that holds all the db ids
249 * @return object CRM_Case_BAO_Case object
253 static function retrieve(&$params, &$defaults, &$ids) {
254 $case = CRM_Case_BAO_Case
::getValues($params, $defaults, $ids);
259 * Function to process case activity add/delete
260 * takes an associative array and
262 * @param array $params (reference ) an assoc array of name/value pairs
267 static function processCaseActivity(&$params) {
268 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
269 $caseActivityDAO->activity_id
= $params['activity_id'];
270 $caseActivityDAO->case_id
= $params['case_id'];
272 $caseActivityDAO->find(TRUE);
273 $caseActivityDAO->save();
277 * Function to get the case subject for Activity
279 * @param int $activityId activity id
281 * @return case subject or null
285 static function getCaseSubject($activityId) {
286 $caseActivity = new CRM_Case_DAO_CaseActivity();
287 $caseActivity->activity_id
= $activityId;
288 if ($caseActivity->find(TRUE)) {
289 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
295 * Function to get the case type.
303 static function getCaseType($caseId, $colName = 'label') {
312 INNER JOIN civicrm_option_group og ON og.name='case_type'
313 INNER JOIN civicrm_option_value ov ON ( ca.case_type_id=ov.value AND ov.option_group_id=og.id )
316 $params = array(1 => array($caseId, 'Integer'));
318 return CRM_Core_DAO
::singleValueQuery($sql, $params);
322 * Delete the record that are associated with this case
323 * record are deleted from case
325 * @param int $caseId id of the case to delete
331 static function deleteCase($caseId, $moveToTrash = FALSE) {
332 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
335 $activities = self
::getCaseActivityDates($caseId);
337 foreach ($activities as $value) {
338 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
343 $transaction = new CRM_Core_Transaction();
345 $case = new CRM_Case_DAO_Case();
348 $result = $case->delete();
349 $transaction->commit();
352 $result = $case->is_deleted
= 1;
357 // CRM-7364, disable relationships
358 self
::enableDisableCaseRelationships($caseId, FALSE);
360 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
362 // remove case from recent items.
367 CRM_Utils_Recent
::del($caseRecent);
375 * Function to enable disable case related relationships
377 * @param int $caseId case id
378 * @param boolean $enable action
384 static function enableDisableCaseRelationships($caseId, $enable) {
385 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
386 if (!empty($contactIds)) {
387 foreach ($contactIds as $cid) {
388 $roles = self
::getCaseRoles($cid, $caseId);
389 if (!empty($roles)) {
390 $relationshipIds = implode(',', array_keys($roles));
391 $enable = (int) $enable;
392 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
393 WHERE id IN ( {$relationshipIds} )";
394 CRM_Core_DAO
::executeQuery($query);
401 * Delete the activities related to case
403 * @param int $activityId id of the activity
409 static function deleteCaseActivity($activityId) {
410 $case = new CRM_Case_DAO_CaseActivity();
411 $case->activity_id
= $activityId;
416 * Retrieve contact_id by case_id
418 * @param int $caseId ID of the case
424 static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
425 $caseContact = new CRM_Case_DAO_CaseContact();
426 $caseContact->case_id
= $caseId;
427 $caseContact->find();
428 $contactArray = array();
430 while ($caseContact->fetch()) {
431 if ($contactID != $caseContact->contact_id
) {
432 $contactArray[$count] = $caseContact->contact_id
;
437 return $contactArray;
441 * Look up a case using an activity ID
443 * @param $activity_id
445 * @return int, case ID
447 static function getCaseIdByActivityId($activityId) {
448 $originalId = CRM_Core_DAO
::singleValueQuery(
449 'SELECT original_id FROM civicrm_activity WHERE id = %1',
450 array('1' => array($activityId, 'Integer'))
452 $caseId = CRM_Core_DAO
::singleValueQuery(
453 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
455 '1' => array($activityId, 'Integer'),
456 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
463 * Retrieve contact names by caseId
465 * @param int $caseId ID of the case
472 static function getContactNames($caseId) {
473 $contactNames = array();
475 return $contactNames;
479 SELECT contact_a.sort_name name,
480 contact_a.display_name as display_name,
482 contact_a.birth_date as birth_date,
485 FROM civicrm_contact contact_a
486 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
487 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
488 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
489 WHERE civicrm_case_contact.case_id = %1";
491 $dao = CRM_Core_DAO
::executeQuery($query,
492 array(1 => array($caseId, 'Integer'))
494 while ($dao->fetch()) {
495 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
496 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
497 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
498 $contactNames[$dao->cid
]['email'] = $dao->email
;
499 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
500 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
501 $contactNames[$dao->cid
]['role'] = ts('Client');
504 return $contactNames;
508 * Retrieve case_id by contact_id
510 * @param int $contactId ID of the contact
511 * @param boolean $includeDeleted include the deleted cases in result
518 static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE) {
521 FROM civicrm_case_contact cc
522 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
523 WHERE cc.contact_id = %1
525 if (!$includeDeleted) {
526 $query .= " AND ca.is_deleted = 0";
529 $params = array(1 => array($contactID, 'Integer'));
530 $dao = CRM_Core_DAO
::executeQuery($query, $params);
532 $caseArray = array();
533 while ($dao->fetch()) {
534 $caseArray[] = $dao->id
;
541 static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL, $isDeleted = 0) {
543 $session = CRM_Core_Session
::singleton();
544 $userID = $session->get('userID');
547 $actStatus = array_flip(CRM_Core_PseudoConstant
::activityStatus('name'));
548 $scheduledStatusId = $actStatus['Scheduled'];
551 civicrm_case.id as case_id,
552 civicrm_case.subject as case_subject,
553 civicrm_contact.id as contact_id,
554 civicrm_contact.sort_name as sort_name,
555 civicrm_phone.phone as phone,
556 civicrm_contact.contact_type as contact_type,
557 civicrm_contact.contact_sub_type as contact_sub_type,
558 t_act.activity_type_id,
559 cov_type.label as case_type,
560 cov_type.name as case_type_name,
561 cov_status.label as case_status,
562 cov_status.label as case_status_name,
564 civicrm_case.start_date as case_start_date,
565 case_relation_type.label_b_a as case_role, ";
567 if ($type == 'upcoming') {
569 t_act.desired_date as case_scheduled_activity_date,
570 t_act.id as case_scheduled_activity_id,
571 t_act.act_type_name as case_scheduled_activity_type_name,
572 t_act.act_type AS case_scheduled_activity_type ";
574 elseif ($type == 'recent') {
576 t_act.desired_date as case_recent_activity_date,
577 t_act.id as case_recent_activity_id,
578 t_act.act_type_name as case_recent_activity_type_name,
579 t_act.act_type AS case_recent_activity_type ";
581 elseif ( $type == 'any' ) {
583 t_act.desired_date as case_activity_date,
584 t_act.id as case_activity_id,
585 t_act.act_type_name as case_activity_type_name,
586 t_act.act_type AS case_activity_type ";
589 $query .= " FROM civicrm_case
590 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
591 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
593 if ($type == 'upcoming') {
594 // This gets the earliest activity per case that's scheduled within 14 days from now.
595 // 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.
596 // In this case we don't really care which one, so min(id) works.
597 // optimized in CRM-11837
598 $query .= " INNER JOIN
600 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
605 FROM civicrm_view_case_activity_upcoming
606 ORDER BY activity_date_time ASC, id ASC
610 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
611 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
615 elseif ($type == 'recent') {
616 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
617 //improve query performance - CRM-10598
618 $query .= " INNER JOIN
620 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
625 FROM civicrm_view_case_activity_recent
626 ORDER BY activity_date_time DESC, id ASC
630 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
631 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
634 elseif ( $type == 'any' ) {
635 $query .= " LEFT JOIN
637 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
638 FROM civicrm_activity act4
639 LEFT JOIN civicrm_case_activity ca4
640 ON ca4.activity_id = act4.id
641 AND act4.is_current_revision = 1
642 LEFT JOIN civicrm_option_group aog
643 ON aog.name='activity_type'
644 LEFT JOIN civicrm_option_value aov
645 ON aov.option_group_id = aog.id
646 AND aov.value = act4.activity_type_id
651 ON t_act.case_id = civicrm_case.id
652 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
653 LEFT JOIN civicrm_relationship case_relationship
654 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
655 AND case_relationship.case_id = civicrm_case.id )
657 LEFT JOIN civicrm_relationship_type case_relation_type
658 ON ( case_relation_type.id = case_relationship.relationship_type_id
659 AND case_relation_type.id = case_relationship.relationship_type_id )
661 LEFT JOIN civicrm_option_group cog_type
662 ON cog_type.name = 'case_type'
664 LEFT JOIN civicrm_option_value cov_type
665 ON ( civicrm_case.case_type_id = cov_type.value
666 AND cog_type.id = cov_type.option_group_id )
668 LEFT JOIN civicrm_option_group cog_status
669 ON cog_status.name = 'case_status'
671 LEFT JOIN civicrm_option_value cov_status
672 ON ( civicrm_case.status_id = cov_status.value
673 AND cog_status.id = cov_status.option_group_id )
677 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
678 $query .= " WHERE (1) $condition ";
681 if ($type == 'upcoming') {
682 $query .= " ORDER BY case_scheduled_activity_date ASC ";
684 elseif ($type == 'recent') {
685 $query .= " ORDER BY case_recent_activity_date ASC ";
687 elseif ( $type == 'any' ) {
688 $query .= " ORDER BY case_activity_date ASC ";
695 * Retrieve cases related to particular contact or whole contact
696 * used in Dashboad and Tab
698 * @param boolean $allCases
702 * @param String $type /upcoming,recent,all/
704 * @return array Array of Cases
709 static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
711 $casesList = array();
713 //validate access for own cases.
714 if (!self
::accessCiviCase()) {
719 $session = CRM_Core_Session
::singleton();
720 $userID = $session->get('userID');
723 //validate access for all cases.
724 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
729 $condition = " AND civicrm_case.is_deleted = 0 ";
732 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
734 if ( $type == 'upcoming' ||
$type == 'any' ) {
735 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
737 AND civicrm_case.status_id != $closedId";
740 $query = self
::getCaseActivityQuery($type, $userID, $condition);
742 $queryParams = array();
743 $result = CRM_Core_DAO
::executeQuery($query,
747 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
749 $resultFields = array(
766 if ($type == 'upcoming') {
767 $resultFields[] = 'case_scheduled_activity_date';
768 $resultFields[] = 'case_scheduled_activity_type_name';
769 $resultFields[] = 'case_scheduled_activity_type';
770 $resultFields[] = 'case_scheduled_activity_id';
772 elseif ($type == 'recent') {
773 $resultFields[] = 'case_recent_activity_date';
774 $resultFields[] = 'case_recent_activity_type_name';
775 $resultFields[] = 'case_recent_activity_type';
776 $resultFields[] = 'case_recent_activity_id';
778 elseif ( $type == 'any' ) {
779 $resultFields[] = 'case_activity_date';
780 $resultFields[] = 'case_activity_type_name';
781 $resultFields[] = 'case_activity_type';
782 $resultFields[] = 'case_activity_id';
785 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
786 $actions = CRM_Case_Selector_Search
::links();
789 // check is the user has view/edit signer permission
790 $permissions = array(CRM_Core_Permission
::VIEW
);
791 if (CRM_Core_Permission
::check('access all cases and activities') ||
792 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
794 $permissions[] = CRM_Core_Permission
::EDIT
;
796 if (CRM_Core_Permission
::check('delete in CiviCase')) {
797 $permissions[] = CRM_Core_Permission
::DELETE
;
799 $mask = CRM_Core_Action
::mask($permissions);
801 while ($result->fetch()) {
802 foreach ($resultFields as $donCare => $field) {
803 $casesList[$result->case_id
][$field] = $result->$field;
804 if ($field == 'contact_type') {
805 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
806 $result->contact_sub_type
: $result->contact_type
808 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
810 'id' => $result->case_id
,
811 'cid' => $result->contact_id
,
816 'case.actions.primary',
820 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
823 'id' => $result->case_id
,
824 'cid' => $result->contact_id
,
834 elseif ($field == 'case_status') {
835 if (in_array($result->$field, $caseStatus)) {
836 $casesList[$result->case_id
]['class'] = "status-urgent";
839 $casesList[$result->case_id
]['class'] = "status-normal";
844 $caseManagerContact = self
::getCaseManagerContact($result->case_type_name
, $result->case_id
);
845 if (!empty($caseManagerContact)) {
846 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
847 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
850 //do check user permissions for edit/view activity.
851 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
852 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
854 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
856 $casesList[$result->case_id
]['activity_type_id'], $userID
858 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
860 $casesList[$result->case_id
]['activity_type_id'], $userID
869 * Function to get the summary of cases counts by type and status.
871 static function getCasesSummary($allCases = TRUE, $userID) {
872 $caseSummary = array();
874 //validate access for civicase.
875 if (!self
::accessCiviCase()) {
879 //validate access for all cases.
880 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
884 $caseTypes = CRM_Case_PseudoConstant
::caseType();
885 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
886 $caseTypes = array_flip($caseTypes);
888 // get statuses as headers for the table
889 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
890 foreach ($caseStatuses as $key => $name) {
891 $caseSummary['headers'][$key]['status'] = $name;
892 $caseSummary['headers'][$key]['url'] = $url . $key;
895 // build rows with actual data
897 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
907 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
908 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
911 $seperator = CRM_Core_DAO
::VALUE_SEPARATOR
;
914 SELECT case_status.label AS case_status, status_id, case_type.label AS case_type,
915 REPLACE(case_type_id,'{$seperator}','') AS case_type_id, case_relationship.contact_id_b
917 LEFT JOIN civicrm_option_group option_group_case_type ON ( option_group_case_type.name = 'case_type' )
918 LEFT JOIN civicrm_option_value case_type ON ( civicrm_case.case_type_id = case_type.value
919 AND option_group_case_type.id = case_type.option_group_id )
920 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
921 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
922 AND option_group_case_status.id = case_status.option_group_id )
923 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
924 AND case_relationship.contact_id_b = {$userID})
926 {$myCaseWhereClause} {$myGroupByClause}";
928 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
929 while ($res->fetch()) {
930 if (CRM_Utils_Array
::value($res->case_type
, $rows) && CRM_Utils_Array
::value($res->case_status
, $rows[$res->case_type
])) {
931 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
934 $rows[$res->case_type
][$res->case_status
] = array(
936 'url' => CRM_Utils_System
::url('civicrm/case/search',
937 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
942 $caseSummary['rows'] = array_merge($caseTypes, $rows);
948 * Function to get Case roles
950 * @param int $contactID contact id
951 * @param int $caseID case id
952 * @return returns case role / relationships
956 static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
958 SELECT civicrm_relationship.id as civicrm_relationship_id,
959 civicrm_contact.sort_name as sort_name,
960 civicrm_email.email as email,
961 civicrm_phone.phone as phone,
962 civicrm_relationship.contact_id_b as civicrm_contact_id,
963 civicrm_relationship.contact_id_a as client_id,
964 civicrm_relationship_type.label_a_b as relation,
965 civicrm_relationship_type.id as relation_type
966 FROM civicrm_relationship
967 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
968 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
969 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
970 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
971 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
975 1 => array($contactID, 'Positive'),
976 2 => array($caseID, 'Positive'),
979 if ($relationshipID) {
980 $query .= ' AND civicrm_relationship.id = %3 ';
981 $params[3] = array($relationshipID, 'Integer');
983 $dao = CRM_Core_DAO
::executeQuery($query, $params);
986 while ($dao->fetch()) {
987 $rid = $dao->civicrm_relationship_id
;
988 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
989 $values[$rid]['relation'] = $dao->relation
;
990 $values[$rid]['name'] = $dao->sort_name
;
991 $values[$rid]['email'] = $dao->email
;
992 $values[$rid]['phone'] = $dao->phone
;
993 $values[$rid]['relation_type'] = $dao->relation_type
;
994 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
995 $values[$rid]['client_id'] = $dao->client_id
;
1003 * Function to get Case Activities
1005 * @param int $caseID case id
1006 * @param array $params posted params
1007 * @param int $contactID contact id
1009 * @return returns case activities
1013 static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
1016 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1017 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1018 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1019 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1021 // CRM-5081 - formatting the dates to omit seconds.
1022 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
1023 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
1024 ca.activity_type_id as type,
1025 ca.activity_type_id as activity_type_id,
1026 cc.sort_name as reporter,
1027 cc.id as reporter_id,
1028 acc.sort_name AS assignee,
1029 acc.id AS assignee_id,
1030 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1031 ca.activity_date_time,
1032 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1033 ), '%Y%m%d%H%i00') as overdue_date,
1034 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
1035 ca.status_id as status,
1036 ca.subject as subject,
1037 ca.is_deleted as deleted,
1038 ca.priority_id as priority,
1039 ca.weight as weight,
1040 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1043 FROM civicrm_case_activity cca
1044 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1045 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1046 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1047 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1048 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1049 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1050 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1051 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1052 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1053 LEFT JOIN civicrm_activity_contact caa
1054 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1055 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1057 $where = 'WHERE cca.case_id= %1
1058 AND ca.is_current_revision = 1';
1060 if (CRM_Utils_Array
::value('reporter_id', $params)) {
1061 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1064 if (CRM_Utils_Array
::value('status_id', $params)) {
1065 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1068 if (CRM_Utils_Array
::value('activity_deleted', $params)) {
1069 $where .= " AND ca.is_deleted = 1";
1072 $where .= " AND ca.is_deleted = 0";
1075 if (CRM_Utils_Array
::value('activity_type_id', $params)) {
1076 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1079 if (CRM_Utils_Array
::value('activity_date_low', $params)) {
1080 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1082 if (CRM_Utils_Array
::value('activity_date_high', $params)) {
1083 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1084 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1087 if (!empty($fromActivityDate)) {
1088 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1091 if (!empty($toActivityDate)) {
1092 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1095 // hack to handle to allow initial sorting to be done by query
1096 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1097 $params['sortname'] = NULL;
1100 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1101 $params['sortorder'] = NULL;
1104 $sortname = CRM_Utils_Array
::value('sortname', $params);
1105 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1107 $groupBy = " GROUP BY ca.id ";
1109 if (!$sortname AND !$sortorder) {
1110 // CRM-5081 - added id to act like creation date
1111 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1114 $sort = "{$sortname} {$sortorder}";
1115 $sort = CRM_Utils_Type
::escape($sort, 'String');
1116 $orderBy = " ORDER BY $sort ";
1117 if ($sortname != 'display_date') {
1118 $orderBy .= ', display_date DESC';
1122 $page = CRM_Utils_Array
::value('page', $params);
1123 $rp = CRM_Utils_Array
::value('rp', $params);
1132 $start = (($page - 1) * $rp);
1133 $query = $select . $from . $where . $groupBy . $orderBy;
1135 $params = array(1 => array($caseID, 'Integer'));
1136 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1137 $params['total'] = $dao->N
;
1139 //FIXME: need to optimize/cache these queries
1140 $limit = " LIMIT $start, $rp";
1144 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1147 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1148 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1149 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1151 $url = CRM_Utils_System
::url("civicrm/case/activity",
1152 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1156 if ($context == 'fulltext') {
1157 $contextUrl = "&context={$context}";
1159 $editUrl = "{$url}&action=update{$contextUrl}";
1160 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1161 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1162 $viewTitle = ts('View this activity.');
1163 $statusTitle = ts('Edit status');
1165 $emailActivityTypeIDs = array(
1166 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1170 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1176 $emailActivityTypeIDs = array(
1177 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1181 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1187 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1189 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1190 $compStatusValues = array();
1191 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1192 foreach ($compStatusNames as $name) {
1193 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1195 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1196 "reset=1&cid=", FALSE, NULL, FALSE
1198 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1199 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1202 $session = CRM_Core_Session
::singleton();
1203 $userID = $session->get('userID');
1206 while ($dao->fetch()) {
1208 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1209 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1210 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1212 //do not have sufficient permission
1213 //to access given case activity record.
1214 if (!$allowView && !$allowEdit && !$allowDelete) {
1218 $values[$dao->id
]['id'] = $dao->id
;
1219 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1221 $reporterName = $dao->reporter
;
1222 if ($hasViewContact) {
1223 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1225 $values[$dao->id
]['reporter'] = $reporterName;
1226 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1227 $targetContactUrls = $withContacts = array();
1228 foreach ($targetNames as $targetId => $targetName) {
1229 if (!in_array($targetId, $clientIds)) {
1230 $withContacts[$targetId] = $targetName;
1233 foreach ($withContacts as $cid => $name) {
1234 if ($hasViewContact) {
1235 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1237 $targetContactUrls[] = $name;
1239 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1241 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1242 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1244 //check for view activity.
1245 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1247 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id
. ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1249 $values[$dao->id
]['subject'] = $subject;
1251 // add activity assignee to activity selector. CRM-4485.
1252 if (isset($dao->assignee
)) {
1253 if ($dao->ismultiple
== 1) {
1254 if ($dao->reporter_id
!= $dao->assignee_id
) {
1255 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1257 $values[$dao->id
]['assignee'] = $dao->assignee
;
1260 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1264 $additionalUrl = "&id={$dao->id}";
1265 if (!$dao->deleted
) {
1266 //hide edit link of activity type email.CRM-4530.
1267 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1268 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1270 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1277 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1280 elseif (!$caseDeleted) {
1281 $url = '<a href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1282 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1285 //check for operations.
1286 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1287 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1289 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1290 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1292 // if there are file attachments we will return how many and, if only one, add a link to it
1293 if (!empty($dao->attachment_ids
)) {
1294 $attachmentIDs = explode(',', $dao->attachment_ids
);
1295 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1296 if ($values[$dao->id
]['no_attachments'] == 1) {
1297 // if there is only one it's easy to do a link - otherwise just flag it
1298 $attachmentViewUrl = CRM_Utils_System
::url(
1300 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1305 $url .= " | " . "<a href=$attachmentViewUrl >" . ts('View Attachment') . '</a> ';
1310 $values[$dao->id
]['links'] = $url;
1311 $values[$dao->id
]['class'] = "";
1313 if (!empty($dao->priority
)) {
1314 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1315 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1317 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1318 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1322 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1323 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1326 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1327 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1330 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1335 $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>';
1344 * Function to get Case Related Contacts
1346 * @param int $caseID case id
1347 * @param boolean $skipDetails if true include details of contacts
1349 * @return returns $searchRows array of returnproperties
1353 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1355 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1356 FROM civicrm_relationship cr
1357 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1358 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1359 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1360 WHERE cr.case_id = %1 AND ce.is_primary= 1
1363 $params = array(1 => array($caseID, 'Integer'));
1364 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1366 while ($dao->fetch()) {
1368 $values[$dao->id
] = 1;
1372 'contact_id' => $dao->id
,
1373 'display_name' => $dao->name
,
1374 'sort_name' => $dao->sort_name
,
1375 'role' => $dao->role
,
1376 'email' => $dao->email
,
1386 * Function that sends e-mail copy of activity
1388 * @param int $activityId activity Id
1389 * @param array $contacts array of related contact
1394 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1399 $tplParams = $activityInfo = array();
1400 //if its a case activity
1402 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1403 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1404 if (CRM_Utils_Array
::value($activityTypeId, $nonCaseActivityTypes)) {
1405 $anyActivity = TRUE;
1408 $anyActivity = FALSE;
1410 $tplParams['isCaseActivity'] = 1;
1411 $tplParams['client_id'] = $clientId;
1414 $anyActivity = TRUE;
1417 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1418 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1420 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1422 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1424 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1426 $tplParams['activity'] = $activityInfo;
1427 foreach ($tplParams['activity']['fields'] as $k => $val) {
1428 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1429 $activitySubject = $val['value'];
1433 $session = CRM_Core_Session
::singleton();
1434 // CRM-8926 If user is not logged in, use the activity creator as userID
1435 if (!($userID = $session->get('userID'))) {
1436 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1439 //also create activities simultaneously of this copy.
1440 $activityParams = array();
1442 $activityParams['source_record_id'] = $activityId;
1443 $activityParams['source_contact_id'] = $userID;
1444 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1445 $activityParams['activity_date_time'] = date('YmdHis');
1446 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1447 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1448 $activityParams['case_id'] = $caseId;
1449 $activityParams['is_auto'] = 0;
1450 $activityParams['target_id'] = $clientId;
1452 $tplParams['activitySubject'] = $activitySubject;
1454 // if it’s a case activity, add hashed id to the template (CRM-5916)
1456 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1460 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1462 $receiptFrom = "$name <$address>";
1464 $recordedActivityParams = array();
1466 foreach ($contacts as $mail => $info) {
1467 $tplParams['contact'] = $info;
1468 self
::buildPermissionLinks($tplParams, $activityParams);
1470 $displayName = CRM_Utils_Array
::value('display_name', $info);
1472 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1474 'groupName' => 'msg_tpl_workflow_case',
1475 'valueName' => 'case_activity',
1476 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1477 'tplParams' => $tplParams,
1478 'from' => $receiptFrom,
1479 'toName' => $displayName,
1481 'attachments' => $attachments,
1485 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1486 $activityParams['details'] = $message;
1488 if (!empty($result[$info['contact_id']])) {
1490 * Really only need to record one activity with all the targets combined.
1491 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1492 * but it's always the same content at the moment.
1494 if (empty($recordedActivityParams)) {
1495 $recordedActivityParams = $activityParams;
1498 $recordedActivityParams['subject'] .= "; $displayName";
1500 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1503 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1507 if (!empty($recordedActivityParams)) {
1508 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1510 //create case_activity record if its case activity.
1512 $caseParams = array(
1513 'activity_id' => $activity->id
,
1514 'case_id' => $caseId,
1516 self
::processCaseActivity($caseParams);
1524 * Retrieve count of activities having a particular type, and
1525 * associated with a particular case.
1527 * @param int $caseId ID of the case
1528 * @param int $activityTypeId ID of the activity type
1535 static function getCaseActivityCount($caseId, $activityTypeId) {
1536 $queryParam = array(
1537 1 => array($caseId, 'Integer'),
1538 2 => array($activityTypeId, 'Integer'),
1540 $query = "SELECT count(ca.id) as countact
1541 FROM civicrm_activity ca
1542 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1543 WHERE ca.activity_type_id = %2
1544 AND cca.case_id = %1
1545 AND ca.is_deleted = 0";
1547 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1548 if ($dao->fetch()) {
1549 return $dao->countact
;
1556 * Create an activity for a case via email
1558 * @param int $file email sent
1560 * @return $activity object of newly creted activity via email
1565 static function recordActivityViaEmail($file) {
1566 if (!file_exists($file) ||
1569 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1574 $result = CRM_Utils_Mail_Incoming
::parse($file);
1575 if ($result['is_error']) {
1579 foreach ($result['to'] as $to) {
1582 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1583 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1585 if ($replacement !== $to['email']) {
1586 $caseId = $replacement;
1587 //if caseId is invalid, return as error file
1588 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1589 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1598 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1599 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1600 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1602 if (CRM_Utils_Array
::value($result['from']['id'], $contactDetails)) {
1604 $params['subject'] = $result['subject'];
1605 $params['activity_date_time'] = $result['date'];
1606 $params['details'] = $result['body'];
1607 $params['source_contact_id'] = $result['from']['id'];
1608 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1613 $details = CRM_Case_PseudoConstant
::caseActivityType();
1615 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1616 $result['body'], $matches
1619 if (!empty($matches) && isset($matches[1])) {
1620 $activityType = trim($matches[1]);
1621 if (isset($details[$activityType])) {
1622 $params['activity_type_id'] = $details[$activityType]['id'];
1625 if (!isset($params['activity_type_id'])) {
1626 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1630 $activity = CRM_Activity_BAO_Activity
::create($params);
1632 $caseParams = array(
1633 'activity_id' => $activity->id
,
1634 'case_id' => $caseId,
1636 self
::processCaseActivity($caseParams);
1639 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1640 array(1 => $result['from']['email'])
1647 * Function to retrieve the scheduled activity type and date
1649 * @param array $cases Array of contact and case id
1651 * @return array $activityInfo Array of scheduled activity type and date
1657 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1658 $session = CRM_Core_Session
::singleton();
1659 $userID = $session->get('userID');
1661 $caseID = implode(',', $cases['case_id']);
1662 $contactID = implode(',', $cases['contact_id']);
1665 AND civicrm_case_contact.contact_id IN( {$contactID} )
1666 AND civicrm_case.id IN( {$caseID})
1667 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1669 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1671 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1673 $activityInfo = array();
1674 while ($res->fetch()) {
1675 if ($type == 'upcoming') {
1676 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1677 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1680 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1681 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1685 return $activityInfo;
1689 * combine all the exportable fields from the lower levels object
1691 * @return array array of exportable Fields
1695 static function &exportableFields() {
1696 if (!self
::$_exportableFields) {
1697 if (!self
::$_exportableFields) {
1698 self
::$_exportableFields = array();
1701 $fields = CRM_Case_DAO_Case
::export();
1702 $fields['case_role'] = array('title' => ts('Role in Case'));
1703 $fields['case_type'] = array(
1704 'title' => ts('Case Type'),
1705 'name' => 'case_type',
1707 $fields['case_status'] = array(
1708 'title' => ts('Case Status'),
1709 'name' => 'case_status',
1712 self
::$_exportableFields = $fields;
1714 return self
::$_exportableFields;
1718 * Restore the record that are associated with this case
1720 * @param int $caseId id of the case to restore
1722 * @return true if success.
1726 static function restoreCase($caseId) {
1727 //restore activities
1728 $activities = self
::getCaseActivityDates($caseId);
1730 foreach ($activities as $value) {
1731 CRM_Activity_BAO_Activity
::restoreActivity($value);
1735 $case = new CRM_Case_DAO_Case();
1736 $case->id
= $caseId;
1737 $case->is_deleted
= 0;
1740 //CRM-7364, enable relationships
1741 self
::enableDisableCaseRelationships($caseId, TRUE);
1745 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1746 $globalContacts = array();
1748 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1749 $settings = $settingsProcessor->run();
1750 if (!empty($settings)) {
1751 $groupInfo['name'] = $settings['groupname'];
1752 if ($groupInfo['name']) {
1753 $searchParams = array('name' => $groupInfo['name']);
1755 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1757 $groupInfo['id'] = $results['id'];
1758 $groupInfo['title'] = $results['title'];
1759 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1760 $return = array('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1761 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1762 list($globalContacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1764 if ($returnOnlyCount) {
1765 return $globalContacts;
1769 foreach ($globalContacts as $idx => $contact) {
1770 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1776 return $globalContacts;
1780 * Convenience function to get both case contacts and global in one array
1782 static function getRelatedAndGlobalContacts($caseId) {
1783 $relatedContacts = self
::getRelatedContacts($caseId);
1785 $groupInfo = array();
1786 $globalContacts = self
::getGlobalContacts($groupInfo);
1788 //unset values which are not required.
1789 foreach ($globalContacts as $k => & $v) {
1790 unset($v['email_id']);
1791 unset($v['group_contact_id']);
1792 unset($v['status']);
1794 $v['role'] = $groupInfo['title'];
1796 //include multiple listings for the same contact/different roles.
1797 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1798 return $relatedGlobalContacts;
1802 * Function to get Case ActivitiesDueDates with given criteria.
1804 * @param int $caseID case id
1805 * @param array $criteriaParams given criteria
1806 * @param boolean $latestDate if set newest or oldest date is selceted.
1808 * @return returns case activities due dates
1812 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1814 $selectDate = " ca.activity_date_time";
1815 $where = $groupBy = ' ';
1822 if (CRM_Utils_Array
::value('activity_type_id', $criteriaParams)) {
1823 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1824 $where .= " AND ca.is_current_revision = 1";
1825 $groupBy .= " GROUP BY ca.activity_type_id";
1828 if (CRM_Utils_Array
::value('newest', $criteriaParams)) {
1829 $selectDate = " max(ca.activity_date_time) ";
1832 $selectDate = " min(ca.activity_date_time) ";
1836 $query = "SELECT ca.id, {$selectDate} as activity_date
1837 FROM civicrm_activity ca
1838 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1839 WHERE cc.id = %1 {$where} {$groupBy}";
1841 $params = array(1 => array($caseID, 'Integer'));
1842 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1844 while ($dao->fetch()) {
1845 $values[$dao->id
]['id'] = $dao->id
;
1846 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1853 * Function to create activities when Case or Other roles assigned/modified/deleted.
1855 * @param int $caseID case id
1856 * @param int $relationshipId relationship id
1857 * @param int $relContactId case role assignee contactId.
1859 * @return void on success creates activity and case activity
1863 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1864 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1868 $queryParam = array();
1869 if (is_array($relationshipId)) {
1870 $relationshipId = implode(',', $relationshipId);
1871 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1874 $relationshipClause = " civicrm_relationship.id = %1";
1875 $queryParam[1] = array($relationshipId, 'Positive');
1879 SELECT cc.display_name as clientName,
1880 cca.display_name as assigneeContactName,
1881 civicrm_relationship.case_id as caseId,
1882 civicrm_relationship_type.label_a_b as relation_a_b,
1883 civicrm_relationship_type.label_b_a as relation_b_a,
1884 civicrm_relationship.contact_id_b as rel_contact_id,
1885 civicrm_relationship.contact_id_a as assign_contact_id
1886 FROM civicrm_relationship_type, civicrm_relationship
1887 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1888 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1889 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1891 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1893 while ($dao->fetch()) {
1894 //to get valid assignee contact(s).
1895 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1896 $caseRelationship = $dao->relation_a_b
;
1897 $assigneContactName = $dao->clientName
;
1898 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1901 $caseRelationship = $dao->relation_b_a
;
1902 $assigneContactName = $dao->assigneeContactName
;
1903 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1907 $session = CRM_Core_Session
::singleton();
1908 $activityParams = array(
1909 'source_contact_id' => $session->get('userID'),
1910 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1911 'activity_date_time' => date('YmdHis'),
1912 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1915 //if $relContactId is passed, role is added or modified.
1916 if (!empty($relContactId)) {
1917 $activityParams['assignee_contact_id'] = $assigneContactIds;
1919 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1925 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1931 $activityParams['activity_type_id'] = $activityTypeID;
1933 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1935 //create case_activity record.
1936 $caseParams = array(
1937 'activity_id' => $activity->id
,
1938 'case_id' => $caseId,
1941 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1945 * Function to get case manger
1946 * contact which is assigned a case role of case manager.
1948 * @param int $caseType case type
1949 * @param int $caseId case id
1951 * @return array $caseManagerContact array of contact on success otherwise empty
1955 static function getCaseManagerContact($caseType, $caseId) {
1956 if (!$caseType ||
!$caseId) {
1960 $caseManagerContact = array();
1961 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1963 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1965 if (!empty($managerRoleId)) {
1966 $managerRoleQuery = "
1967 SELECT civicrm_contact.id as casemanager_id,
1968 civicrm_contact.sort_name as casemanager
1969 FROM civicrm_contact
1970 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1971 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1972 WHERE civicrm_case.id = %2";
1974 $managerRoleParams = array(
1975 1 => array($managerRoleId, 'Integer'),
1976 2 => array($caseId, 'Integer'),
1979 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1980 if ($dao->fetch()) {
1981 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1982 $caseManagerContact['casemanager'] = $dao->casemanager
;
1986 return $caseManagerContact;
1990 * Get all cases with no end dates
1992 * @return array of case and related data keyed on case id
1994 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1995 //params from ajax call.
1996 $where = array('( ca.end_date is null )');
1997 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
1998 $where[] = "( ov.label LIKE '%$caseType%' )";
2000 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
2001 $config = CRM_Core_Config
::singleton();
2002 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
2003 $where[] = "( sort_name LIKE '$search' )";
2005 if (is_array($excludeCaseIds) &&
2006 !CRM_Utils_System
::isNull($excludeCaseIds)
2008 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2010 if ($excludeDeleted) {
2011 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2014 //filter for permissioned cases.
2015 $filterCases = array();
2016 $doFilterCases = FALSE;
2017 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2018 $doFilterCases = TRUE;
2019 $session = CRM_Core_Session
::singleton();
2020 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2022 $whereClause = implode(' AND ', $where);
2025 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
2026 $limitClause = "LIMIT 0, $limit";
2030 SELECT c.id as contact_id,
2033 ca.subject as case_subject,
2034 ov.label as case_type,
2035 ca.start_date as start_date
2036 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2037 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2038 INNER JOIN civicrm_option_group og ON og.name='case_type'
2039 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2040 WHERE {$whereClause}
2041 ORDER BY c.sort_name
2044 $dao = CRM_Core_DAO
::executeQuery($query);
2045 $unclosedCases = array();
2046 while ($dao->fetch()) {
2047 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2050 $unclosedCases[$dao->id
] = array(
2051 'sort_name' => $dao->sort_name
,
2052 'case_type' => $dao->case_type
,
2053 'contact_id' => $dao->contact_id
,
2054 'start_date' => $dao->start_date
,
2055 'case_subject' => $dao->case_subject
,
2060 return $unclosedCases;
2063 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2064 $whereConditions = array();
2065 if ($excludeDeleted) {
2066 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2069 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2071 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2072 static $accessibleCaseIds;
2073 if (!is_array($accessibleCaseIds)) {
2074 $session = CRM_Core_Session
::singleton();
2075 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID'), 'any'));
2077 //no need of further processing.
2078 if (empty($accessibleCaseIds)) {
2081 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2085 if (!empty($whereConditions)) {
2086 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2090 SELECT count( civicrm_case.id )
2092 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2095 return CRM_Core_DAO
::singleValueQuery($query);
2099 * Retrieve cases related to particular contact.
2101 * @param int $contactId contact id
2102 * @param boolean $excludeDeleted do not include deleted cases.
2104 * @return an array of cases.
2108 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2114 $whereClause = "civicrm_case_contact.contact_id = %1";
2115 if ($excludeDeleted) {
2116 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2120 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2122 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2123 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2124 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2125 AND case_type_og.id = case_type_ov.option_group_id )
2126 WHERE {$whereClause}";
2128 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2129 while ($dao->fetch()) {
2130 $cases[$dao->id
] = array(
2131 'case_id' => $dao->id
,
2132 'case_type' => $dao->case_type
,
2133 'case_start_date' => $dao->start_date
,
2142 * Retrieve related cases for give case.
2144 * @param int $mainCaseId id of main case
2145 * @param int $contactId id of contact
2146 * @param boolean $excludeDeleted do not include deleted cases.
2148 * @return an array of related cases.
2152 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2153 //FIXME : do check for permissions.
2155 $relatedCases = array();
2156 if (!$mainCaseId ||
!$contactId) {
2157 return $relatedCases;
2160 $linkActType = array_search('Link Cases',
2161 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2163 if (!$linkActType) {
2164 return $relatedCases;
2167 $whereClause = "mainCase.id = %2";
2168 if ($excludeDeleted) {
2169 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2172 //1. first fetch related case ids.
2174 SELECT relCaseAct.case_id
2175 FROM civicrm_case mainCase
2176 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2177 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2178 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2179 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2180 WHERE $whereClause";
2182 $dao = CRM_Core_DAO
::executeQuery($query, array(
2183 1 => array($linkActType, 'Integer'),
2184 2 => array($mainCaseId, 'Integer'),
2186 $relatedCaseIds = array();
2187 while ($dao->fetch()) {
2188 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2192 // there are no related cases.
2193 if (empty($relatedCaseIds)) {
2194 return $relatedCases;
2197 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2198 if ($excludeDeleted) {
2199 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2202 //filter for permissioned cases.
2203 $filterCases = array();
2204 $doFilterCases = FALSE;
2205 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2206 $doFilterCases = TRUE;
2207 $session = CRM_Core_Session
::singleton();
2208 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2211 //2. fetch the details of related cases.
2213 SELECT relCase.id as id,
2214 case_type_ov.label as case_type,
2215 client.display_name as client_name,
2216 client.id as client_id
2217 FROM civicrm_case relCase
2218 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2219 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2220 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2221 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2222 AND case_type_og.id = case_type_ov.option_group_id )
2223 WHERE {$whereClause}";
2225 $dao = CRM_Core_DAO
::executeQuery($query);
2226 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2227 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2229 while ($dao->fetch()) {
2231 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2232 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2233 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2234 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2236 $clientView = $dao->client_name
;
2237 if ($hasViewContact) {
2238 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2241 $relatedCases[$dao->id
] = array(
2242 'case_id' => $dao->id
,
2243 'case_type' => $dao->case_type
,
2244 'client_name' => $clientView,
2245 'links' => $caseView,
2250 return $relatedCases;
2254 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2256 * @see CRM_Dedupe_Merger::cpTables()
2258 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2260 static function mergeContacts($mainContactId, $otherContactId) {
2261 self
::mergeCases($mainContactId, NULL, $otherContactId);
2265 * Function perform two task.
2266 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2267 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2269 * @param int $mainContactId contact id of main contact record.
2270 * @param int $mainCaseId case id of main case record.
2271 * @param int $otherContactId contact id of record which is going to merge.
2272 * @param int $otherCaseId case id of record which is going to merge.
2277 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2278 $otherCaseId = NULL, $changeClient = FALSE) {
2279 $moveToTrash = TRUE;
2281 $duplicateContacts = FALSE;
2282 if ($mainContactId && $otherContactId &&
2283 $mainContactId != $otherContactId
2285 $duplicateContacts = TRUE;
2288 $duplicateCases = FALSE;
2289 if ($mainCaseId && $otherCaseId &&
2290 $mainCaseId != $otherCaseId
2292 $duplicateCases = TRUE;
2295 $mainCaseIds = array();
2296 if (!$duplicateContacts && !$duplicateCases) {
2297 return $mainCaseIds;
2300 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2301 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2302 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2303 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2304 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2305 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2307 $processCaseIds = array($otherCaseId);
2308 if ($duplicateContacts && !$duplicateCases) {
2309 if ($changeClient) {
2310 $processCaseIds = array($mainCaseId);
2313 //get all case ids for other contact.
2314 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2316 if (!is_array($processCaseIds)) {
2321 $session = CRM_Core_Session
::singleton();
2322 $currentUserId = $session->get('userID');
2324 // copy all cases and connect to main contact id.
2325 foreach ($processCaseIds as $otherCaseId) {
2326 if ($duplicateContacts) {
2327 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2328 $mainCaseId = $mainCase->id
;
2333 // CRM-11662 Copy Case custom data
2334 $extends = array('case');
2335 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2337 foreach ($groupTree as $groupID => $group) {
2338 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2339 foreach ($group['fields'] as $fieldID => $field) {
2340 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2344 foreach ($table as $tableName => $tableColumns) {
2345 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2346 $tableColumns[0] = $mainCaseId;
2347 $select = 'SELECT ' . implode(', ', $tableColumns);
2348 $from = ' FROM ' . $tableName;
2349 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2350 $query = $insert . $select . $from . $where;
2351 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2357 $mainCaseIds[] = $mainCaseId;
2358 //insert record for case contact.
2359 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2360 $otherCaseContact->case_id
= $otherCaseId;
2361 $otherCaseContact->find();
2362 while ($otherCaseContact->fetch()) {
2363 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2364 $mainCaseContact->case_id
= $mainCaseId;
2365 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2366 if ($mainCaseContact->contact_id
== $otherContactId) {
2367 $mainCaseContact->contact_id
= $mainContactId;
2369 //avoid duplicate object.
2370 if (!$mainCaseContact->find(TRUE)) {
2371 $mainCaseContact->save();
2373 $mainCaseContact->free();
2375 $otherCaseContact->free();
2377 elseif (!$otherContactId) {
2378 $otherContactId = $mainContactId;
2381 if (!$mainCaseId ||
!$otherCaseId ||
2382 !$mainContactId ||
!$otherContactId
2387 // get all activities for other case.
2388 $otherCaseActivities = array();
2389 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2391 //for duplicate cases do not process singleton activities.
2392 $otherActivityIds = $singletonActivityIds = array();
2393 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2394 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2395 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2398 $otherActivityIds[] = $otherActId;
2400 if ($duplicateCases) {
2401 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2404 FROM civicrm_activity
2405 WHERE activity_type_id = $openCaseType
2406 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2407 $dao = CRM_Core_DAO
::executeQuery($sql);
2408 while ($dao->fetch()) {
2409 $singletonActivityIds[] = $dao->id
;
2415 // migrate all activities and connect to main contact.
2416 $copiedActivityIds = $activityMappingIds = array();
2417 sort($otherActivityIds);
2418 foreach ($otherActivityIds as $otherActivityId) {
2420 //for duplicate cases -
2421 //do not migrate singleton activities.
2422 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2426 //migrate activity record.
2427 $otherActivity = new CRM_Activity_DAO_Activity();
2428 $otherActivity->id
= $otherActivityId;
2429 if (!$otherActivity->find(TRUE)) {
2433 $mainActVals = array();
2434 $mainActivity = new CRM_Activity_DAO_Activity();
2435 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2436 $mainActivity->copyValues($mainActVals);
2437 $mainActivity->id
= NULL;
2438 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2439 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2443 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2447 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2450 $mainActivity->save();
2451 $mainActivityId = $mainActivity->id
;
2452 if (!$mainActivityId) {
2456 $activityMappingIds[$otherActivityId] = $mainActivityId;
2457 // insert log of all activities
2458 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2460 $otherActivity->free();
2461 $mainActivity->free();
2462 $copiedActivityIds[] = $otherActivityId;
2464 //create case activity record.
2465 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2466 $mainCaseActivity->case_id
= $mainCaseId;
2467 $mainCaseActivity->activity_id
= $mainActivityId;
2468 $mainCaseActivity->save();
2469 $mainCaseActivity->free();
2471 //migrate source activity.
2472 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2473 $otherSourceActivity->activity_id
= $otherActivityId;
2474 $otherSourceActivity->record_type_id
= $sourceID;
2475 $otherSourceActivity->find();
2476 while ($otherSourceActivity->fetch()) {
2477 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2478 $mainActivitySource->record_type_id
= $sourceID;
2479 $mainActivitySource->activity_id
= $mainActivityId;
2480 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2481 if ($mainActivitySource->contact_id
== $otherContactId) {
2482 $mainActivitySource->contact_id
= $mainContactId;
2484 //avoid duplicate object.
2485 if (!$mainActivitySource->find(TRUE)) {
2486 $mainActivitySource->save();
2488 $mainActivitySource->free();
2490 $otherSourceActivity->free();
2492 //migrate target activities.
2493 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2494 $otherTargetActivity->activity_id
= $otherActivityId;
2495 $otherTargetActivity->record_type_id
= $targetID;
2496 $otherTargetActivity->find();
2497 while ($otherTargetActivity->fetch()) {
2498 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2499 $mainActivityTarget->record_type_id
= $targetID;
2500 $mainActivityTarget->activity_id
= $mainActivityId;
2501 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2502 if ($mainActivityTarget->contact_id
== $otherContactId) {
2503 $mainActivityTarget->contact_id
= $mainContactId;
2505 //avoid duplicate object.
2506 if (!$mainActivityTarget->find(TRUE)) {
2507 $mainActivityTarget->save();
2509 $mainActivityTarget->free();
2511 $otherTargetActivity->free();
2513 //migrate assignee activities.
2514 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2515 $otherAssigneeActivity->activity_id
= $otherActivityId;
2516 $otherAssigneeActivity->record_type_id
= $assigneeID;
2517 $otherAssigneeActivity->find();
2518 while ($otherAssigneeActivity->fetch()) {
2519 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2520 $mainAssigneeActivity->activity_id
= $mainActivityId;
2521 $mainAssigneeActivity->record_type_id
= $assigneeID;
2522 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2523 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2524 $mainAssigneeActivity->contact_id
= $mainContactId;
2526 //avoid duplicate object.
2527 if (!$mainAssigneeActivity->find(TRUE)) {
2528 $mainAssigneeActivity->save();
2530 $mainAssigneeActivity->free();
2532 $otherAssigneeActivity->free();
2534 // copy custom fields and attachments
2536 'activityID' => $otherActivityId,
2537 'mainActivityId' => $mainActivityId,
2539 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2542 //copy case relationship.
2543 if ($duplicateContacts) {
2544 //migrate relationship records.
2545 $otherRelationship = new CRM_Contact_DAO_Relationship();
2546 $otherRelationship->case_id
= $otherCaseId;
2547 $otherRelationship->find();
2548 $otherRelationshipIds = array();
2549 while ($otherRelationship->fetch()) {
2550 $otherRelVals = array();
2551 $updateOtherRel = FALSE;
2552 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2554 $mainRelationship = new CRM_Contact_DAO_Relationship();
2555 $mainRelationship->copyValues($otherRelVals);
2556 $mainRelationship->id
= NULL;
2557 $mainRelationship->case_id
= $mainCaseId;
2558 if ($mainRelationship->contact_id_a
== $otherContactId) {
2559 $updateOtherRel = TRUE;
2560 $mainRelationship->contact_id_a
= $mainContactId;
2563 //case creator change only when we merge user contact.
2564 if ($mainRelationship->contact_id_b
== $otherContactId) {
2565 //do not change creator for change client.
2566 if (!$changeClient) {
2567 $updateOtherRel = TRUE;
2568 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2571 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2572 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2574 //avoid duplicate object.
2575 if (!$mainRelationship->find(TRUE)) {
2576 $mainRelationship->save();
2578 $mainRelationship->free();
2580 //get the other relationship ids to update end date.
2581 if ($updateOtherRel) {
2582 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2585 $otherRelationship->free();
2587 //update other relationships end dates
2588 if (!empty($otherRelationshipIds)) {
2589 $sql = 'UPDATE civicrm_relationship
2590 SET end_date = CURDATE()
2591 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2592 CRM_Core_DAO
::executeQuery($sql);
2596 //move other case to trash.
2597 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2602 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2603 if ($changeClient) {
2604 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2605 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2607 $mergeActType = array_search('Reassigned Case', $activityTypes);
2608 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2611 2 => $otherContactDisplayName,
2612 3 => $mainContactDisplayName,
2617 elseif ($duplicateContacts) {
2618 $mergeActType = array_search('Merge Case', $activityTypes);
2619 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2622 2 => $otherContactId,
2623 3 => $mainContactId,
2629 $mergeActType = array_search('Merge Case', $activityTypes);
2630 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2631 if (!empty($copiedActivityIds)) {
2633 SELECT id, subject, activity_date_time, activity_type_id
2634 FROM civicrm_activity
2635 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2636 $dao = CRM_Core_DAO
::executeQuery($sql);
2637 while ($dao->fetch()) {
2638 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2639 if ($dao->subject
) {
2640 $mergeActSubjectDetails .= " :: {$dao->subject}";
2642 $mergeActSubjectDetails .= "<br />";
2647 //create merge activity record.
2648 $activityParams = array(
2649 'subject' => $mergeActSubject,
2650 'details' => $mergeActSubjectDetails,
2651 'status_id' => array_search('Completed', $activityStatuses),
2652 'activity_type_id' => $mergeActType,
2653 'source_contact_id' => $mainContactId,
2654 'activity_date_time' => date('YmdHis'),
2657 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2658 $mergeActivityId = $mergeActivity->id
;
2659 if (!$mergeActivityId) {
2662 $mergeActivity->free();
2664 //connect merge activity to case.
2665 $mergeCaseAct = array(
2666 'case_id' => $mainCaseId,
2667 'activity_id' => $mergeActivityId,
2670 self
::processCaseActivity($mergeCaseAct);
2672 return $mainCaseIds;
2676 * Validate contact permission for
2677 * edit/view on activity record and build links.
2679 * @param array $tplParams params to be sent to template for sending email.
2680 * @param array $activityParams info of the activity.
2685 static function buildPermissionLinks(&$tplParams, $activityParams) {
2686 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2687 'activity_type_id', 'id'
2690 if (CRM_Utils_Array
::value('isCaseActivity', $tplParams)) {
2691 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2692 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2695 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2696 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2699 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2700 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2704 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2705 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2708 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2709 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2715 * Validate contact permission for
2716 * given operation on activity record.
2718 * @param int $activityId activity record id.
2719 * @param string $operation user operation.
2720 * @param int $actTypeId activity type id.
2721 * @param int $contactId contact id/if not pass consider logged in
2722 * @param boolean $checkComponent do we need to check component enabled.
2724 * @return boolean $allow true/false
2727 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2729 if (!$actTypeId && $activityId) {
2730 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2733 if (!$activityId ||
!$operation ||
!$actTypeId) {
2737 //do check for civicase component enabled.
2738 if ($checkComponent) {
2739 static $componentEnabled;
2740 if (!isset($componentEnabled)) {
2741 $config = CRM_Core_Config
::singleton();
2742 $componentEnabled = FALSE;
2743 if (in_array('CiviCase', $config->enableComponents
)) {
2744 $componentEnabled = TRUE;
2747 if (!$componentEnabled) {
2752 //do check for cases.
2753 $caseActOperations = array(
2760 if (in_array($operation, $caseActOperations)) {
2761 static $unclosedCases;
2762 if (!is_array($unclosedCases)) {
2763 $unclosedCases = self
::getUnclosedCases();
2765 if ($operation == 'File On Case') {
2766 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2769 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2773 $actionOperations = array('view', 'edit', 'delete');
2774 if (in_array($operation, $actionOperations)) {
2776 //do cache when user has non/supper permission.
2777 static $allowOperations;
2779 if (!is_array($allowOperations) ||
2780 !array_key_exists($operation, $allowOperations)
2784 $session = CRM_Core_Session
::singleton();
2785 $contactId = $session->get('userID');
2788 //check for permissions.
2789 $permissions = array(
2791 'access my cases and activities',
2792 'access all cases and activities',
2795 'access my cases and activities',
2796 'access all cases and activities',
2798 'delete' => array('delete activities'),
2801 //check for core permission.
2802 $hasPermissions = array();
2803 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2804 if (is_array($checkPermissions)) {
2805 foreach ($checkPermissions as $per) {
2806 if (CRM_Core_Permission
::check($per)) {
2807 $hasPermissions[$operation][] = $per;
2813 if (!empty($hasPermissions)) {
2814 //need to check activity object specific.
2815 if (in_array($operation, array(
2820 //do we have supper permission.
2821 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2822 $allowOperations[$operation] = $allow = TRUE;
2825 //user has only access to my cases and activity.
2826 //here object specific permmions come in picture.
2828 //edit - contact must be source or assignee
2829 //view - contact must be source/assignee/target
2830 $isTarget = $isAssignee = $isSource = FALSE;
2831 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2832 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2833 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2834 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2836 $target = new CRM_Activity_DAO_ActivityContact();
2837 $target->record_type_id
= $targetID;
2838 $target->activity_id
= $activityId;
2839 $target->contact_id
= $contactId;
2840 if ($target->find(TRUE)) {
2844 $assignee = new CRM_Activity_DAO_ActivityContact();
2845 $assignee->activity_id
= $activityId;
2846 $assignee->record_type_id
= $assigneeID;
2847 $assignee->contact_id
= $contactId;
2848 if ($assignee->find(TRUE)) {
2852 $source = new CRM_Activity_DAO_ActivityContact();
2853 $source->activity_id
= $activityId;
2854 $source->record_type_id
= $sourceID;
2855 $source->contact_id
= $contactId;
2856 if ($source->find(TRUE)) {
2860 if ($operation == 'edit') {
2861 if ($isAssignee ||
$isSource) {
2865 if ($operation == 'view') {
2866 if ($isTarget ||
$isAssignee ||
$isSource) {
2872 elseif (is_array($hasPermissions[$operation])) {
2873 $allowOperations[$operation] = $allow = TRUE;
2877 //contact do not have permission.
2878 $allowOperations[$operation] = FALSE;
2883 //here contact might have supper/non permission.
2884 $allow = $allowOperations[$operation];
2888 //do further only when operation is granted.
2890 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2892 //get the activity type name.
2893 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2895 //do not allow multiple copy / edit action.
2896 $singletonNames = array(
2906 //do not allow to delete these activities, CRM-4543
2907 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2909 //allow edit operation.
2910 $allowEditNames = array('Open Case');
2912 // do not allow File on Case
2913 $doNotFileNames = array(
2916 'Change Case Status',
2917 'Change Case Start Date',
2924 if (in_array($actTypeName, $singletonNames)) {
2926 if ($operation == 'File On Case') {
2927 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2929 if (in_array($operation, $actionOperations)) {
2931 if ($operation == 'edit') {
2932 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2934 elseif ($operation == 'delete') {
2935 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2939 if ($allow && ($operation == 'delete') &&
2940 in_array($actTypeName, $doNotDeleteNames)
2945 if ($allow && ($operation == 'File On Case') &&
2946 in_array($actTypeName, $doNotFileNames)
2951 //check settings file for masking actions
2952 //on the basis the activity types
2953 //hide Edit link if activity type is NOT editable
2954 //(special case activities).CRM-5871
2955 if ($allow && in_array($operation, $actionOperations)) {
2956 static $actionFilter = array();
2957 if (!array_key_exists($operation, $actionFilter)) {
2958 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2959 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2961 if (array_key_exists($operation, $actionFilter[$operation]) &&
2962 in_array($actTypeId, $actionFilter[$operation][$operation])
2973 * since we drop 'access CiviCase', allow access
2974 * if user has 'access my cases and activities'
2975 * or 'access all cases and activities'
2977 static function accessCiviCase() {
2978 static $componentEnabled;
2979 if (!isset($componentEnabled)) {
2980 $componentEnabled = FALSE;
2981 $config = CRM_Core_Config
::singleton();
2982 if (in_array('CiviCase', $config->enableComponents
)) {
2983 $componentEnabled = TRUE;
2986 if (!$componentEnabled) {
2990 if (CRM_Core_Permission
::check('access my cases and activities') ||
2991 CRM_Core_Permission
::check('access all cases and activities')
3000 * Function to check whether activity is a case Activity
3002 * @param int $activityID activity id
3004 * @return boolean $isCaseActivity true/false
3006 static function isCaseActivity($activityID) {
3007 $isCaseActivity = FALSE;
3009 $params = array(1 => array($activityID, 'Integer'));
3010 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3011 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
3012 $isCaseActivity = TRUE;
3016 return $isCaseActivity;
3020 * Function to get all the case type ids currently in use
3023 * @return array $caseTypeIds
3025 static function getUsedCaseType() {
3026 static $caseTypeIds;
3028 if (!is_array($caseTypeIds)) {
3029 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3031 $dao = CRM_Core_DAO
::executeQuery($query);
3032 $caseTypeIds = array();
3033 while ($dao->fetch()) {
3034 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3037 $caseTypeIds[] = $typeId[1];
3041 return $caseTypeIds;
3045 * Function to get all the case status ids currently in use
3048 * @return array $caseStatusIds
3050 static function getUsedCaseStatuses() {
3051 static $caseStatusIds;
3053 if (!is_array($caseStatusIds)) {
3054 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3056 $dao = CRM_Core_DAO
::executeQuery($query);
3057 $caseStatusIds = array();
3058 while ($dao->fetch()) {
3059 $caseStatusIds[] = $dao->status_id
;
3063 return $caseStatusIds;
3067 * Function to get all the encounter medium ids currently in use
3070 static function getUsedEncounterMediums() {
3073 if (!is_array($mediumIds)) {
3074 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3076 $dao = CRM_Core_DAO
::executeQuery($query);
3077 $mediumIds = array();
3078 while ($dao->fetch()) {
3079 $mediumIds[] = $dao->medium_id
;
3087 * Function to check case configuration.
3089 * @return array $configured
3091 static function isCaseConfigured($contactId = NULL) {
3092 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3094 //lets check for case configured.
3095 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3096 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3097 if (!$configured['configured']) {
3098 //do check for case type and case status.
3099 $caseTypes = CRM_Case_PseudoConstant
::caseType('label', FALSE);
3100 if (!empty($caseTypes)) {
3101 $configured['configured'] = TRUE;
3102 if (!$configured['configured']) {
3103 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3104 if (!empty($caseStatuses)) {
3105 $configured['configured'] = TRUE;
3110 if ($configured['configured']) {
3111 //do check for active case type and case status.
3112 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3113 if (!empty($caseTypes)) {
3114 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3115 if (!empty($caseStatuses)) {
3116 $configured['allowToAddNewCase'] = TRUE;
3120 //do we need to redirect user to case admin.
3121 if (!$configured['allowToAddNewCase'] && $contactId) {
3122 //check for current contact case count.
3123 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3124 //redirect user to case admin page.
3125 if (!$currentContatCasesCount) {
3126 $configured['redirectToCaseAdmin'] = TRUE;
3135 * Used during case component enablement and during ugprade
3137 static function createCaseViews() {
3138 $dao = new CRM_Core_DAO();
3140 $sql = self
::createCaseViewsQuery('upcoming');
3141 CRM_Core_Error
::ignoreException();
3143 CRM_Core_Error
::setCallback();
3144 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3148 // Above error doesn't get caught?
3149 CRM_Core_Error
::ignoreException();
3150 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3151 CRM_Core_Error
::setCallback();
3152 if (is_null($doublecheck)) {
3156 $sql = self
::createCaseViewsQuery('recent');
3157 CRM_Core_Error
::ignoreException();
3159 CRM_Core_Error
::setCallback();
3160 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3164 // Above error doesn't get caught?
3165 CRM_Core_Error
::ignoreException();
3166 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3167 CRM_Core_Error
::setCallback();
3168 if (is_null($doublecheck)) {
3176 * helper function, also used by the upgrade in case of error
3178 static function createCaseViewsQuery($section = 'upcoming') {
3180 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3183 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3184 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3185 FROM civicrm_case_activity ca
3186 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3187 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3188 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3192 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3193 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3194 FROM civicrm_case_activity ca
3195 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3196 WHERE a.activity_date_time <= NOW()
3197 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3198 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3205 * Function to add/copy relationships, when new client is added for a case
3207 * @param int $caseId case id
3208 * @param int $contactId contact id / new client id
3212 static function addCaseRelationships($caseId, $contactId) {
3213 // get the case role / relationships for the case
3214 $caseRelationships = new CRM_Contact_DAO_Relationship();
3215 $caseRelationships->case_id
= $caseId;
3216 $caseRelationships->find();
3217 $relationshipTypes = array();
3219 // make sure we don't add duplicate relationships of same relationship type.
3220 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3222 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3224 // add relationship for new client.
3225 $newRelationship = new CRM_Contact_DAO_Relationship();
3226 $newRelationship->copyValues($values);
3227 $newRelationship->id
= NULL;
3228 $newRelationship->case_id
= $caseId;
3229 $newRelationship->contact_id_a
= $contactId;
3230 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3231 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3233 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3234 if (!$newRelationship->find(TRUE)) {
3235 $newRelationship->save();
3237 $newRelationship->free();
3239 // store relationship type of newly created relationship
3240 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3245 * Function to get the list of clients for a case
3247 * @param int $caseId
3249 * @return array $clients associated array with client ids
3252 static function getCaseClients($caseId) {
3254 $caseContact = new CRM_Case_DAO_CaseContact();
3255 $caseContact->case_id
= $caseId;
3256 $caseContact->find();
3258 while ($caseContact->fetch()) {
3259 $clients[] = $caseContact->contact_id
;
3266 * Get options for a given case field.
3267 * @see CRM_Core_DAO::buildOptions
3269 * @param String $fieldName
3270 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3271 * @param Array $props: whatever is known about this dao object
3273 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3274 $className = __CLASS__
;
3276 switch ($fieldName) {
3277 // This field is not part of this object but the api supports it
3279 $className = 'CRM_Activity_BAO_Activity';
3282 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);