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
,
815 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
818 'id' => $result->case_id
,
819 'cid' => $result->contact_id
,
826 elseif ($field == 'case_status') {
827 if (in_array($result->$field, $caseStatus)) {
828 $casesList[$result->case_id
]['class'] = "status-urgent";
831 $casesList[$result->case_id
]['class'] = "status-normal";
836 $caseManagerContact = self
::getCaseManagerContact($result->case_type_name
, $result->case_id
);
837 if (!empty($caseManagerContact)) {
838 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
839 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
842 //do check user permissions for edit/view activity.
843 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
844 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
846 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
848 $casesList[$result->case_id
]['activity_type_id'], $userID
850 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
852 $casesList[$result->case_id
]['activity_type_id'], $userID
861 * Function to get the summary of cases counts by type and status.
863 static function getCasesSummary($allCases = TRUE, $userID) {
864 $caseSummary = array();
866 //validate access for civicase.
867 if (!self
::accessCiviCase()) {
871 //validate access for all cases.
872 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
876 $caseTypes = CRM_Case_PseudoConstant
::caseType();
877 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
878 $caseTypes = array_flip($caseTypes);
880 // get statuses as headers for the table
881 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
882 foreach ($caseStatuses as $key => $name) {
883 $caseSummary['headers'][$key]['status'] = $name;
884 $caseSummary['headers'][$key]['url'] = $url . $key;
887 // build rows with actual data
889 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
899 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
900 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
903 $seperator = CRM_Core_DAO
::VALUE_SEPARATOR
;
906 SELECT case_status.label AS case_status, status_id, case_type.label AS case_type,
907 REPLACE(case_type_id,'{$seperator}','') AS case_type_id, case_relationship.contact_id_b
909 LEFT JOIN civicrm_option_group option_group_case_type ON ( option_group_case_type.name = 'case_type' )
910 LEFT JOIN civicrm_option_value case_type ON ( civicrm_case.case_type_id = case_type.value
911 AND option_group_case_type.id = case_type.option_group_id )
912 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
913 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
914 AND option_group_case_status.id = case_status.option_group_id )
915 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
916 AND case_relationship.contact_id_b = {$userID})
918 {$myCaseWhereClause} {$myGroupByClause}";
920 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
921 while ($res->fetch()) {
922 if (CRM_Utils_Array
::value($res->case_type
, $rows) && CRM_Utils_Array
::value($res->case_status
, $rows[$res->case_type
])) {
923 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
926 $rows[$res->case_type
][$res->case_status
] = array(
928 'url' => CRM_Utils_System
::url('civicrm/case/search',
929 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
934 $caseSummary['rows'] = array_merge($caseTypes, $rows);
940 * Function to get Case roles
942 * @param int $contactID contact id
943 * @param int $caseID case id
944 * @return returns case role / relationships
948 static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
950 SELECT civicrm_relationship.id as civicrm_relationship_id,
951 civicrm_contact.sort_name as sort_name,
952 civicrm_email.email as email,
953 civicrm_phone.phone as phone,
954 civicrm_relationship.contact_id_b as civicrm_contact_id,
955 civicrm_relationship.contact_id_a as client_id,
956 civicrm_relationship_type.label_a_b as relation,
957 civicrm_relationship_type.id as relation_type
958 FROM civicrm_relationship
959 INNER JOIN civicrm_relationship_type ON civicrm_relationship.relationship_type_id = civicrm_relationship_type.id
960 INNER JOIN civicrm_contact ON civicrm_relationship.contact_id_b = civicrm_contact.id
961 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
962 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id )
963 WHERE civicrm_relationship.contact_id_a = %1 AND civicrm_relationship.case_id = %2';
967 1 => array($contactID, 'Positive'),
968 2 => array($caseID, 'Positive'),
971 if ($relationshipID) {
972 $query .= ' AND civicrm_relationship.id = %3 ';
973 $params[3] = array($relationshipID, 'Integer');
975 $dao = CRM_Core_DAO
::executeQuery($query, $params);
978 while ($dao->fetch()) {
979 $rid = $dao->civicrm_relationship_id
;
980 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
981 $values[$rid]['relation'] = $dao->relation
;
982 $values[$rid]['name'] = $dao->sort_name
;
983 $values[$rid]['email'] = $dao->email
;
984 $values[$rid]['phone'] = $dao->phone
;
985 $values[$rid]['relation_type'] = $dao->relation_type
;
986 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
987 $values[$rid]['client_id'] = $dao->client_id
;
995 * Function to get Case Activities
997 * @param int $caseID case id
998 * @param array $params posted params
999 * @param int $contactID contact id
1001 * @return returns case activities
1005 static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
1008 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1009 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1010 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1011 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1013 // CRM-5081 - formatting the dates to omit seconds.
1014 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
1015 $select = "SELECT count(ca.id) as ismultiple, ca.id as id,
1016 ca.activity_type_id as type,
1017 ca.activity_type_id as activity_type_id,
1018 cc.sort_name as reporter,
1019 cc.id as reporter_id,
1020 acc.sort_name AS assignee,
1021 acc.id AS assignee_id,
1022 DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
1023 ca.activity_date_time,
1024 DATE_ADD(NOW(), INTERVAL 1 YEAR)
1025 ), '%Y%m%d%H%i00') as overdue_date,
1026 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,
1027 ca.status_id as status,
1028 ca.subject as subject,
1029 ca.is_deleted as deleted,
1030 ca.priority_id as priority,
1031 ca.weight as weight,
1032 GROUP_CONCAT(ef.file_id) as attachment_ids ";
1035 FROM civicrm_case_activity cca
1036 INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id
1037 INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}
1038 INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id
1039 INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'
1040 INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id
1041 AND cov.value = ca.activity_type_id AND cov.is_active = 1
1042 LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id
1043 LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'
1044 LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'
1045 LEFT JOIN civicrm_activity_contact caa
1046 ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}
1047 LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id ";
1049 $where = 'WHERE cca.case_id= %1
1050 AND ca.is_current_revision = 1';
1052 if (CRM_Utils_Array
::value('reporter_id', $params)) {
1053 $where .= " AND cac.contact_id = " . CRM_Utils_Type
::escape($params['reporter_id'], 'Integer');
1056 if (CRM_Utils_Array
::value('status_id', $params)) {
1057 $where .= " AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
1060 if (CRM_Utils_Array
::value('activity_deleted', $params)) {
1061 $where .= " AND ca.is_deleted = 1";
1064 $where .= " AND ca.is_deleted = 0";
1067 if (CRM_Utils_Array
::value('activity_type_id', $params)) {
1068 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1071 if (CRM_Utils_Array
::value('activity_date_low', $params)) {
1072 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1074 if (CRM_Utils_Array
::value('activity_date_high', $params)) {
1075 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1076 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1079 if (!empty($fromActivityDate)) {
1080 $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
1083 if (!empty($toActivityDate)) {
1084 $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
1087 // hack to handle to allow initial sorting to be done by query
1088 if (CRM_Utils_Array
::value('sortname', $params) == 'undefined') {
1089 $params['sortname'] = NULL;
1092 if (CRM_Utils_Array
::value('sortorder', $params) == 'undefined') {
1093 $params['sortorder'] = NULL;
1096 $sortname = CRM_Utils_Array
::value('sortname', $params);
1097 $sortorder = CRM_Utils_Array
::value('sortorder', $params);
1099 $groupBy = " GROUP BY ca.id ";
1101 if (!$sortname AND !$sortorder) {
1102 // CRM-5081 - added id to act like creation date
1103 $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1106 $sort = "{$sortname} {$sortorder}";
1107 $sort = CRM_Utils_Type
::escape($sort, 'String');
1108 $orderBy = " ORDER BY $sort ";
1109 if ($sortname != 'display_date') {
1110 $orderBy .= ', display_date DESC';
1114 $page = CRM_Utils_Array
::value('page', $params);
1115 $rp = CRM_Utils_Array
::value('rp', $params);
1124 $start = (($page - 1) * $rp);
1125 $query = $select . $from . $where . $groupBy . $orderBy;
1127 $params = array(1 => array($caseID, 'Integer'));
1128 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1129 $params['total'] = $dao->N
;
1131 //FIXME: need to optimize/cache these queries
1132 $limit = " LIMIT $start, $rp";
1136 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1139 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1140 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
1141 $activityPriority = CRM_Core_PseudoConstant
::get('CRM_Activity_DAO_Activity', 'priority_id');
1143 $url = CRM_Utils_System
::url("civicrm/case/activity",
1144 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1148 if ($context == 'fulltext') {
1149 $contextUrl = "&context={$context}";
1151 $editUrl = "{$url}&action=update{$contextUrl}";
1152 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1153 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1154 $viewTitle = ts('View this activity.');
1155 $statusTitle = ts('Edit status');
1157 $emailActivityTypeIDs = array(
1158 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1162 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1168 $emailActivityTypeIDs = array(
1169 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1173 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1179 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1181 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1182 $compStatusValues = array();
1183 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1184 foreach ($compStatusNames as $name) {
1185 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1187 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view",
1188 "reset=1&cid=", FALSE, NULL, FALSE
1190 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1191 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1194 $session = CRM_Core_Session
::singleton();
1195 $userID = $session->get('userID');
1198 while ($dao->fetch()) {
1200 $allowView = self
::checkPermission($dao->id
, 'view', $dao->activity_type_id
, $userID);
1201 $allowEdit = self
::checkPermission($dao->id
, 'edit', $dao->activity_type_id
, $userID);
1202 $allowDelete = self
::checkPermission($dao->id
, 'delete', $dao->activity_type_id
, $userID);
1204 //do not have sufficient permission
1205 //to access given case activity record.
1206 if (!$allowView && !$allowEdit && !$allowDelete) {
1210 $values[$dao->id
]['id'] = $dao->id
;
1211 $values[$dao->id
]['type'] = $activityTypes[$dao->type
]['label'];
1213 $reporterName = $dao->reporter
;
1214 if ($hasViewContact) {
1215 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id
. '">' . $dao->reporter
. '</a>';
1217 $values[$dao->id
]['reporter'] = $reporterName;
1218 $targetNames = CRM_Activity_BAO_ActivityContact
::getNames($dao->id
, $targetID);
1219 $targetContactUrls = $withContacts = array();
1220 foreach ($targetNames as $targetId => $targetName) {
1221 if (!in_array($targetId, $clientIds)) {
1222 $withContacts[$targetId] = $targetName;
1225 foreach ($withContacts as $cid => $name) {
1226 if ($hasViewContact) {
1227 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1229 $targetContactUrls[] = $name;
1231 $values[$dao->id
]['with_contacts'] = implode('; ', $targetContactUrls);
1233 $values[$dao->id
]['display_date'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1234 $values[$dao->id
]['status'] = $activityStatus[$dao->status
];
1236 //check for view activity.
1237 $subject = (empty($dao->subject
)) ?
'(' . ts('no subject') . ')' : $dao->subject
;
1239 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id
. ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1241 $values[$dao->id
]['subject'] = $subject;
1243 // add activity assignee to activity selector. CRM-4485.
1244 if (isset($dao->assignee
)) {
1245 if ($dao->ismultiple
== 1) {
1246 if ($dao->reporter_id
!= $dao->assignee_id
) {
1247 $values[$dao->id
]['reporter'] .= ($hasViewContact) ?
' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee
;
1249 $values[$dao->id
]['assignee'] = $dao->assignee
;
1252 $values[$dao->id
]['reporter'] .= ' / ' . ts('(multiple)');
1256 $additionalUrl = "&id={$dao->id}";
1257 if (!$dao->deleted
) {
1258 //hide edit link of activity type email.CRM-4530.
1259 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1260 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1262 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1269 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1272 elseif (!$caseDeleted) {
1273 $url = '<a href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1274 $values[$dao->id
]['status'] = $values[$dao->id
]['status'] . '<br /> (deleted)';
1277 //check for operations.
1278 if (self
::checkPermission($dao->id
, 'Move To Case', $dao->activity_type_id
)) {
1279 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id
. ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1281 if (self
::checkPermission($dao->id
, 'Copy To Case', $dao->activity_type_id
)) {
1282 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id
. ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1284 // if there are file attachments we will return how many and, if only one, add a link to it
1285 if (!empty($dao->attachment_ids
)) {
1286 $attachmentIDs = explode(',', $dao->attachment_ids
);
1287 $values[$dao->id
]['no_attachments'] = count($attachmentIDs);
1288 if ($values[$dao->id
]['no_attachments'] == 1) {
1289 // if there is only one it's easy to do a link - otherwise just flag it
1290 $attachmentViewUrl = CRM_Utils_System
::url(
1292 "reset=1&eid=" . $dao->id
. "&id=" . $dao->attachment_ids
,
1297 $url .= " | " . "<a href=$attachmentViewUrl >" . ts('View Attachment') . '</a> ';
1302 $values[$dao->id
]['links'] = $url;
1303 $values[$dao->id
]['class'] = "";
1305 if (!empty($dao->priority
)) {
1306 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1307 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-urgent ";
1309 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1310 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . "priority-low ";
1314 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1315 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-completed";
1318 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1319 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-overdue";
1322 $values[$dao->id
]['class'] = $values[$dao->id
]['class'] . " status-scheduled";
1327 $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>';
1336 * Function to get Case Related Contacts
1338 * @param int $caseID case id
1339 * @param boolean $skipDetails if true include details of contacts
1341 * @return returns $searchRows array of returnproperties
1345 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1347 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1348 FROM civicrm_relationship cr
1349 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1350 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1351 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1352 WHERE cr.case_id = %1 AND ce.is_primary= 1
1355 $params = array(1 => array($caseID, 'Integer'));
1356 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1358 while ($dao->fetch()) {
1360 $values[$dao->id
] = 1;
1364 'contact_id' => $dao->id
,
1365 'display_name' => $dao->name
,
1366 'sort_name' => $dao->sort_name
,
1367 'role' => $dao->role
,
1368 'email' => $dao->email
,
1378 * Function that sends e-mail copy of activity
1380 * @param int $activityId activity Id
1381 * @param array $contacts array of related contact
1386 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1391 $tplParams = $activityInfo = array();
1392 //if its a case activity
1394 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1395 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1396 if (CRM_Utils_Array
::value($activityTypeId, $nonCaseActivityTypes)) {
1397 $anyActivity = TRUE;
1400 $anyActivity = FALSE;
1402 $tplParams['isCaseActivity'] = 1;
1403 $tplParams['client_id'] = $clientId;
1406 $anyActivity = TRUE;
1409 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1410 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1412 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1414 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1416 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1418 $tplParams['activity'] = $activityInfo;
1419 foreach ($tplParams['activity']['fields'] as $k => $val) {
1420 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1421 $activitySubject = $val['value'];
1425 $session = CRM_Core_Session
::singleton();
1426 // CRM-8926 If user is not logged in, use the activity creator as userID
1427 if (!($userID = $session->get('userID'))) {
1428 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1431 //also create activities simultaneously of this copy.
1432 $activityParams = array();
1434 $activityParams['source_record_id'] = $activityId;
1435 $activityParams['source_contact_id'] = $userID;
1436 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1437 $activityParams['activity_date_time'] = date('YmdHis');
1438 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1439 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1440 $activityParams['case_id'] = $caseId;
1441 $activityParams['is_auto'] = 0;
1442 $activityParams['target_id'] = $clientId;
1444 $tplParams['activitySubject'] = $activitySubject;
1446 // if it’s a case activity, add hashed id to the template (CRM-5916)
1448 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1452 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1454 $receiptFrom = "$name <$address>";
1456 $recordedActivityParams = array();
1458 foreach ($contacts as $mail => $info) {
1459 $tplParams['contact'] = $info;
1460 self
::buildPermissionLinks($tplParams, $activityParams);
1462 $displayName = CRM_Utils_Array
::value('display_name', $info);
1464 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1466 'groupName' => 'msg_tpl_workflow_case',
1467 'valueName' => 'case_activity',
1468 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1469 'tplParams' => $tplParams,
1470 'from' => $receiptFrom,
1471 'toName' => $displayName,
1473 'attachments' => $attachments,
1477 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1478 $activityParams['details'] = $message;
1480 if (!empty($result[$info['contact_id']])) {
1482 * Really only need to record one activity with all the targets combined.
1483 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1484 * but it's always the same content at the moment.
1486 if (empty($recordedActivityParams)) {
1487 $recordedActivityParams = $activityParams;
1490 $recordedActivityParams['subject'] .= "; $displayName";
1492 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1495 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1499 if (!empty($recordedActivityParams)) {
1500 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1502 //create case_activity record if its case activity.
1504 $caseParams = array(
1505 'activity_id' => $activity->id
,
1506 'case_id' => $caseId,
1508 self
::processCaseActivity($caseParams);
1516 * Retrieve count of activities having a particular type, and
1517 * associated with a particular case.
1519 * @param int $caseId ID of the case
1520 * @param int $activityTypeId ID of the activity type
1527 static function getCaseActivityCount($caseId, $activityTypeId) {
1528 $queryParam = array(
1529 1 => array($caseId, 'Integer'),
1530 2 => array($activityTypeId, 'Integer'),
1532 $query = "SELECT count(ca.id) as countact
1533 FROM civicrm_activity ca
1534 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1535 WHERE ca.activity_type_id = %2
1536 AND cca.case_id = %1
1537 AND ca.is_deleted = 0";
1539 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1540 if ($dao->fetch()) {
1541 return $dao->countact
;
1548 * Create an activity for a case via email
1550 * @param int $file email sent
1552 * @return $activity object of newly creted activity via email
1557 static function recordActivityViaEmail($file) {
1558 if (!file_exists($file) ||
1561 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1566 $result = CRM_Utils_Mail_Incoming
::parse($file);
1567 if ($result['is_error']) {
1571 foreach ($result['to'] as $to) {
1574 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1575 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1577 if ($replacement !== $to['email']) {
1578 $caseId = $replacement;
1579 //if caseId is invalid, return as error file
1580 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1581 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1590 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1591 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1592 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1594 if (CRM_Utils_Array
::value($result['from']['id'], $contactDetails)) {
1596 $params['subject'] = $result['subject'];
1597 $params['activity_date_time'] = $result['date'];
1598 $params['details'] = $result['body'];
1599 $params['source_contact_id'] = $result['from']['id'];
1600 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1605 $details = CRM_Case_PseudoConstant
::caseActivityType();
1607 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1608 $result['body'], $matches
1611 if (!empty($matches) && isset($matches[1])) {
1612 $activityType = trim($matches[1]);
1613 if (isset($details[$activityType])) {
1614 $params['activity_type_id'] = $details[$activityType]['id'];
1617 if (!isset($params['activity_type_id'])) {
1618 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1622 $activity = CRM_Activity_BAO_Activity
::create($params);
1624 $caseParams = array(
1625 'activity_id' => $activity->id
,
1626 'case_id' => $caseId,
1628 self
::processCaseActivity($caseParams);
1631 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1632 array(1 => $result['from']['email'])
1639 * Function to retrieve the scheduled activity type and date
1641 * @param array $cases Array of contact and case id
1643 * @return array $activityInfo Array of scheduled activity type and date
1649 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1650 $session = CRM_Core_Session
::singleton();
1651 $userID = $session->get('userID');
1653 $caseID = implode(',', $cases['case_id']);
1654 $contactID = implode(',', $cases['contact_id']);
1657 AND civicrm_case_contact.contact_id IN( {$contactID} )
1658 AND civicrm_case.id IN( {$caseID})
1659 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1661 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1663 $res = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1665 $activityInfo = array();
1666 while ($res->fetch()) {
1667 if ($type == 'upcoming') {
1668 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1669 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1672 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1673 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1677 return $activityInfo;
1681 * combine all the exportable fields from the lower levels object
1683 * @return array array of exportable Fields
1687 static function &exportableFields() {
1688 if (!self
::$_exportableFields) {
1689 if (!self
::$_exportableFields) {
1690 self
::$_exportableFields = array();
1693 $fields = CRM_Case_DAO_Case
::export();
1694 $fields['case_role'] = array('title' => ts('Role in Case'));
1695 $fields['case_type'] = array(
1696 'title' => ts('Case Type'),
1697 'name' => 'case_type',
1699 $fields['case_status'] = array(
1700 'title' => ts('Case Status'),
1701 'name' => 'case_status',
1704 self
::$_exportableFields = $fields;
1706 return self
::$_exportableFields;
1710 * Restore the record that are associated with this case
1712 * @param int $caseId id of the case to restore
1714 * @return true if success.
1718 static function restoreCase($caseId) {
1719 //restore activities
1720 $activities = self
::getCaseActivityDates($caseId);
1722 foreach ($activities as $value) {
1723 CRM_Activity_BAO_Activity
::restoreActivity($value);
1727 $case = new CRM_Case_DAO_Case();
1728 $case->id
= $caseId;
1729 $case->is_deleted
= 0;
1732 //CRM-7364, enable relationships
1733 self
::enableDisableCaseRelationships($caseId, TRUE);
1737 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1738 $globalContacts = array();
1740 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1741 $settings = $settingsProcessor->run();
1742 if (!empty($settings)) {
1743 $groupInfo['name'] = $settings['groupname'];
1744 if ($groupInfo['name']) {
1745 $searchParams = array('name' => $groupInfo['name']);
1747 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1749 $groupInfo['id'] = $results['id'];
1750 $groupInfo['title'] = $results['title'];
1751 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1752 $return = array('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1753 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1754 list($globalContacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1756 if ($returnOnlyCount) {
1757 return $globalContacts;
1761 foreach ($globalContacts as $idx => $contact) {
1762 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1768 return $globalContacts;
1772 * Convenience function to get both case contacts and global in one array
1774 static function getRelatedAndGlobalContacts($caseId) {
1775 $relatedContacts = self
::getRelatedContacts($caseId);
1777 $groupInfo = array();
1778 $globalContacts = self
::getGlobalContacts($groupInfo);
1780 //unset values which are not required.
1781 foreach ($globalContacts as $k => & $v) {
1782 unset($v['email_id']);
1783 unset($v['group_contact_id']);
1784 unset($v['status']);
1786 $v['role'] = $groupInfo['title'];
1788 //include multiple listings for the same contact/different roles.
1789 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1790 return $relatedGlobalContacts;
1794 * Function to get Case ActivitiesDueDates with given criteria.
1796 * @param int $caseID case id
1797 * @param array $criteriaParams given criteria
1798 * @param boolean $latestDate if set newest or oldest date is selceted.
1800 * @return returns case activities due dates
1804 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1806 $selectDate = " ca.activity_date_time";
1807 $where = $groupBy = ' ';
1814 if (CRM_Utils_Array
::value('activity_type_id', $criteriaParams)) {
1815 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1816 $where .= " AND ca.is_current_revision = 1";
1817 $groupBy .= " GROUP BY ca.activity_type_id";
1820 if (CRM_Utils_Array
::value('newest', $criteriaParams)) {
1821 $selectDate = " max(ca.activity_date_time) ";
1824 $selectDate = " min(ca.activity_date_time) ";
1828 $query = "SELECT ca.id, {$selectDate} as activity_date
1829 FROM civicrm_activity ca
1830 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1831 WHERE cc.id = %1 {$where} {$groupBy}";
1833 $params = array(1 => array($caseID, 'Integer'));
1834 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1836 while ($dao->fetch()) {
1837 $values[$dao->id
]['id'] = $dao->id
;
1838 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1845 * Function to create activities when Case or Other roles assigned/modified/deleted.
1847 * @param int $caseID case id
1848 * @param int $relationshipId relationship id
1849 * @param int $relContactId case role assignee contactId.
1851 * @return void on success creates activity and case activity
1855 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1856 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1860 $queryParam = array();
1861 if (is_array($relationshipId)) {
1862 $relationshipId = implode(',', $relationshipId);
1863 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1866 $relationshipClause = " civicrm_relationship.id = %1";
1867 $queryParam[1] = array($relationshipId, 'Positive');
1871 SELECT cc.display_name as clientName,
1872 cca.display_name as assigneeContactName,
1873 civicrm_relationship.case_id as caseId,
1874 civicrm_relationship_type.label_a_b as relation_a_b,
1875 civicrm_relationship_type.label_b_a as relation_b_a,
1876 civicrm_relationship.contact_id_b as rel_contact_id,
1877 civicrm_relationship.contact_id_a as assign_contact_id
1878 FROM civicrm_relationship_type, civicrm_relationship
1879 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1880 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1881 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1883 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1885 while ($dao->fetch()) {
1886 //to get valid assignee contact(s).
1887 if (isset($dao->caseId
) ||
$dao->rel_contact_id
!= $contactId) {
1888 $caseRelationship = $dao->relation_a_b
;
1889 $assigneContactName = $dao->clientName
;
1890 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1893 $caseRelationship = $dao->relation_b_a
;
1894 $assigneContactName = $dao->assigneeContactName
;
1895 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1899 $session = CRM_Core_Session
::singleton();
1900 $activityParams = array(
1901 'source_contact_id' => $session->get('userID'),
1902 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1903 'activity_date_time' => date('YmdHis'),
1904 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1907 //if $relContactId is passed, role is added or modified.
1908 if (!empty($relContactId)) {
1909 $activityParams['assignee_contact_id'] = $assigneContactIds;
1911 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1917 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1923 $activityParams['activity_type_id'] = $activityTypeID;
1925 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1927 //create case_activity record.
1928 $caseParams = array(
1929 'activity_id' => $activity->id
,
1930 'case_id' => $caseId,
1933 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1937 * Function to get case manger
1938 * contact which is assigned a case role of case manager.
1940 * @param int $caseType case type
1941 * @param int $caseId case id
1943 * @return array $caseManagerContact array of contact on success otherwise empty
1947 static function getCaseManagerContact($caseType, $caseId) {
1948 if (!$caseType ||
!$caseId) {
1952 $caseManagerContact = array();
1953 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1955 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1957 if (!empty($managerRoleId)) {
1958 $managerRoleQuery = "
1959 SELECT civicrm_contact.id as casemanager_id,
1960 civicrm_contact.sort_name as casemanager
1961 FROM civicrm_contact
1962 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1963 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1964 WHERE civicrm_case.id = %2";
1966 $managerRoleParams = array(
1967 1 => array($managerRoleId, 'Integer'),
1968 2 => array($caseId, 'Integer'),
1971 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1972 if ($dao->fetch()) {
1973 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1974 $caseManagerContact['casemanager'] = $dao->casemanager
;
1978 return $caseManagerContact;
1982 * Get all cases with no end dates
1984 * @return array of case and related data keyed on case id
1986 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1987 //params from ajax call.
1988 $where = array('( ca.end_date is null )');
1989 if ($caseType = CRM_Utils_Array
::value('case_type', $params)) {
1990 $where[] = "( ov.label LIKE '%$caseType%' )";
1992 if ($sortName = CRM_Utils_Array
::value('sort_name', $params)) {
1993 $config = CRM_Core_Config
::singleton();
1994 $search = ($config->includeWildCardInName
) ?
"%$sortName%" : "$sortName%";
1995 $where[] = "( sort_name LIKE '$search' )";
1997 if (is_array($excludeCaseIds) &&
1998 !CRM_Utils_System
::isNull($excludeCaseIds)
2000 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2002 if ($excludeDeleted) {
2003 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2006 //filter for permissioned cases.
2007 $filterCases = array();
2008 $doFilterCases = FALSE;
2009 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2010 $doFilterCases = TRUE;
2011 $session = CRM_Core_Session
::singleton();
2012 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2014 $whereClause = implode(' AND ', $where);
2017 if ($limit = CRM_Utils_Array
::value('limit', $params)) {
2018 $limitClause = "LIMIT 0, $limit";
2022 SELECT c.id as contact_id,
2025 ca.subject as case_subject,
2026 ov.label as case_type,
2027 ca.start_date as start_date
2028 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2029 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2030 INNER JOIN civicrm_option_group og ON og.name='case_type'
2031 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2032 WHERE {$whereClause}
2033 ORDER BY c.sort_name
2036 $dao = CRM_Core_DAO
::executeQuery($query);
2037 $unclosedCases = array();
2038 while ($dao->fetch()) {
2039 if ($doFilterCases && !array_key_exists($dao->id
, $filterCases)) {
2042 $unclosedCases[$dao->id
] = array(
2043 'sort_name' => $dao->sort_name
,
2044 'case_type' => $dao->case_type
,
2045 'contact_id' => $dao->contact_id
,
2046 'start_date' => $dao->start_date
,
2047 'case_subject' => $dao->case_subject
,
2052 return $unclosedCases;
2055 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2056 $whereConditions = array();
2057 if ($excludeDeleted) {
2058 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2061 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2063 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2064 static $accessibleCaseIds;
2065 if (!is_array($accessibleCaseIds)) {
2066 $session = CRM_Core_Session
::singleton();
2067 $accessibleCaseIds = array_keys(self
::getCases(FALSE, $session->get('userID')));
2069 //no need of further processing.
2070 if (empty($accessibleCaseIds)) {
2073 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2077 if (!empty($whereConditions)) {
2078 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2082 SELECT count( civicrm_case.id )
2084 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2087 return CRM_Core_DAO
::singleValueQuery($query);
2091 * Retrieve cases related to particular contact.
2093 * @param int $contactId contact id
2094 * @param boolean $excludeDeleted do not include deleted cases.
2096 * @return an array of cases.
2100 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2106 $whereClause = "civicrm_case_contact.contact_id = %1";
2107 if ($excludeDeleted) {
2108 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2112 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2114 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2115 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2116 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2117 AND case_type_og.id = case_type_ov.option_group_id )
2118 WHERE {$whereClause}";
2120 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($contactId, 'Integer')));
2121 while ($dao->fetch()) {
2122 $cases[$dao->id
] = array(
2123 'case_id' => $dao->id
,
2124 'case_type' => $dao->case_type
,
2125 'case_start_date' => $dao->start_date
,
2134 * Retrieve related cases for give case.
2136 * @param int $mainCaseId id of main case
2137 * @param int $contactId id of contact
2138 * @param boolean $excludeDeleted do not include deleted cases.
2140 * @return an array of related cases.
2144 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2145 //FIXME : do check for permissions.
2147 $relatedCases = array();
2148 if (!$mainCaseId ||
!$contactId) {
2149 return $relatedCases;
2152 $linkActType = array_search('Link Cases',
2153 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
2155 if (!$linkActType) {
2156 return $relatedCases;
2159 $whereClause = "mainCase.id = %2";
2160 if ($excludeDeleted) {
2161 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2164 //1. first fetch related case ids.
2166 SELECT relCaseAct.case_id
2167 FROM civicrm_case mainCase
2168 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2169 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2170 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2171 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2172 WHERE $whereClause";
2174 $dao = CRM_Core_DAO
::executeQuery($query, array(
2175 1 => array($linkActType, 'Integer'),
2176 2 => array($mainCaseId, 'Integer'),
2178 $relatedCaseIds = array();
2179 while ($dao->fetch()) {
2180 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2184 // there are no related cases.
2185 if (empty($relatedCaseIds)) {
2186 return $relatedCases;
2189 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2190 if ($excludeDeleted) {
2191 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2194 //filter for permissioned cases.
2195 $filterCases = array();
2196 $doFilterCases = FALSE;
2197 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2198 $doFilterCases = TRUE;
2199 $session = CRM_Core_Session
::singleton();
2200 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
2203 //2. fetch the details of related cases.
2205 SELECT relCase.id as id,
2206 case_type_ov.label as case_type,
2207 client.display_name as client_name,
2208 client.id as client_id
2209 FROM civicrm_case relCase
2210 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2211 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2212 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2213 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2214 AND case_type_og.id = case_type_ov.option_group_id )
2215 WHERE {$whereClause}";
2217 $dao = CRM_Core_DAO
::executeQuery($query);
2218 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2219 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2221 while ($dao->fetch()) {
2223 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2224 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2225 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2226 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2228 $clientView = $dao->client_name
;
2229 if ($hasViewContact) {
2230 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2233 $relatedCases[$dao->id
] = array(
2234 'case_id' => $dao->id
,
2235 'case_type' => $dao->case_type
,
2236 'client_name' => $clientView,
2237 'links' => $caseView,
2242 return $relatedCases;
2246 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2248 * @see CRM_Dedupe_Merger::cpTables()
2250 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2252 static function mergeContacts($mainContactId, $otherContactId) {
2253 self
::mergeCases($mainContactId, NULL, $otherContactId);
2257 * Function perform two task.
2258 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2259 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2261 * @param int $mainContactId contact id of main contact record.
2262 * @param int $mainCaseId case id of main case record.
2263 * @param int $otherContactId contact id of record which is going to merge.
2264 * @param int $otherCaseId case id of record which is going to merge.
2269 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2270 $otherCaseId = NULL, $changeClient = FALSE) {
2271 $moveToTrash = TRUE;
2273 $duplicateContacts = FALSE;
2274 if ($mainContactId && $otherContactId &&
2275 $mainContactId != $otherContactId
2277 $duplicateContacts = TRUE;
2280 $duplicateCases = FALSE;
2281 if ($mainCaseId && $otherCaseId &&
2282 $mainCaseId != $otherCaseId
2284 $duplicateCases = TRUE;
2287 $mainCaseIds = array();
2288 if (!$duplicateContacts && !$duplicateCases) {
2289 return $mainCaseIds;
2292 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2293 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2294 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2295 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2296 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2297 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2299 $processCaseIds = array($otherCaseId);
2300 if ($duplicateContacts && !$duplicateCases) {
2301 if ($changeClient) {
2302 $processCaseIds = array($mainCaseId);
2305 //get all case ids for other contact.
2306 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2308 if (!is_array($processCaseIds)) {
2313 $session = CRM_Core_Session
::singleton();
2314 $currentUserId = $session->get('userID');
2316 // copy all cases and connect to main contact id.
2317 foreach ($processCaseIds as $otherCaseId) {
2318 if ($duplicateContacts) {
2319 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2320 $mainCaseId = $mainCase->id
;
2325 // CRM-11662 Copy Case custom data
2326 $extends = array('case');
2327 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2329 foreach ($groupTree as $groupID => $group) {
2330 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2331 foreach ($group['fields'] as $fieldID => $field) {
2332 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2336 foreach ($table as $tableName => $tableColumns) {
2337 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2338 $tableColumns[0] = $mainCaseId;
2339 $select = 'SELECT ' . implode(', ', $tableColumns);
2340 $from = ' FROM ' . $tableName;
2341 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2342 $query = $insert . $select . $from . $where;
2343 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
2349 $mainCaseIds[] = $mainCaseId;
2350 //insert record for case contact.
2351 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2352 $otherCaseContact->case_id
= $otherCaseId;
2353 $otherCaseContact->find();
2354 while ($otherCaseContact->fetch()) {
2355 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2356 $mainCaseContact->case_id
= $mainCaseId;
2357 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2358 if ($mainCaseContact->contact_id
== $otherContactId) {
2359 $mainCaseContact->contact_id
= $mainContactId;
2361 //avoid duplicate object.
2362 if (!$mainCaseContact->find(TRUE)) {
2363 $mainCaseContact->save();
2365 $mainCaseContact->free();
2367 $otherCaseContact->free();
2369 elseif (!$otherContactId) {
2370 $otherContactId = $mainContactId;
2373 if (!$mainCaseId ||
!$otherCaseId ||
2374 !$mainContactId ||
!$otherContactId
2379 // get all activities for other case.
2380 $otherCaseActivities = array();
2381 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2383 //for duplicate cases do not process singleton activities.
2384 $otherActivityIds = $singletonActivityIds = array();
2385 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2386 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2387 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2390 $otherActivityIds[] = $otherActId;
2392 if ($duplicateCases) {
2393 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2396 FROM civicrm_activity
2397 WHERE activity_type_id = $openCaseType
2398 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2399 $dao = CRM_Core_DAO
::executeQuery($sql);
2400 while ($dao->fetch()) {
2401 $singletonActivityIds[] = $dao->id
;
2407 // migrate all activities and connect to main contact.
2408 $copiedActivityIds = $activityMappingIds = array();
2409 sort($otherActivityIds);
2410 foreach ($otherActivityIds as $otherActivityId) {
2412 //for duplicate cases -
2413 //do not migrate singleton activities.
2414 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2418 //migrate activity record.
2419 $otherActivity = new CRM_Activity_DAO_Activity();
2420 $otherActivity->id
= $otherActivityId;
2421 if (!$otherActivity->find(TRUE)) {
2425 $mainActVals = array();
2426 $mainActivity = new CRM_Activity_DAO_Activity();
2427 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2428 $mainActivity->copyValues($mainActVals);
2429 $mainActivity->id
= NULL;
2430 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2431 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2435 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2439 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2442 $mainActivity->save();
2443 $mainActivityId = $mainActivity->id
;
2444 if (!$mainActivityId) {
2448 $activityMappingIds[$otherActivityId] = $mainActivityId;
2449 // insert log of all activities
2450 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2452 $otherActivity->free();
2453 $mainActivity->free();
2454 $copiedActivityIds[] = $otherActivityId;
2456 //create case activity record.
2457 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2458 $mainCaseActivity->case_id
= $mainCaseId;
2459 $mainCaseActivity->activity_id
= $mainActivityId;
2460 $mainCaseActivity->save();
2461 $mainCaseActivity->free();
2463 //migrate source activity.
2464 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2465 $otherSourceActivity->activity_id
= $otherActivityId;
2466 $otherSourceActivity->record_type_id
= $sourceID;
2467 $otherSourceActivity->find();
2468 while ($otherSourceActivity->fetch()) {
2469 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2470 $mainActivitySource->record_type_id
= $sourceID;
2471 $mainActivitySource->activity_id
= $mainActivityId;
2472 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2473 if ($mainActivitySource->contact_id
== $otherContactId) {
2474 $mainActivitySource->contact_id
= $mainContactId;
2476 //avoid duplicate object.
2477 if (!$mainActivitySource->find(TRUE)) {
2478 $mainActivitySource->save();
2480 $mainActivitySource->free();
2482 $otherSourceActivity->free();
2484 //migrate target activities.
2485 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2486 $otherTargetActivity->activity_id
= $otherActivityId;
2487 $otherTargetActivity->record_type_id
= $targetID;
2488 $otherTargetActivity->find();
2489 while ($otherTargetActivity->fetch()) {
2490 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2491 $mainActivityTarget->record_type_id
= $targetID;
2492 $mainActivityTarget->activity_id
= $mainActivityId;
2493 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2494 if ($mainActivityTarget->contact_id
== $otherContactId) {
2495 $mainActivityTarget->contact_id
= $mainContactId;
2497 //avoid duplicate object.
2498 if (!$mainActivityTarget->find(TRUE)) {
2499 $mainActivityTarget->save();
2501 $mainActivityTarget->free();
2503 $otherTargetActivity->free();
2505 //migrate assignee activities.
2506 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2507 $otherAssigneeActivity->activity_id
= $otherActivityId;
2508 $otherAssigneeActivity->record_type_id
= $assigneeID;
2509 $otherAssigneeActivity->find();
2510 while ($otherAssigneeActivity->fetch()) {
2511 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2512 $mainAssigneeActivity->activity_id
= $mainActivityId;
2513 $mainAssigneeActivity->record_type_id
= $assigneeID;
2514 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2515 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2516 $mainAssigneeActivity->contact_id
= $mainContactId;
2518 //avoid duplicate object.
2519 if (!$mainAssigneeActivity->find(TRUE)) {
2520 $mainAssigneeActivity->save();
2522 $mainAssigneeActivity->free();
2524 $otherAssigneeActivity->free();
2526 // copy custom fields and attachments
2528 'activityID' => $otherActivityId,
2529 'mainActivityId' => $mainActivityId,
2531 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2534 //copy case relationship.
2535 if ($duplicateContacts) {
2536 //migrate relationship records.
2537 $otherRelationship = new CRM_Contact_DAO_Relationship();
2538 $otherRelationship->case_id
= $otherCaseId;
2539 $otherRelationship->find();
2540 $otherRelationshipIds = array();
2541 while ($otherRelationship->fetch()) {
2542 $otherRelVals = array();
2543 $updateOtherRel = FALSE;
2544 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2546 $mainRelationship = new CRM_Contact_DAO_Relationship();
2547 $mainRelationship->copyValues($otherRelVals);
2548 $mainRelationship->id
= NULL;
2549 $mainRelationship->case_id
= $mainCaseId;
2550 if ($mainRelationship->contact_id_a
== $otherContactId) {
2551 $updateOtherRel = TRUE;
2552 $mainRelationship->contact_id_a
= $mainContactId;
2555 //case creator change only when we merge user contact.
2556 if ($mainRelationship->contact_id_b
== $otherContactId) {
2557 //do not change creator for change client.
2558 if (!$changeClient) {
2559 $updateOtherRel = TRUE;
2560 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2563 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2564 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2566 //avoid duplicate object.
2567 if (!$mainRelationship->find(TRUE)) {
2568 $mainRelationship->save();
2570 $mainRelationship->free();
2572 //get the other relationship ids to update end date.
2573 if ($updateOtherRel) {
2574 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2577 $otherRelationship->free();
2579 //update other relationships end dates
2580 if (!empty($otherRelationshipIds)) {
2581 $sql = 'UPDATE civicrm_relationship
2582 SET end_date = CURDATE()
2583 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2584 CRM_Core_DAO
::executeQuery($sql);
2588 //move other case to trash.
2589 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2594 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2595 if ($changeClient) {
2596 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2597 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2599 $mergeActType = array_search('Reassigned Case', $activityTypes);
2600 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2603 2 => $otherContactDisplayName,
2604 3 => $mainContactDisplayName,
2609 elseif ($duplicateContacts) {
2610 $mergeActType = array_search('Merge Case', $activityTypes);
2611 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2614 2 => $otherContactId,
2615 3 => $mainContactId,
2621 $mergeActType = array_search('Merge Case', $activityTypes);
2622 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2623 if (!empty($copiedActivityIds)) {
2625 SELECT id, subject, activity_date_time, activity_type_id
2626 FROM civicrm_activity
2627 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2628 $dao = CRM_Core_DAO
::executeQuery($sql);
2629 while ($dao->fetch()) {
2630 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2631 if ($dao->subject
) {
2632 $mergeActSubjectDetails .= " :: {$dao->subject}";
2634 $mergeActSubjectDetails .= "<br />";
2639 //create merge activity record.
2640 $activityParams = array(
2641 'subject' => $mergeActSubject,
2642 'details' => $mergeActSubjectDetails,
2643 'status_id' => array_search('Completed', $activityStatuses),
2644 'activity_type_id' => $mergeActType,
2645 'source_contact_id' => $mainContactId,
2646 'activity_date_time' => date('YmdHis'),
2649 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2650 $mergeActivityId = $mergeActivity->id
;
2651 if (!$mergeActivityId) {
2654 $mergeActivity->free();
2656 //connect merge activity to case.
2657 $mergeCaseAct = array(
2658 'case_id' => $mainCaseId,
2659 'activity_id' => $mergeActivityId,
2662 self
::processCaseActivity($mergeCaseAct);
2664 return $mainCaseIds;
2668 * Validate contact permission for
2669 * edit/view on activity record and build links.
2671 * @param array $tplParams params to be sent to template for sending email.
2672 * @param array $activityParams info of the activity.
2677 static function buildPermissionLinks(&$tplParams, $activityParams) {
2678 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2679 'activity_type_id', 'id'
2682 if (CRM_Utils_Array
::value('isCaseActivity', $tplParams)) {
2683 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2684 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2687 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2688 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2691 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2692 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2696 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2697 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2700 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2701 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2707 * Validate contact permission for
2708 * given operation on activity record.
2710 * @param int $activityId activity record id.
2711 * @param string $operation user operation.
2712 * @param int $actTypeId activity type id.
2713 * @param int $contactId contact id/if not pass consider logged in
2714 * @param boolean $checkComponent do we need to check component enabled.
2716 * @return boolean $allow true/false
2719 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2721 if (!$actTypeId && $activityId) {
2722 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2725 if (!$activityId ||
!$operation ||
!$actTypeId) {
2729 //do check for civicase component enabled.
2730 if ($checkComponent) {
2731 static $componentEnabled;
2732 if (!isset($componentEnabled)) {
2733 $config = CRM_Core_Config
::singleton();
2734 $componentEnabled = FALSE;
2735 if (in_array('CiviCase', $config->enableComponents
)) {
2736 $componentEnabled = TRUE;
2739 if (!$componentEnabled) {
2744 //do check for cases.
2745 $caseActOperations = array(
2752 if (in_array($operation, $caseActOperations)) {
2753 static $unclosedCases;
2754 if (!is_array($unclosedCases)) {
2755 $unclosedCases = self
::getUnclosedCases();
2757 if ($operation == 'File On Case') {
2758 $allow = (empty($unclosedCases)) ?
FALSE : TRUE;
2761 $allow = (count($unclosedCases) > 1) ?
TRUE : FALSE;
2765 $actionOperations = array('view', 'edit', 'delete');
2766 if (in_array($operation, $actionOperations)) {
2768 //do cache when user has non/supper permission.
2769 static $allowOperations;
2771 if (!is_array($allowOperations) ||
2772 !array_key_exists($operation, $allowOperations)
2776 $session = CRM_Core_Session
::singleton();
2777 $contactId = $session->get('userID');
2780 //check for permissions.
2781 $permissions = array(
2783 'access my cases and activities',
2784 'access all cases and activities',
2787 'access my cases and activities',
2788 'access all cases and activities',
2790 'delete' => array('delete activities'),
2793 //check for core permission.
2794 $hasPermissions = array();
2795 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2796 if (is_array($checkPermissions)) {
2797 foreach ($checkPermissions as $per) {
2798 if (CRM_Core_Permission
::check($per)) {
2799 $hasPermissions[$operation][] = $per;
2805 if (!empty($hasPermissions)) {
2806 //need to check activity object specific.
2807 if (in_array($operation, array(
2812 //do we have supper permission.
2813 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2814 $allowOperations[$operation] = $allow = TRUE;
2817 //user has only access to my cases and activity.
2818 //here object specific permmions come in picture.
2820 //edit - contact must be source or assignee
2821 //view - contact must be source/assignee/target
2822 $isTarget = $isAssignee = $isSource = FALSE;
2823 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2824 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2825 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2826 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2828 $target = new CRM_Activity_DAO_ActivityContact();
2829 $target->record_type_id
= $targetID;
2830 $target->activity_id
= $activityId;
2831 $target->contact_id
= $contactId;
2832 if ($target->find(TRUE)) {
2836 $assignee = new CRM_Activity_DAO_ActivityContact();
2837 $assignee->activity_id
= $activityId;
2838 $assignee->record_type_id
= $assigneeID;
2839 $assignee->contact_id
= $contactId;
2840 if ($assignee->find(TRUE)) {
2844 $source = new CRM_Activity_DAO_ActivityContact();
2845 $source->activity_id
= $activityId;
2846 $source->record_type_id
= $sourceID;
2847 $source->contact_id
= $contactId;
2848 if ($source->find(TRUE)) {
2852 if ($operation == 'edit') {
2853 if ($isAssignee ||
$isSource) {
2857 if ($operation == 'view') {
2858 if ($isTarget ||
$isAssignee ||
$isSource) {
2864 elseif (is_array($hasPermissions[$operation])) {
2865 $allowOperations[$operation] = $allow = TRUE;
2869 //contact do not have permission.
2870 $allowOperations[$operation] = FALSE;
2875 //here contact might have supper/non permission.
2876 $allow = $allowOperations[$operation];
2880 //do further only when operation is granted.
2882 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2884 //get the activity type name.
2885 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2887 //do not allow multiple copy / edit action.
2888 $singletonNames = array(
2898 //do not allow to delete these activities, CRM-4543
2899 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2901 //allow edit operation.
2902 $allowEditNames = array('Open Case');
2904 // do not allow File on Case
2905 $doNotFileNames = array(
2908 'Change Case Status',
2909 'Change Case Start Date',
2916 if (in_array($actTypeName, $singletonNames)) {
2918 if ($operation == 'File On Case') {
2919 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2921 if (in_array($operation, $actionOperations)) {
2923 if ($operation == 'edit') {
2924 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2926 elseif ($operation == 'delete') {
2927 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2931 if ($allow && ($operation == 'delete') &&
2932 in_array($actTypeName, $doNotDeleteNames)
2937 if ($allow && ($operation == 'File On Case') &&
2938 in_array($actTypeName, $doNotFileNames)
2943 //check settings file for masking actions
2944 //on the basis the activity types
2945 //hide Edit link if activity type is NOT editable
2946 //(special case activities).CRM-5871
2947 if ($allow && in_array($operation, $actionOperations)) {
2948 static $actionFilter = array();
2949 if (!array_key_exists($operation, $actionFilter)) {
2950 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2951 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2953 if (array_key_exists($operation, $actionFilter[$operation]) &&
2954 in_array($actTypeId, $actionFilter[$operation][$operation])
2965 * since we drop 'access CiviCase', allow access
2966 * if user has 'access my cases and activities'
2967 * or 'access all cases and activities'
2969 static function accessCiviCase() {
2970 static $componentEnabled;
2971 if (!isset($componentEnabled)) {
2972 $componentEnabled = FALSE;
2973 $config = CRM_Core_Config
::singleton();
2974 if (in_array('CiviCase', $config->enableComponents
)) {
2975 $componentEnabled = TRUE;
2978 if (!$componentEnabled) {
2982 if (CRM_Core_Permission
::check('access my cases and activities') ||
2983 CRM_Core_Permission
::check('access all cases and activities')
2992 * Function to check whether activity is a case Activity
2994 * @param int $activityID activity id
2996 * @return boolean $isCaseActivity true/false
2998 static function isCaseActivity($activityID) {
2999 $isCaseActivity = FALSE;
3001 $params = array(1 => array($activityID, 'Integer'));
3002 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3003 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
3004 $isCaseActivity = TRUE;
3008 return $isCaseActivity;
3012 * Function to get all the case type ids currently in use
3015 * @return array $caseTypeIds
3017 static function getUsedCaseType() {
3018 static $caseTypeIds;
3020 if (!is_array($caseTypeIds)) {
3021 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3023 $dao = CRM_Core_DAO
::executeQuery($query);
3024 $caseTypeIds = array();
3025 while ($dao->fetch()) {
3026 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
3029 $caseTypeIds[] = $typeId[1];
3033 return $caseTypeIds;
3037 * Function to get all the case status ids currently in use
3040 * @return array $caseStatusIds
3042 static function getUsedCaseStatuses() {
3043 static $caseStatusIds;
3045 if (!is_array($caseStatusIds)) {
3046 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3048 $dao = CRM_Core_DAO
::executeQuery($query);
3049 $caseStatusIds = array();
3050 while ($dao->fetch()) {
3051 $caseStatusIds[] = $dao->status_id
;
3055 return $caseStatusIds;
3059 * Function to get all the encounter medium ids currently in use
3062 static function getUsedEncounterMediums() {
3065 if (!is_array($mediumIds)) {
3066 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3068 $dao = CRM_Core_DAO
::executeQuery($query);
3069 $mediumIds = array();
3070 while ($dao->fetch()) {
3071 $mediumIds[] = $dao->medium_id
;
3079 * Function to check case configuration.
3081 * @return array $configured
3083 static function isCaseConfigured($contactId = NULL) {
3084 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3086 //lets check for case configured.
3087 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
3088 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
3089 if (!$configured['configured']) {
3090 //do check for case type and case status.
3091 $caseTypes = CRM_Case_PseudoConstant
::caseType('label', FALSE);
3092 if (!empty($caseTypes)) {
3093 $configured['configured'] = TRUE;
3094 if (!$configured['configured']) {
3095 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
3096 if (!empty($caseStatuses)) {
3097 $configured['configured'] = TRUE;
3102 if ($configured['configured']) {
3103 //do check for active case type and case status.
3104 $caseTypes = CRM_Case_PseudoConstant
::caseType();
3105 if (!empty($caseTypes)) {
3106 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
3107 if (!empty($caseStatuses)) {
3108 $configured['allowToAddNewCase'] = TRUE;
3112 //do we need to redirect user to case admin.
3113 if (!$configured['allowToAddNewCase'] && $contactId) {
3114 //check for current contact case count.
3115 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3116 //redirect user to case admin page.
3117 if (!$currentContatCasesCount) {
3118 $configured['redirectToCaseAdmin'] = TRUE;
3127 * Used during case component enablement and during ugprade
3129 static function createCaseViews() {
3130 $dao = new CRM_Core_DAO();
3132 $sql = self
::createCaseViewsQuery('upcoming');
3133 CRM_Core_Error
::ignoreException();
3135 CRM_Core_Error
::setCallback();
3136 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3140 // Above error doesn't get caught?
3141 CRM_Core_Error
::ignoreException();
3142 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3143 CRM_Core_Error
::setCallback();
3144 if (is_null($doublecheck)) {
3148 $sql = self
::createCaseViewsQuery('recent');
3149 CRM_Core_Error
::ignoreException();
3151 CRM_Core_Error
::setCallback();
3152 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3156 // Above error doesn't get caught?
3157 CRM_Core_Error
::ignoreException();
3158 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3159 CRM_Core_Error
::setCallback();
3160 if (is_null($doublecheck)) {
3168 * helper function, also used by the upgrade in case of error
3170 static function createCaseViewsQuery($section = 'upcoming') {
3172 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
3175 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3176 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3177 FROM civicrm_case_activity ca
3178 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3179 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3180 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3184 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3185 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3186 FROM civicrm_case_activity ca
3187 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3188 WHERE a.activity_date_time <= NOW()
3189 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3190 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3197 * Function to add/copy relationships, when new client is added for a case
3199 * @param int $caseId case id
3200 * @param int $contactId contact id / new client id
3204 static function addCaseRelationships($caseId, $contactId) {
3205 // get the case role / relationships for the case
3206 $caseRelationships = new CRM_Contact_DAO_Relationship();
3207 $caseRelationships->case_id
= $caseId;
3208 $caseRelationships->find();
3209 $relationshipTypes = array();
3211 // make sure we don't add duplicate relationships of same relationship type.
3212 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3214 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3216 // add relationship for new client.
3217 $newRelationship = new CRM_Contact_DAO_Relationship();
3218 $newRelationship->copyValues($values);
3219 $newRelationship->id
= NULL;
3220 $newRelationship->case_id
= $caseId;
3221 $newRelationship->contact_id_a
= $contactId;
3222 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3223 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3225 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3226 if (!$newRelationship->find(TRUE)) {
3227 $newRelationship->save();
3229 $newRelationship->free();
3231 // store relationship type of newly created relationship
3232 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3237 * Function to get the list of clients for a case
3239 * @param int $caseId
3241 * @return array $clients associated array with client ids
3244 static function getCaseClients($caseId) {
3246 $caseContact = new CRM_Case_DAO_CaseContact();
3247 $caseContact->case_id
= $caseId;
3248 $caseContact->find();
3250 while ($caseContact->fetch()) {
3251 $clients[] = $caseContact->contact_id
;
3258 * Get options for a given case field.
3259 * @see CRM_Core_DAO::buildOptions
3261 * @param String $fieldName
3262 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3263 * @param Array $props: whatever is known about this dao object
3265 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3266 $className = __CLASS__
;
3268 switch ($fieldName) {
3269 // This field is not part of this object but the api supports it
3271 $className = 'CRM_Activity_BAO_Activity';
3274 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);