3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 * This class contains the functions for Case Management.
37 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
40 * Static field for all the case information that we can potentially export.
44 public static $_exportableFields = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Is CiviCase enabled?
58 public static function enabled() {
59 $config = CRM_Core_Config
::singleton();
60 return in_array('CiviCase', $config->enableComponents
);
64 * Create a case object.
66 * The function extracts all the params it needs to initialize the create a
67 * case object. the params array could contain additional unused name/value
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
73 * @return CRM_Case_BAO_Case
75 public static function add(&$params) {
76 $caseDAO = new CRM_Case_DAO_Case();
77 $caseDAO->copyValues($params);
78 $result = $caseDAO->save();
79 // Get other case values (required by XML processor), this adds to $result array
85 * Takes an associative array and creates a case object.
87 * @param array $params
88 * (reference) an assoc array of name/value pairs.
90 * @return CRM_Case_BAO_Case
92 public static function &create(&$params) {
93 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
94 unset($params['created_date']);
95 unset($params['modified_date']);
96 $caseStatus = CRM_Case_PseudoConstant
::caseStatus('name');
97 // for resolved case the end date should set to now
98 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
99 $params['end_date'] = date("Ymd");
102 $transaction = new CRM_Core_Transaction();
104 if (!empty($params['id'])) {
105 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
108 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
111 $case = self
::add($params);
113 if (!empty($params['custom']) &&
114 is_array($params['custom'])
116 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
119 if (is_a($case, 'CRM_Core_Error')) {
120 $transaction->rollback();
124 if (!empty($params['id'])) {
125 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
128 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
130 $transaction->commit();
132 //we are not creating log for case
133 //since case log can be tracked using log for activity.
138 * Process case activity add/delete
139 * takes an associative array and
141 * @param array $params
142 * (reference ) an assoc array of name/value pairs.
145 public static function processCaseActivity(&$params) {
146 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
147 $caseActivityDAO->activity_id
= $params['activity_id'];
148 $caseActivityDAO->case_id
= $params['case_id'];
150 $caseActivityDAO->find(TRUE);
151 $caseActivityDAO->save();
155 * Get the case subject for Activity.
157 * @param int $activityId
160 * @return string|null
162 public static function getCaseSubject($activityId) {
163 $caseActivity = new CRM_Case_DAO_CaseActivity();
164 $caseActivity->activity_id
= $activityId;
165 if ($caseActivity->find(TRUE)) {
166 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
175 * @param string $colName
180 public static function getCaseType($caseId, $colName = 'title') {
182 SELECT civicrm_case_type.{$colName} FROM civicrm_case
183 LEFT JOIN civicrm_case_type ON
184 civicrm_case.case_type_id = civicrm_case_type.id
185 WHERE civicrm_case.id = %1";
187 $queryParams = array(1 => array($caseId, 'Integer'));
189 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
193 * Delete the record that are associated with this case.
194 * record are deleted from case
197 * Id of the case to delete.
199 * @param bool $moveToTrash
204 public static function deleteCase($caseId, $moveToTrash = FALSE) {
205 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
208 $activities = self
::getCaseActivityDates($caseId);
210 foreach ($activities as $value) {
211 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
216 $transaction = new CRM_Core_Transaction();
218 $case = new CRM_Case_DAO_Case();
221 $result = $case->delete();
222 $transaction->commit();
225 $result = $case->is_deleted
= 1;
230 // CRM-7364, disable relationships
231 self
::enableDisableCaseRelationships($caseId, FALSE);
233 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
235 // remove case from recent items.
240 CRM_Utils_Recent
::del($caseRecent);
248 * Enable disable case related relationships.
252 * @param bool $enable
255 public static function enableDisableCaseRelationships($caseId, $enable) {
256 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
257 if (!empty($contactIds)) {
258 foreach ($contactIds as $cid) {
259 $roles = self
::getCaseRoles($cid, $caseId);
260 if (!empty($roles)) {
261 $relationshipIds = implode(',', array_keys($roles));
262 $enable = (int) $enable;
263 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
264 WHERE id IN ( {$relationshipIds} )";
265 CRM_Core_DAO
::executeQuery($query);
272 * Retrieve contact_id by case_id.
277 * @param int $contactID
278 * @param int $startArrayAt This is to support legacy calls to Case.Get API which may rely on the first array index being set to 1
282 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
283 $caseContact = new CRM_Case_DAO_CaseContact();
284 $caseContact->case_id
= $caseId;
285 $caseContact->find();
286 $contactArray = array();
287 $count = $startArrayAt;
288 while ($caseContact->fetch()) {
289 if ($contactID != $caseContact->contact_id
) {
290 $contactArray[$count] = $caseContact->contact_id
;
295 return $contactArray;
299 * Look up a case using an activity ID.
301 * @param int $activityId
303 * @return int, case ID
305 public static function getCaseIdByActivityId($activityId) {
306 $originalId = CRM_Core_DAO
::singleValueQuery(
307 'SELECT original_id FROM civicrm_activity WHERE id = %1',
308 array('1' => array($activityId, 'Integer'))
310 $caseId = CRM_Core_DAO
::singleValueQuery(
311 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
313 '1' => array($activityId, 'Integer'),
314 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
321 * Retrieve contact names by caseId.
328 public static function getContactNames($caseId) {
329 $contactNames = array();
331 return $contactNames;
335 SELECT contact_a.sort_name name,
336 contact_a.display_name as display_name,
338 contact_a.birth_date as birth_date,
341 FROM civicrm_contact contact_a
342 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
343 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
344 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
345 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
346 ORDER BY civicrm_case_contact.id";
348 $dao = CRM_Core_DAO
::executeQuery($query,
349 array(1 => array($caseId, 'Integer'))
351 while ($dao->fetch()) {
352 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
353 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
354 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
355 $contactNames[$dao->cid
]['email'] = $dao->email
;
356 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
357 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
358 $contactNames[$dao->cid
]['role'] = ts('Client');
361 return $contactNames;
365 * Retrieve case_id by contact_id.
367 * @param int $contactID
368 * @param bool $includeDeleted
369 * Include the deleted cases in result.
370 * @param null $caseType
374 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
377 FROM civicrm_case_contact cc
378 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
380 if (isset($caseType)) {
382 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
383 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
385 if (!isset($caseType)) {
386 $query .= "WHERE cc.contact_id = %1";
388 if (!$includeDeleted) {
389 $query .= " AND ca.is_deleted = 0";
392 $params = array(1 => array($contactID, 'Integer'));
393 $dao = CRM_Core_DAO
::executeQuery($query, $params);
395 $caseArray = array();
396 while ($dao->fetch()) {
397 $caseArray[] = $dao->id
;
404 * @param string $type
406 * @param string $condition
410 public static function getCaseActivityCountQuery($type = 'upcoming', $userID, $condition = NULL) {
411 return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self
::getCaseActivityQuery($type, $userID, $condition));
415 * @param string $type
417 * @param string $condition
418 * @param string $limit
419 * @param string $order
423 public static function getCaseActivityQuery($type = 'upcoming', $userID, $condition = NULL, $limit = NULL, $order = NULL) {
424 $selectClauses = array(
425 'civicrm_case.id as case_id',
426 'civicrm_case.subject as case_subject',
427 'civicrm_contact.id as contact_id',
428 'civicrm_contact.sort_name as sort_name',
429 'civicrm_phone.phone as phone',
430 'civicrm_contact.contact_type as contact_type',
431 'civicrm_contact.contact_sub_type as contact_sub_type',
432 't_act.activity_type_id as activity_type_id',
433 'civicrm_case.case_type_id as case_type_id',
434 'civicrm_case.status_id as case_status_id',
435 't_act.status_id as status_id',
436 'civicrm_case.start_date as case_start_date',
437 "GROUP_CONCAT(DISTINCT IF(case_relationship.contact_id_b = $userID, case_relation_type.label_a_b, case_relation_type.label_b_a) SEPARATOR ', ') as case_role",
438 't_act.activity_date_time as activity_date_time',
439 't_act.id as activity_id',
442 $query = CRM_Contact_BAO_Query
::appendAnyValueToSelect($selectClauses, 'case_id');
446 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
447 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id
453 // civicrm_view_case_activity_upcoming and
454 // civicrm_view_case_activity_recent are views that show the next
455 // scheduled and most recent not-scheduled activity on each case,
458 INNER JOIN civicrm_view_case_activity_$type t_act
459 ON t_act.case_id = civicrm_case.id
465 LEFT JOIN civicrm_case_activity ca4
466 ON civicrm_case.id = ca4.case_id
467 LEFT JOIN civicrm_activity t_act
468 ON t_act.id = ca4.activity_id
469 AND t_act.is_current_revision = 1
474 LEFT JOIN civicrm_phone
475 ON civicrm_phone.contact_id = civicrm_contact.id
476 AND civicrm_phone.is_primary = 1
477 LEFT JOIN civicrm_relationship case_relationship
478 ON ((case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID})
479 OR (case_relationship.contact_id_b = civicrm_case_contact.contact_id AND case_relationship.contact_id_a = {$userID}))
480 AND case_relationship.is_active
481 AND case_relationship.case_id = civicrm_case.id
482 LEFT JOIN civicrm_relationship_type case_relation_type
483 ON case_relation_type.id = case_relationship.relationship_type_id
484 AND case_relation_type.id = case_relationship.relationship_type_id
488 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
489 $query .= " WHERE (1) AND $condition ";
491 $query .= " GROUP BY case_id ";
493 $query .= ($order) ?
: ' ORDER BY activity_date_time ASC';
503 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
505 * @param bool $allCases
506 * @param array $params
507 * @param string $context
508 * @param bool $getCount
513 public static function getCases($allCases = TRUE, $params = array(), $context = 'dashboard', $getCount = FALSE) {
515 $casesList = array();
517 // validate access for own cases.
518 if (!self
::accessCiviCase()) {
519 return $getCount ?
0 : $casesList;
522 // Return cached value instead of re-running query
523 if (isset(Civi
::$statics[__CLASS__
]['totalCount']) && $getCount) {
524 return Civi
::$statics[__CLASS__
]['totalCount'];
527 $type = CRM_Utils_Array
::value('type', $params, 'upcoming');
528 $userID = CRM_Core_Session
::singleton()->get('userID');
530 // validate access for all cases.
531 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
535 $whereClauses = array('civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1');
538 $whereClauses[] = "(case_relationship.contact_id_b = {$userID} OR case_relationship.contact_id_a = {$userID})";
539 $whereClauses[] = 'case_relationship.is_active';
541 if (empty($params['status_id']) && ($type == 'upcoming' ||
$type == 'any')) {
542 $whereClauses[] = "civicrm_case.status_id != " . CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
545 foreach (array('case_type_id', 'status_id') as $column) {
546 if (!empty($params[$column])) {
547 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
550 $condition = implode(' AND ', $whereClauses);
552 Civi
::$statics[__CLASS__
]['totalCount'] = $totalCount = CRM_Core_DAO
::singleValueQuery(self
::getCaseActivityCountQuery($type, $userID, $condition));
556 $casesList['total'] = $totalCount;
559 if (!empty($params['rp'])) {
560 $params['offset'] = ($params['page'] - 1) * $params['rp'];
561 $params['rowCount'] = $params['rp'];
562 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
563 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
568 if (!empty($params['sortBy'])) {
569 if (strstr($params['sortBy'], 'date ')) {
570 $params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
572 $order = "ORDER BY " . $params['sortBy'];
575 $query = self
::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
576 $result = CRM_Core_DAO
::executeQuery($query);
578 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
579 $actions = CRM_Case_Selector_Search
::links();
581 // check is the user has view/edit signer permission
582 $permissions = array(CRM_Core_Permission
::VIEW
);
583 if (CRM_Core_Permission
::check('access all cases and activities') ||
584 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
586 $permissions[] = CRM_Core_Permission
::EDIT
;
588 if (CRM_Core_Permission
::check('delete in CiviCase')) {
589 $permissions[] = CRM_Core_Permission
::DELETE
;
591 $mask = CRM_Core_Action
::mask($permissions);
593 // Pseudoconstants to populate labels
594 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
595 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
596 $caseTypeTitles = CRM_Case_PseudoConstant
::caseType('title', FALSE);
597 $activityTypeLabels = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
599 foreach ($result->fetchAll() as $case) {
600 $key = $case['case_id'];
601 $casesList[$key] = array();
602 $casesList[$key]['DT_RowId'] = $case['case_id'];
603 $casesList[$key]['DT_RowAttr'] = array('data-entity' => 'case', 'data-id' => $case['case_id']);
604 $casesList[$key]['DT_RowClass'] = "crm-entity";
606 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
608 CRM_Utils_System
::url('civicrm/case/details', array('caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type))
611 $phone = empty($case['phone']) ?
'' : '<br /><span class="description">' . $case['phone'] . '</span>';
612 $casesList[$key]['contact_id'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
613 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $case['contact_id'])),
619 $casesList[$key]['subject'] = $case['case_subject'];
620 $casesList[$key]['case_status'] = CRM_Utils_Array
::value($case['case_status_id'], $caseStatuses);
621 if ($case['case_status_id'] == CRM_Case_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
622 $casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
624 $casesList[$key]['case_type'] = CRM_Utils_Array
::value($case['case_type_id'], $caseTypeTitles);
625 $casesList[$key]['case_role'] = CRM_Utils_Array
::value('case_role', $case, '---');
626 $casesList[$key]['manager'] = self
::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
628 $casesList[$key]['date'] = CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels);
629 if ($actId = CRM_Utils_Array
::value('activity_id', $case)) {
630 if (self
::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
631 if ($type == 'recent') {
632 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
633 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id'])),
635 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
639 $status = CRM_Utils_Date
::overdue($case['activity_date_time']) ?
'status-overdue' : 'status-scheduled';
640 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
642 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id'])),
644 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
648 if (isset($case['activity_type_id']) && self
::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
649 $casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil"></i></a>',
650 CRM_Utils_System
::url('civicrm/case/activity', array('reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId)),
655 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date
::customFormat($case['activity_date_time']);
656 $casesList[$key]['links'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
658 'id' => $case['case_id'],
659 'cid' => $case['contact_id'],
664 'case.actions.primary',
674 * Get the summary of cases counts by type and status.
676 * @param bool $allCases
679 public static function getCasesSummary($allCases = TRUE) {
680 $caseSummary = array();
682 //validate access for civicase.
683 if (!self
::accessCiviCase()) {
687 $userID = CRM_Core_Session
::singleton()->get('userID');
689 //validate access for all cases.
690 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
694 $caseTypes = CRM_Case_PseudoConstant
::caseType();
695 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
696 $caseTypes = array_flip($caseTypes);
698 // get statuses as headers for the table
699 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
700 foreach ($caseStatuses as $key => $name) {
701 $caseSummary['headers'][$key]['status'] = $name;
702 $caseSummary['headers'][$key]['url'] = $url . $key;
705 // build rows with actual data
707 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClauseA = $myCaseWhereClauseB = '';
713 $myGroupByClauseB = ' GROUP BY civicrm_case.id';
718 $myCaseWhereClauseA = " AND case_relationship.contact_id_a = {$userID} AND case_relationship.is_active ";
719 $myGroupByClauseA = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_a)";
720 $myCaseWhereClauseB = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
721 $myGroupByClauseB = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_b)";
723 $myGroupByClauseB .= ", case_status.label, status_id, case_type_id, civicrm_case.id";
724 $myGroupByClauseA = $myGroupByClauseB;
725 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
727 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
728 case_type_id, case_relationship.contact_id_b as case_contact
730 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
731 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
732 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
733 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
734 AND option_group_case_status.id = case_status.option_group_id )
735 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
736 AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
737 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
738 {$myCaseWhereClauseB} {$myGroupByClauseB}
740 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
741 case_type_id, case_relationship.contact_id_a as case_contact
743 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
744 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
745 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
746 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
747 AND option_group_case_status.id = case_status.option_group_id )
748 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
749 AND case_relationship.contact_id_a = {$userID})
750 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
751 {$myCaseWhereClauseA} {$myGroupByClauseA}";
753 $res = CRM_Core_DAO
::executeQuery($query);
754 while ($res->fetch()) {
755 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
756 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
759 $rows[$res->case_type
][$res->case_status
] = array(
761 'url' => CRM_Utils_System
::url('civicrm/case/search',
762 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
767 $caseSummary['rows'] = array_merge($caseTypes, $rows);
775 * @param int $contactID
779 * @param int $relationshipID
780 * @param bool $activeOnly
783 * case role / relationships
786 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
788 SELECT rel.id as civicrm_relationship_id,
789 con.sort_name as sort_name,
790 civicrm_email.email as email,
791 civicrm_phone.phone as phone,
792 con.id as civicrm_contact_id,
793 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
794 civicrm_relationship_type.id as relation_type,
795 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
796 FROM civicrm_relationship rel
797 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
798 INNER JOIN civicrm_contact con ON ((con.id <> %1 AND con.id IN (rel.contact_id_a, rel.contact_id_b)) OR (con.id = %1 AND rel.contact_id_b = rel.contact_id_a AND rel.contact_id_a = %1 AND rel.is_active))
799 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
800 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
801 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
802 AND con.is_deleted = 0';
805 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
809 1 => array($contactID, 'Positive'),
810 2 => array($caseID, 'Positive'),
813 if ($relationshipID) {
814 $query .= ' AND rel.id = %3 ';
815 $params[3] = array($relationshipID, 'Integer');
817 $dao = CRM_Core_DAO
::executeQuery($query, $params);
820 while ($dao->fetch()) {
821 $rid = $dao->civicrm_relationship_id
;
822 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
823 $values[$rid]['relation'] = $dao->relation
;
824 $values[$rid]['name'] = $dao->sort_name
;
825 $values[$rid]['email'] = $dao->email
;
826 $values[$rid]['phone'] = $dao->phone
;
827 $values[$rid]['relation_type'] = $dao->relation_type
;
828 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
829 $values[$rid]['client_id'] = $contactID;
830 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
837 * Get Case Activities.
841 * @param array $params
843 * @param int $contactID
846 * @param null $context
848 * @param null $type (deprecated)
851 * Array of case activities
854 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
855 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
856 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
857 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
858 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
860 // CRM-5081 - formatting the dates to omit seconds.
861 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
863 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
865 ca.activity_type_id AS type,
866 ca.activity_type_id AS activity_type_id,
867 tcc.sort_name AS target_contact_name,
868 tcc.id AS target_contact_id,
869 scc.sort_name AS source_contact_name,
870 scc.id AS source_contact_id,
871 acc.sort_name AS assignee_contact_name,
872 acc.id AS assignee_contact_id,
874 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
875 ca.activity_date_time,
876 DATE_ADD(NOW(), INTERVAL 1 YEAR)
877 ), '%Y%m%d%H%i00') AS overdue_date,
878 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
879 ca.status_id AS status,
880 ca.subject AS subject,
881 ca.is_deleted AS deleted,
882 ca.priority_id AS priority,
884 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
887 FROM civicrm_case_activity cca
888 INNER JOIN civicrm_activity ca
889 ON ca.id = cca.activity_id
890 INNER JOIN civicrm_activity_contact cas
891 ON cas.activity_id = ca.id
892 AND cas.record_type_id = {$sourceID}
893 INNER JOIN civicrm_contact scc
894 ON scc.id = cas.contact_id
895 LEFT JOIN civicrm_activity_contact caa
896 ON caa.activity_id = ca.id
897 AND caa.record_type_id = {$assigneeID}
898 LEFT JOIN civicrm_contact acc
899 ON acc.id = caa.contact_id
900 LEFT JOIN civicrm_activity_contact cat
901 ON cat.activity_id = ca.id
902 AND cat.record_type_id = {$targetID}
903 LEFT JOIN civicrm_contact tcc
904 ON tcc.id = cat.contact_id
905 INNER JOIN civicrm_option_group cog
906 ON cog.name = 'activity_type'
907 INNER JOIN civicrm_option_value cov
908 ON cov.option_group_id = cog.id
909 AND cov.value = ca.activity_type_id
910 AND cov.is_active = 1
911 LEFT JOIN civicrm_entity_file ef
912 ON ef.entity_table = 'civicrm_activity'
913 AND ef.entity_id = ca.id
914 LEFT OUTER JOIN civicrm_option_group og
915 ON og.name = 'activity_status'
916 LEFT OUTER JOIN civicrm_option_value ov
917 ON ov.option_group_id=og.id
918 AND ov.name = 'Scheduled'";
921 WHERE cca.case_id= %1
922 AND ca.is_current_revision = 1';
924 if (!empty($params['source_contact_id'])) {
926 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
929 if (!empty($params['status_id'])) {
931 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
934 if (!empty($params['activity_deleted'])) {
936 AND ca.is_deleted = 1";
940 AND ca.is_deleted = 0";
943 if (!empty($params['activity_type_id'])) {
945 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
948 if (!empty($params['activity_date_low'])) {
949 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
951 if (!empty($fromActivityDate)) {
953 AND ca.activity_date_time >= '{$fromActivityDate}'";
956 if (!empty($params['activity_date_high'])) {
957 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
958 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
960 if (!empty($toActivityDate)) {
962 AND ca.activity_date_time <= '{$toActivityDate}'";
966 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
968 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
970 // CRM-5081 - added id to act like creation date
972 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
975 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
976 $orderBy = " ORDER BY $sortBy ";
979 $page = CRM_Utils_Array
::value('page', $params);
980 $rp = CRM_Utils_Array
::value('rp', $params);
988 $start = (($page - 1) * $rp);
989 $limit = " LIMIT $start, $rp";
991 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
992 $queryParams = array(1 => array($caseID, 'Integer'));
994 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
995 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
997 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
999 $compStatusValues = array_keys(
1000 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
1001 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
1005 $userID = CRM_Core_Session
::getLoggedInContactID();
1008 $caseActivities = [];
1010 while ($dao->fetch()) {
1011 $caseActivityId = $dao->id
;
1013 //Do we have permission to access given case activity record.
1014 if (!self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID)) {
1018 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1019 //Add classes to the row, via DataTables syntax
1020 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1022 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1023 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1026 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1027 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1030 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1034 if (!empty($dao->priority
)) {
1035 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1036 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1038 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1039 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1043 //Add data to the row for inline editing, via DataTable syntax
1044 $caseActivities[$caseActivityId]['DT_RowAttr'] = array();
1045 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1046 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1048 //Activity Date and Time
1049 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1052 $caseActivities[$caseActivityId]['subject'] = $dao->subject
;
1055 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1056 . $activityTypes[$dao->type
]['label'];
1058 // Activity Target (With Contact) (There can be more than one)
1059 $targetContact = self
::formatContactLink($dao->target_contact_id
, $dao->target_contact_name
);
1060 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1061 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1064 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1065 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1069 // Activity Source Contact (Reporter) (There can only be one)
1070 $sourceContact = self
::formatContactLink($dao->source_contact_id
, $dao->source_contact_name
);
1071 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1073 // Activity Assignee (There can be more than one)
1074 $assigneeContact = self
::formatContactLink($dao->assignee_contact_id
, $dao->assignee_contact_name
);
1075 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1076 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1079 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1080 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1084 // Activity Status Label for Case activities list
1086 if ($dao->deleted
) {
1087 $deleted = '<br /> ' . ts('(deleted)');
1089 $caseActivities[$caseActivityId]['status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status
) . $deleted;
1090 // if there are file attachments we will return how many
1091 if (!empty($dao->attachment_ids
)) {
1092 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1093 $caseActivity['no_attachments'] = count($attachmentIDs);
1096 $caseActivities[$caseActivityId]['links'] = CRM_Case_Selector_Search
::addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao);
1099 $caseActivitiesDT = array();
1100 $caseActivitiesDT['data'] = array_values($caseActivities);
1101 $caseActivitiesDT['recordsTotal'] = $caseCount;
1102 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1104 return $caseActivitiesDT;
1108 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1111 * @param $contactName
1115 private static function formatContactLink($contactId, $contactName) {
1116 if (empty($contactId)) {
1120 $hasViewContact = CRM_Contact_BAO_Contact_Permission
::allow($contactId);
1122 if ($hasViewContact) {
1123 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1124 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1127 return $contactName;
1132 * Get Case Related Contacts.
1134 * @param int $caseID
1136 * @param bool $includeDetails
1137 * If true include details of contacts.
1140 * array of return properties
1143 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1144 $caseRoles = array();
1145 if ($includeDetails) {
1146 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1148 // Most efficient way of retrieving definition is to also include case type id and name so the api doesn't have to look it up separately
1149 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition', 'contact_id'),
1151 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1152 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1158 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, cr.relationship_type_id, crt.label_b_a as role, crt.name_b_a as role_name, ce.email, cp.phone
1159 FROM civicrm_relationship cr
1160 JOIN civicrm_relationship_type crt
1161 ON crt.id = cr.relationship_type_id
1162 JOIN civicrm_contact cc
1163 ON cc.id = cr.contact_id_a
1164 AND cc.is_deleted <> 1
1165 LEFT JOIN civicrm_email ce
1166 ON ce.contact_id = cc.id
1167 AND ce.is_primary= 1
1168 LEFT JOIN civicrm_phone cp
1169 ON cp.contact_id = cc.id
1170 AND cp.is_primary= 1
1171 WHERE cr.case_id = %1
1173 AND cc.id NOT IN (%2)
1175 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, cr.relationship_type_id, crt.label_a_b as role, crt.name_a_b as role_name, ce.email, cp.phone
1176 FROM civicrm_relationship cr
1177 JOIN civicrm_relationship_type crt
1178 ON crt.id = cr.relationship_type_id
1179 JOIN civicrm_contact cc
1180 ON cc.id = cr.contact_id_b
1181 AND cc.is_deleted <> 1
1182 LEFT JOIN civicrm_email ce
1183 ON ce.contact_id = cc.id
1184 AND ce.is_primary= 1
1185 LEFT JOIN civicrm_phone cp
1186 ON cp.contact_id = cc.id
1187 AND cp.is_primary= 1
1188 WHERE cr.case_id = %1
1190 AND cc.id NOT IN (%2)
1193 1 => array($caseID, 'Integer'),
1194 2 => array(implode(',', $caseInfo['client_id']), 'String'),
1196 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1198 while ($dao->fetch()) {
1199 if (!$includeDetails) {
1200 $values[$dao->id
] = 1;
1204 'contact_id' => $dao->id
,
1205 'display_name' => $dao->name
,
1206 'sort_name' => $dao->sort_name
,
1207 'relationship_type_id' => $dao->relationship_type_id
,
1208 'role' => $dao->role
,
1209 'email' => $dao->email
,
1210 'phone' => $dao->phone
,
1212 // Add more info about the role (creator, manager)
1213 $role = CRM_Utils_Array
::value($dao->role_name
, $caseRoles);
1215 unset($role['name']);
1218 $values[] = $details;
1226 * Send e-mail copy of activity
1228 * @param int $clientId
1229 * @param int $activityId
1231 * @param array $contacts
1232 * Array of related contact.
1234 * @param null $attachments
1235 * @param int $caseId
1237 * @return bool |array
1239 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1244 $tplParams = $activityInfo = array();
1245 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1246 // If it's a case activity
1248 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1249 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1250 $anyActivity = TRUE;
1253 $anyActivity = FALSE;
1255 $tplParams['isCaseActivity'] = 1;
1256 $tplParams['client_id'] = $clientId;
1259 $anyActivity = TRUE;
1262 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1263 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1265 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1267 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1269 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1271 $tplParams['activityTypeName'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeId);
1272 $tplParams['activity'] = $activityInfo;
1273 foreach ($tplParams['activity']['fields'] as $k => $val) {
1274 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1275 $activitySubject = $val['value'];
1279 $session = CRM_Core_Session
::singleton();
1280 // CRM-8926 If user is not logged in, use the activity creator as userID
1281 if (!($userID = $session->get('userID'))) {
1282 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1285 //also create activities simultaneously of this copy.
1286 $activityParams = array();
1288 $activityParams['source_record_id'] = $activityId;
1289 $activityParams['source_contact_id'] = $userID;
1290 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1291 $activityParams['activity_date_time'] = date('YmdHis');
1292 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1293 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1294 $activityParams['case_id'] = $caseId;
1295 $activityParams['is_auto'] = 0;
1296 $activityParams['target_id'] = $clientId;
1298 $tplParams['activitySubject'] = $activitySubject;
1300 // if it’s a case activity, add hashed id to the template (CRM-5916)
1302 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1306 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1307 $receiptFrom = self
::getReceiptFrom($activityId);
1309 $recordedActivityParams = array();
1311 foreach ($contacts as $mail => $info) {
1312 $tplParams['contact'] = $info;
1313 self
::buildPermissionLinks($tplParams, $activityParams);
1315 $displayName = CRM_Utils_Array
::value('display_name', $info);
1317 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1319 'groupName' => 'msg_tpl_workflow_case',
1320 'valueName' => 'case_activity',
1321 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1322 'tplParams' => $tplParams,
1323 'from' => $receiptFrom,
1324 'toName' => $displayName,
1326 'attachments' => $attachments,
1330 $activityParams['subject'] = ts('%1 - copy sent to %2', [1 => $activitySubject, 2 => $displayName]);
1331 $activityParams['details'] = $message;
1333 if (!empty($result[$info['contact_id']])) {
1335 * Really only need to record one activity with all the targets combined.
1336 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1337 * but it's always the same content at the moment.
1339 if (empty($recordedActivityParams)) {
1340 $recordedActivityParams = $activityParams;
1343 $recordedActivityParams['subject'] .= "; $displayName";
1345 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1348 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1352 if (!empty($recordedActivityParams)) {
1353 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1355 //create case_activity record if its case activity.
1357 $caseParams = array(
1358 'activity_id' => $activity->id
,
1359 'case_id' => $caseId,
1361 self
::processCaseActivity($caseParams);
1369 * Retrieve count of activities having a particular type, and
1370 * associated with a particular case.
1372 * @param int $caseId
1374 * @param int $activityTypeId
1375 * ID of the activity type.
1379 public static function getCaseActivityCount($caseId, $activityTypeId) {
1380 $queryParam = array(
1381 1 => array($caseId, 'Integer'),
1382 2 => array($activityTypeId, 'Integer'),
1384 $query = "SELECT count(ca.id) as countact
1385 FROM civicrm_activity ca
1386 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1387 WHERE ca.activity_type_id = %2
1388 AND cca.case_id = %1
1389 AND ca.is_deleted = 0";
1391 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1392 if ($dao->fetch()) {
1393 return $dao->countact
;
1400 * Create an activity for a case via email.
1405 * @return array|void
1406 * $activity object of newly creted activity via email
1408 public static function recordActivityViaEmail($file) {
1409 if (!file_exists($file) ||
1412 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1417 $result = CRM_Utils_Mail_Incoming
::parse($file);
1418 if ($result['is_error']) {
1422 foreach ($result['to'] as $to) {
1425 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1426 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1428 if ($replacement !== $to['email']) {
1429 $caseId = $replacement;
1430 //if caseId is invalid, return as error file
1431 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1432 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1441 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1442 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1443 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1445 if (!empty($contactDetails[$result['from']['id']])) {
1447 $params['subject'] = $result['subject'];
1448 $params['activity_date_time'] = $result['date'];
1449 $params['details'] = $result['body'];
1450 $params['source_contact_id'] = $result['from']['id'];
1451 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1453 $details = CRM_Case_PseudoConstant
::caseActivityType();
1455 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1456 $result['body'], $matches
1459 if (!empty($matches) && isset($matches[1])) {
1460 $activityType = trim($matches[1]);
1461 if (isset($details[$activityType])) {
1462 $params['activity_type_id'] = $details[$activityType]['id'];
1465 if (!isset($params['activity_type_id'])) {
1466 $params['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
1470 $activity = CRM_Activity_BAO_Activity
::create($params);
1472 $caseParams = array(
1473 'activity_id' => $activity->id
,
1474 'case_id' => $caseId,
1476 self
::processCaseActivity($caseParams);
1479 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1480 array(1 => $result['from']['email'])
1487 * Retrieve the scheduled activity type and date.
1489 * @param array $cases
1490 * Array of contact and case id.
1492 * @param string $type
1495 * Array of scheduled activity type and date
1499 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1500 $session = CRM_Core_Session
::singleton();
1501 $userID = $session->get('userID');
1503 $caseID = implode(',', $cases['case_id']);
1504 $contactID = implode(',', $cases['contact_id']);
1506 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1507 AND civicrm_case.id IN( {$caseID})
1508 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1510 $query = self
::getCaseActivityQuery($type, $userID, $condition);
1511 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
1513 $res = CRM_Core_DAO
::executeQuery($query);
1515 $activityInfo = array();
1516 while ($res->fetch()) {
1517 if ($type == 'upcoming') {
1518 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1519 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1522 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1523 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1527 return $activityInfo;
1531 * Combine all the exportable fields from the lower levels object.
1534 * array of exportable Fields
1536 public static function &exportableFields() {
1537 if (!self
::$_exportableFields) {
1538 if (!self
::$_exportableFields) {
1539 self
::$_exportableFields = array();
1542 $fields = CRM_Case_DAO_Case
::export();
1543 $fields['case_role'] = array('title' => ts('Role in Case'));
1544 $fields['case_type'] = array(
1545 'title' => ts('Case Type'),
1546 'name' => 'case_type',
1548 $fields['case_status'] = array(
1549 'title' => ts('Case Status'),
1550 'name' => 'case_status',
1553 // add custom data for cases
1554 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1556 self
::$_exportableFields = $fields;
1558 return self
::$_exportableFields;
1562 * Restore the record that are associated with this case.
1564 * @param int $caseId
1565 * Id of the case to restore.
1569 public static function restoreCase($caseId) {
1570 //restore activities
1571 $activities = self
::getCaseActivityDates($caseId);
1573 foreach ($activities as $value) {
1574 CRM_Activity_BAO_Activity
::restoreActivity($value);
1578 $case = new CRM_Case_DAO_Case();
1579 $case->id
= $caseId;
1580 $case->is_deleted
= 0;
1583 //CRM-7364, enable relationships
1584 self
::enableDisableCaseRelationships($caseId, TRUE);
1591 * @param null $showLinks
1592 * @param bool $returnOnlyCount
1593 * @param int $offset
1594 * @param int $rowCount
1598 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1599 $globalContacts = array();
1601 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1602 $settings = $settingsProcessor->run();
1603 if (!empty($settings)) {
1604 $groupInfo['name'] = $settings['groupname'];
1605 if ($groupInfo['name']) {
1606 $searchParams = array('name' => $groupInfo['name']);
1608 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1610 $groupInfo['id'] = $results['id'];
1611 $groupInfo['title'] = $results['title'];
1612 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1613 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1614 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1616 if ($returnOnlyCount) {
1617 return $globalContacts;
1621 foreach ($globalContacts as $idx => $contact) {
1622 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1628 return $globalContacts;
1632 * Convenience function to get both case contacts and global in one array.
1633 * @param int $caseId
1637 public static function getRelatedAndGlobalContacts($caseId) {
1638 $relatedContacts = self
::getRelatedContacts($caseId);
1640 $groupInfo = array();
1641 $globalContacts = self
::getGlobalContacts($groupInfo);
1643 //unset values which are not required.
1644 foreach ($globalContacts as $k => & $v) {
1645 unset($v['email_id']);
1646 unset($v['group_contact_id']);
1647 unset($v['status']);
1649 $v['role'] = $groupInfo['title'];
1651 //include multiple listings for the same contact/different roles.
1652 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1653 return $relatedGlobalContacts;
1657 * Get Case ActivitiesDueDates with given criteria.
1659 * @param int $caseID
1661 * @param array $criteriaParams
1663 * @param bool $latestDate
1664 * If set newest or oldest date is selected.
1667 * case activities due dates
1670 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1672 $selectDate = " ca.activity_date_time";
1673 $where = $groupBy = ' ';
1680 if (!empty($criteriaParams['activity_type_id'])) {
1681 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1682 $where .= " AND ca.is_current_revision = 1";
1683 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1686 if (!empty($criteriaParams['newest'])) {
1687 $selectDate = " max(ca.activity_date_time) ";
1690 $selectDate = " min(ca.activity_date_time) ";
1694 $query = "SELECT ca.id, {$selectDate} as activity_date
1695 FROM civicrm_activity ca
1696 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1697 WHERE cc.id = %1 {$where} {$groupBy}";
1699 $params = array(1 => array($caseID, 'Integer'));
1700 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1702 while ($dao->fetch()) {
1703 $values[$dao->id
]['id'] = $dao->id
;
1704 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1710 * Create activities when Case or Other roles assigned/modified/deleted.
1712 * @param int $caseId
1713 * @param int $relationshipId
1715 * @param int $relContactId
1716 * Case role assignee contactId.
1717 * @param int $contactId
1719 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1720 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1724 $queryParam = array();
1725 if (is_array($relationshipId)) {
1726 $relationshipId = implode(',', $relationshipId);
1727 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1730 $relationshipClause = " civicrm_relationship.id = %1";
1731 $queryParam[1] = array($relationshipId, 'Positive');
1735 SELECT cc.display_name as clientName,
1736 cca.display_name as assigneeContactName,
1737 civicrm_relationship.case_id as caseId,
1738 civicrm_relationship_type.label_a_b as relation_a_b,
1739 civicrm_relationship_type.label_b_a as relation_b_a,
1740 civicrm_relationship.contact_id_b as rel_contact_id,
1741 civicrm_relationship.contact_id_a as assign_contact_id
1742 FROM civicrm_relationship_type, civicrm_relationship
1743 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1744 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1745 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1747 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1749 while ($dao->fetch()) {
1750 // The assignee is not the client.
1751 if ($dao->rel_contact_id
!= $contactId) {
1752 $caseRelationship = $dao->relation_a_b
;
1753 $assigneContactName = $dao->clientName
;
1754 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1757 $caseRelationship = $dao->relation_b_a
;
1758 $assigneContactName = $dao->assigneeContactName
;
1759 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1763 $session = CRM_Core_Session
::singleton();
1764 $activityParams = array(
1765 'source_contact_id' => $session->get('userID'),
1766 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1767 'activity_date_time' => date('YmdHis'),
1768 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1771 //if $relContactId is passed, role is added or modified.
1772 if (!empty($relContactId)) {
1773 $activityParams['assignee_contact_id'] = $assigneContactIds;
1774 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1777 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1780 $activityParams['activity_type_id'] = $activityTypeID;
1782 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1784 //create case_activity record.
1785 $caseParams = array(
1786 'activity_id' => $activity->id
,
1787 'case_id' => $caseId,
1790 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1795 * contact which is assigned a case role of case manager.
1797 * @param int $caseType
1799 * @param int $caseId
1803 * html hyperlink of manager contact view page
1806 public static function getCaseManagerContact($caseType, $caseId) {
1807 if (!$caseType ||
!$caseId) {
1811 $caseManagerName = '---';
1812 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1814 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1816 if (!empty($managerRoleId)) {
1817 if (substr($managerRoleId, -4) == '_a_b') {
1818 $managerRoleQuery = "
1819 SELECT civicrm_contact.id as casemanager_id,
1820 civicrm_contact.sort_name as casemanager
1821 FROM civicrm_contact
1822 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1) AND civicrm_relationship.is_active
1823 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1824 WHERE civicrm_case.id = %2 AND is_active = 1";
1826 if (substr($managerRoleId, -4) == '_b_a') {
1827 $managerRoleQuery = "
1828 SELECT civicrm_contact.id as casemanager_id,
1829 civicrm_contact.sort_name as casemanager
1830 FROM civicrm_contact
1831 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1) AND civicrm_relationship.is_active
1832 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1833 WHERE civicrm_case.id = %2 AND is_active = 1";
1836 $managerRoleParams = array(
1837 1 => array(substr($managerRoleId, 0, -4), 'Integer'),
1838 2 => array($caseId, 'Integer'),
1841 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1842 if ($dao->fetch()) {
1843 $caseManagerName = sprintf('<a href="%s">%s</a>',
1844 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $dao->casemanager_id
)),
1850 return $caseManagerName;
1854 * @param int $contactId
1855 * @param bool $excludeDeleted
1859 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1860 $params = array('check_permissions' => TRUE);
1861 if ($excludeDeleted) {
1862 $params['is_deleted'] = 0;
1865 $params['contact_id'] = $contactId;
1868 return civicrm_api3('Case', 'getcount', $params);
1870 catch (CiviCRM_API3_Exception
$e) {
1871 // Lack of permissions will throw an exception
1877 * Retrieve related case ids for given case.
1879 * @param int $caseId
1880 * @param bool $excludeDeleted
1881 * Do not include deleted cases.
1885 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1886 //FIXME : do check for permissions.
1892 $linkActType = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Link Cases');
1893 if (!$linkActType) {
1897 $whereClause = "mainCase.id = %2";
1898 if ($excludeDeleted) {
1899 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1903 SELECT relCaseAct.case_id
1904 FROM civicrm_case mainCase
1905 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1906 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1907 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1908 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1909 WHERE $whereClause";
1911 $dao = CRM_Core_DAO
::executeQuery($query, array(
1912 1 => array($linkActType, 'Integer'),
1913 2 => array($caseId, 'Integer'),
1915 $relatedCaseIds = array();
1916 while ($dao->fetch()) {
1917 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1920 return array_values($relatedCaseIds);
1924 * Retrieve related case details for given case.
1926 * @param int $caseId
1927 * @param bool $excludeDeleted
1928 * Do not include deleted cases.
1932 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1933 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1934 $relatedCases = array();
1936 if (!$relatedCaseIds) {
1940 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1941 if ($excludeDeleted) {
1942 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1945 //filter for permissioned cases.
1946 $filterCases = array();
1947 $doFilterCases = FALSE;
1948 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1949 $doFilterCases = TRUE;
1950 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
1953 //2. fetch the details of related cases.
1955 SELECT relCase.id as id,
1956 civicrm_case_type.title as case_type,
1957 client.display_name as client_name,
1958 client.id as client_id,
1960 FROM civicrm_case relCase
1961 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1962 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1963 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1964 WHERE {$whereClause}";
1966 $dao = CRM_Core_DAO
::executeQuery($query);
1967 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
1968 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1969 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
1971 while ($dao->fetch()) {
1973 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
1974 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
1975 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
1976 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
1978 $clientView = $dao->client_name
;
1979 if ($hasViewContact) {
1980 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
1983 $relatedCases[$dao->id
] = array(
1984 'case_id' => $dao->id
,
1985 'case_type' => $dao->case_type
,
1986 'client_name' => $clientView,
1987 'case_status' => $statuses[$dao->status_id
],
1988 'links' => $caseView,
1992 return $relatedCases;
1996 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
1998 * @see CRM_Dedupe_Merger::cpTables()
2000 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2002 * @param int $mainContactId
2003 * @param int $otherContactId
2005 public static function mergeContacts($mainContactId, $otherContactId) {
2006 self
::mergeCases($mainContactId, NULL, $otherContactId);
2010 * Function perform two task.
2011 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2012 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2014 * @param int $mainContactId
2015 * Contact id of main contact record.
2016 * @param int $mainCaseId
2017 * Case id of main case record.
2018 * @param int $otherContactId
2019 * Contact id of record which is going to merge.
2020 * @param int $otherCaseId
2021 * Case id of record which is going to merge.
2023 * @param bool $changeClient
2026 * @throws \CRM_Core_Exception
2028 public static function mergeCases(
2029 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2030 $otherCaseId = NULL, $changeClient = FALSE) {
2031 $moveToTrash = TRUE;
2033 $duplicateContacts = FALSE;
2034 if ($mainContactId && $otherContactId &&
2035 $mainContactId != $otherContactId
2037 $duplicateContacts = TRUE;
2040 $duplicateCases = FALSE;
2041 if ($mainCaseId && $otherCaseId &&
2042 $mainCaseId != $otherCaseId
2044 $duplicateCases = TRUE;
2047 $mainCaseIds = array();
2048 if (!$duplicateContacts && !$duplicateCases) {
2049 return $mainCaseIds;
2052 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
2053 $completedActivityStatus = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
2054 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2055 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2056 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2057 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2059 $processCaseIds = array($otherCaseId);
2060 if ($duplicateContacts && !$duplicateCases) {
2061 if ($changeClient) {
2062 $processCaseIds = array($mainCaseId);
2065 //get all case ids for other contact.
2066 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2068 if (!is_array($processCaseIds)) {
2073 $session = CRM_Core_Session
::singleton();
2074 $currentUserId = $session->get('userID');
2076 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2078 // copy all cases and connect to main contact id.
2079 foreach ($processCaseIds as $otherCaseId) {
2080 if ($duplicateContacts) {
2081 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2082 $mainCaseId = $mainCase->id
;
2087 // CRM-11662 Copy Case custom data
2088 $extends = array('case');
2089 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2091 foreach ($groupTree as $groupID => $group) {
2092 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2093 foreach ($group['fields'] as $fieldID => $field) {
2094 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2098 foreach ($table as $tableName => $tableColumns) {
2099 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2100 $tableColumns[0] = $mainCaseId;
2101 $select = 'SELECT ' . implode(', ', $tableColumns);
2102 $from = ' FROM ' . $tableName;
2103 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2104 $query = $insert . $select . $from . $where;
2105 $dao = CRM_Core_DAO
::executeQuery($query);
2109 $mainCaseIds[] = $mainCaseId;
2110 //insert record for case contact.
2111 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2112 $otherCaseContact->case_id
= $otherCaseId;
2113 $otherCaseContact->find();
2114 while ($otherCaseContact->fetch()) {
2115 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2116 $mainCaseContact->case_id
= $mainCaseId;
2117 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2118 if ($mainCaseContact->contact_id
== $otherContactId) {
2119 $mainCaseContact->contact_id
= $mainContactId;
2121 //avoid duplicate object.
2122 if (!$mainCaseContact->find(TRUE)) {
2123 $mainCaseContact->save();
2127 elseif (!$otherContactId) {
2128 $otherContactId = $mainContactId;
2131 if (!$mainCaseId ||
!$otherCaseId ||
2132 !$mainContactId ||
!$otherContactId
2137 // get all activities for other case.
2138 $otherCaseActivities = array();
2139 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2141 //for duplicate cases do not process singleton activities.
2142 $otherActivityIds = $singletonActivityIds = array();
2143 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2144 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2145 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2148 $otherActivityIds[] = $otherActId;
2150 if ($duplicateCases) {
2151 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2154 FROM civicrm_activity
2155 WHERE activity_type_id = $openCaseType
2156 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2157 $dao = CRM_Core_DAO
::executeQuery($sql);
2158 while ($dao->fetch()) {
2159 $singletonActivityIds[] = $dao->id
;
2164 // migrate all activities and connect to main contact.
2165 $copiedActivityIds = $activityMappingIds = array();
2166 sort($otherActivityIds);
2167 foreach ($otherActivityIds as $otherActivityId) {
2169 //for duplicate cases -
2170 //do not migrate singleton activities.
2171 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2175 //migrate activity record.
2176 $otherActivity = new CRM_Activity_DAO_Activity();
2177 $otherActivity->id
= $otherActivityId;
2178 if (!$otherActivity->find(TRUE)) {
2182 $mainActVals = array();
2183 $mainActivity = new CRM_Activity_DAO_Activity();
2184 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2185 $mainActivity->copyValues($mainActVals);
2186 $mainActivity->id
= NULL;
2187 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2188 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2192 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2196 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2199 $mainActivity->save();
2200 $mainActivityId = $mainActivity->id
;
2201 if (!$mainActivityId) {
2205 $activityMappingIds[$otherActivityId] = $mainActivityId;
2206 // insert log of all activities
2207 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2209 $copiedActivityIds[] = $otherActivityId;
2211 //create case activity record.
2212 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2213 $mainCaseActivity->case_id
= $mainCaseId;
2214 $mainCaseActivity->activity_id
= $mainActivityId;
2215 $mainCaseActivity->save();
2217 //migrate source activity.
2218 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2219 $otherSourceActivity->activity_id
= $otherActivityId;
2220 $otherSourceActivity->record_type_id
= $sourceID;
2221 $otherSourceActivity->find();
2222 while ($otherSourceActivity->fetch()) {
2223 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2224 $mainActivitySource->record_type_id
= $sourceID;
2225 $mainActivitySource->activity_id
= $mainActivityId;
2226 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2227 if ($mainActivitySource->contact_id
== $otherContactId) {
2228 $mainActivitySource->contact_id
= $mainContactId;
2230 //avoid duplicate object.
2231 if (!$mainActivitySource->find(TRUE)) {
2232 $mainActivitySource->save();
2236 //migrate target activities.
2237 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2238 $otherTargetActivity->activity_id
= $otherActivityId;
2239 $otherTargetActivity->record_type_id
= $targetID;
2240 $otherTargetActivity->find();
2241 while ($otherTargetActivity->fetch()) {
2242 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2243 $mainActivityTarget->record_type_id
= $targetID;
2244 $mainActivityTarget->activity_id
= $mainActivityId;
2245 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2246 if ($mainActivityTarget->contact_id
== $otherContactId) {
2247 $mainActivityTarget->contact_id
= $mainContactId;
2249 //avoid duplicate object.
2250 if (!$mainActivityTarget->find(TRUE)) {
2251 $mainActivityTarget->save();
2255 //migrate assignee activities.
2256 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2257 $otherAssigneeActivity->activity_id
= $otherActivityId;
2258 $otherAssigneeActivity->record_type_id
= $assigneeID;
2259 $otherAssigneeActivity->find();
2260 while ($otherAssigneeActivity->fetch()) {
2261 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2262 $mainAssigneeActivity->activity_id
= $mainActivityId;
2263 $mainAssigneeActivity->record_type_id
= $assigneeID;
2264 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2265 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2266 $mainAssigneeActivity->contact_id
= $mainContactId;
2268 //avoid duplicate object.
2269 if (!$mainAssigneeActivity->find(TRUE)) {
2270 $mainAssigneeActivity->save();
2274 // copy custom fields and attachments
2276 'activityID' => $otherActivityId,
2277 'mainActivityId' => $mainActivityId,
2279 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2282 //copy case relationship.
2283 if ($duplicateContacts) {
2284 //migrate relationship records.
2285 $otherRelationship = new CRM_Contact_DAO_Relationship();
2286 $otherRelationship->case_id
= $otherCaseId;
2287 $otherRelationship->find();
2288 $otherRelationshipIds = array();
2289 while ($otherRelationship->fetch()) {
2290 $otherRelVals = array();
2291 $updateOtherRel = FALSE;
2292 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2294 $mainRelationship = new CRM_Contact_DAO_Relationship();
2295 $mainRelationship->copyValues($otherRelVals);
2296 $mainRelationship->id
= NULL;
2297 $mainRelationship->case_id
= $mainCaseId;
2298 if ($mainRelationship->contact_id_a
== $otherContactId) {
2299 $updateOtherRel = TRUE;
2300 $mainRelationship->contact_id_a
= $mainContactId;
2303 //case creator change only when we merge user contact.
2304 if ($mainRelationship->contact_id_b
== $otherContactId) {
2305 //do not change creator for change client.
2306 if (!$changeClient) {
2307 $updateOtherRel = TRUE;
2308 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2311 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2312 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2314 //avoid duplicate object.
2315 if (!$mainRelationship->find(TRUE)) {
2316 $mainRelationship->save();
2319 //get the other relationship ids to update end date.
2320 if ($updateOtherRel) {
2321 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2325 //update other relationships end dates
2326 if (!empty($otherRelationshipIds)) {
2327 $sql = 'UPDATE civicrm_relationship
2328 SET end_date = CURDATE()
2329 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2330 CRM_Core_DAO
::executeQuery($sql);
2334 //move other case to trash.
2335 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2340 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2341 if ($changeClient) {
2342 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2343 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2345 $mergeActType = array_search('Reassigned Case', $activityTypes);
2346 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2349 2 => $otherContactDisplayName,
2350 3 => $mainContactDisplayName,
2355 elseif ($duplicateContacts) {
2356 $mergeActType = array_search('Merge Case', $activityTypes);
2357 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2360 2 => $otherContactId,
2361 3 => $mainContactId,
2367 $mergeActType = array_search('Merge Case', $activityTypes);
2368 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2369 if (!empty($copiedActivityIds)) {
2371 SELECT id, subject, activity_date_time, activity_type_id
2372 FROM civicrm_activity
2373 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2374 $dao = CRM_Core_DAO
::executeQuery($sql);
2375 while ($dao->fetch()) {
2376 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2377 if ($dao->subject
) {
2378 $mergeActSubjectDetails .= " :: {$dao->subject}";
2380 $mergeActSubjectDetails .= "<br />";
2385 // Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2386 $activityParams = array(
2387 'subject' => $mergeActSubject,
2388 'details' => $mergeActSubjectDetails,
2389 'status_id' => $completedActivityStatus,
2390 'activity_type_id' => $mergeActType,
2391 'source_contact_id' => $currentUserId,
2392 'activity_date_time' => date('YmdHis'),
2395 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2396 $mergeActivityId = $mergeActivity->id
;
2397 if (!$mergeActivityId) {
2401 //connect merge activity to case.
2402 $mergeCaseAct = array(
2403 'case_id' => $mainCaseId,
2404 'activity_id' => $mergeActivityId,
2407 self
::processCaseActivity($mergeCaseAct);
2410 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2412 return $mainCaseIds;
2416 * Validate contact permission for
2417 * edit/view on activity record and build links.
2419 * @param array $tplParams
2420 * Params to be sent to template for sending email.
2421 * @param array $activityParams
2422 * Info of the activity.
2424 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2425 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2426 'activity_type_id', 'id'
2429 if (!empty($tplParams['isCaseActivity'])) {
2430 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2431 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2434 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2435 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2438 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2439 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2443 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2444 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2447 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2448 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2454 * Validate contact permission for
2455 * given operation on activity record.
2457 * @param int $activityId
2458 * Activity record id.
2459 * @param string $operation
2461 * @param int $actTypeId
2463 * @param int $contactId
2464 * Contact id/if not pass consider logged in.
2465 * @param bool $checkComponent
2466 * Do we need to check component enabled.
2470 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2472 if (!$actTypeId && $activityId) {
2473 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2476 if (!$activityId ||
!$operation ||
!$actTypeId) {
2480 //do check for civicase component enabled.
2481 if ($checkComponent && !self
::enabled()) {
2485 //do check for cases.
2486 $caseActOperations = array(
2493 if (in_array($operation, $caseActOperations)) {
2495 if (!isset($caseCount)) {
2497 $caseCount = civicrm_api3('Case', 'getcount', array(
2498 'check_permissions' => TRUE,
2499 'status_id' => array('!=' => 'Closed'),
2501 'end_date' => array('IS NULL' => 1),
2504 catch (CiviCRM_API3_Exception
$e) {
2505 // Lack of permissions will throw an exception
2509 if ($operation == 'File On Case') {
2510 $allow = !empty($caseCount);
2513 $allow = ($caseCount > 1);
2517 $actionOperations = array('view', 'edit', 'delete');
2518 if (in_array($operation, $actionOperations)) {
2520 //do cache when user has non/supper permission.
2521 static $allowOperations;
2523 if (!is_array($allowOperations) ||
2524 !array_key_exists($operation, $allowOperations)
2528 $session = CRM_Core_Session
::singleton();
2529 $contactId = $session->get('userID');
2532 //check for permissions.
2533 $permissions = array(
2535 'access my cases and activities',
2536 'access all cases and activities',
2539 'access my cases and activities',
2540 'access all cases and activities',
2542 'delete' => array('delete activities'),
2545 //check for core permission.
2546 $hasPermissions = array();
2547 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2548 if (is_array($checkPermissions)) {
2549 foreach ($checkPermissions as $per) {
2550 if (CRM_Core_Permission
::check($per)) {
2551 $hasPermissions[$operation][] = $per;
2557 if (!empty($hasPermissions)) {
2558 //need to check activity object specific.
2559 if (in_array($operation, array(
2564 //do we have supper permission.
2565 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2566 $allowOperations[$operation] = $allow = TRUE;
2569 //user has only access to my cases and activity.
2570 //here object specific permmions come in picture.
2572 //edit - contact must be source or assignee
2573 //view - contact must be source/assignee/target
2574 $isTarget = $isAssignee = $isSource = FALSE;
2575 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2576 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2577 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2578 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2580 $target = new CRM_Activity_DAO_ActivityContact();
2581 $target->record_type_id
= $targetID;
2582 $target->activity_id
= $activityId;
2583 $target->contact_id
= $contactId;
2584 if ($target->find(TRUE)) {
2588 $assignee = new CRM_Activity_DAO_ActivityContact();
2589 $assignee->activity_id
= $activityId;
2590 $assignee->record_type_id
= $assigneeID;
2591 $assignee->contact_id
= $contactId;
2592 if ($assignee->find(TRUE)) {
2596 $source = new CRM_Activity_DAO_ActivityContact();
2597 $source->activity_id
= $activityId;
2598 $source->record_type_id
= $sourceID;
2599 $source->contact_id
= $contactId;
2600 if ($source->find(TRUE)) {
2604 if ($operation == 'edit') {
2605 if ($isAssignee ||
$isSource) {
2609 if ($operation == 'view') {
2610 if ($isTarget ||
$isAssignee ||
$isSource) {
2616 elseif (is_array($hasPermissions[$operation])) {
2617 $allowOperations[$operation] = $allow = TRUE;
2621 //contact do not have permission.
2622 $allowOperations[$operation] = FALSE;
2627 //here contact might have supper/non permission.
2628 $allow = $allowOperations[$operation];
2632 //do further only when operation is granted.
2634 $actTypeName = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $actTypeId);
2636 //do not allow multiple copy / edit action.
2637 $singletonNames = array(
2647 //do not allow to delete these activities, CRM-4543
2648 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2650 //allow edit operation.
2651 $allowEditNames = array('Open Case');
2653 if (CRM_Activity_BAO_Activity
::checkEditInboundEmailsPermissions()) {
2654 $allowEditNames[] = 'Inbound Email';
2657 // do not allow File on Case
2658 $doNotFileNames = array(
2661 'Change Case Status',
2662 'Change Case Start Date',
2669 if (in_array($actTypeName, $singletonNames)) {
2671 if ($operation == 'File On Case') {
2672 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2674 if (in_array($operation, $actionOperations)) {
2676 if ($operation == 'edit') {
2677 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2679 elseif ($operation == 'delete') {
2680 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2684 if ($allow && ($operation == 'delete') &&
2685 in_array($actTypeName, $doNotDeleteNames)
2690 if ($allow && ($operation == 'File On Case') &&
2691 in_array($actTypeName, $doNotFileNames)
2696 //check settings file for masking actions
2697 //on the basis the activity types
2698 //hide Edit link if activity type is NOT editable
2699 //(special case activities).CRM-5871
2700 if ($allow && in_array($operation, $actionOperations)) {
2701 static $actionFilter = array();
2702 if (!array_key_exists($operation, $actionFilter)) {
2703 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2704 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2706 if (array_key_exists($operation, $actionFilter[$operation]) &&
2707 in_array($actTypeId, $actionFilter[$operation][$operation])
2718 * Since we drop 'access CiviCase', allow access
2719 * if user has 'access my cases and activities'
2720 * or 'access all cases and activities'
2722 public static function accessCiviCase() {
2723 if (!self
::enabled()) {
2727 if (CRM_Core_Permission
::check('access my cases and activities') ||
2728 CRM_Core_Permission
::check('access all cases and activities')
2737 * Verify user has permission to access a case.
2739 * @param int $caseId
2740 * @param bool $denyClosed
2741 * Set TRUE if one wants closed cases to be treated as inaccessible.
2745 public static function accessCase($caseId, $denyClosed = TRUE) {
2746 if (!$caseId ||
!self
::enabled()) {
2750 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2751 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2752 $params['status_id'] = array('!=' => 'Closed');
2755 return (bool) civicrm_api3('Case', 'getcount', $params);
2757 catch (CiviCRM_API3_Exception
$e) {
2758 // Lack of permissions will throw an exception
2764 * Check whether activity is a case Activity.
2766 * @param int $activityID
2771 public static function isCaseActivity($activityID) {
2772 $isCaseActivity = FALSE;
2774 $params = array(1 => array($activityID, 'Integer'));
2775 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2776 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2777 $isCaseActivity = TRUE;
2781 return $isCaseActivity;
2785 * Get all the case type ids currently in use.
2789 public static function getUsedCaseType() {
2790 static $caseTypeIds;
2792 if (!is_array($caseTypeIds)) {
2793 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2795 $dao = CRM_Core_DAO
::executeQuery($query);
2796 $caseTypeIds = array();
2797 while ($dao->fetch()) {
2798 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2801 $caseTypeIds[] = $typeId[1];
2805 return $caseTypeIds;
2809 * Get all the case status ids currently in use.
2813 public static function getUsedCaseStatuses() {
2814 static $caseStatusIds;
2816 if (!is_array($caseStatusIds)) {
2817 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2819 $dao = CRM_Core_DAO
::executeQuery($query);
2820 $caseStatusIds = array();
2821 while ($dao->fetch()) {
2822 $caseStatusIds[] = $dao->status_id
;
2826 return $caseStatusIds;
2830 * Get all the encounter medium ids currently in use.
2834 public static function getUsedEncounterMediums() {
2837 if (!is_array($mediumIds)) {
2838 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2840 $dao = CRM_Core_DAO
::executeQuery($query);
2841 $mediumIds = array();
2842 while ($dao->fetch()) {
2843 $mediumIds[] = $dao->medium_id
;
2851 * Check case configuration.
2853 * @param int $contactId
2857 public static function isCaseConfigured($contactId = NULL) {
2858 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2860 //lets check for case configured.
2861 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2862 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2863 if (!$configured['configured']) {
2864 //do check for case type and case status.
2865 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2866 if (!empty($caseTypes)) {
2867 $configured['configured'] = TRUE;
2868 if (!$configured['configured']) {
2869 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2870 if (!empty($caseStatuses)) {
2871 $configured['configured'] = TRUE;
2876 if ($configured['configured']) {
2877 //do check for active case type and case status.
2878 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2879 if (!empty($caseTypes)) {
2880 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2881 if (!empty($caseStatuses)) {
2882 $configured['allowToAddNewCase'] = TRUE;
2886 //do we need to redirect user to case admin.
2887 if (!$configured['allowToAddNewCase'] && $contactId) {
2888 //check for current contact case count.
2889 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2890 //redirect user to case admin page.
2891 if (!$currentContatCasesCount) {
2892 $configured['redirectToCaseAdmin'] = TRUE;
2901 * Used during case component enablement and during ugprade.
2905 public static function createCaseViews() {
2906 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2907 $dao = new CRM_Core_DAO();
2909 $sql = self
::createCaseViewsQuery('upcoming');
2911 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2915 // Above error doesn't get caught?
2916 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2917 if (is_null($doublecheck)) {
2921 $sql = self
::createCaseViewsQuery('recent');
2923 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2927 // Above error doesn't get caught?
2928 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2929 if (is_null($doublecheck)) {
2937 * Helper function, also used by the upgrade in case of error
2939 * @param string $section
2943 public static function createCaseViewsQuery($section = 'upcoming') {
2945 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2948 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2949 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2950 FROM civicrm_case_activity ca
2951 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2953 (SELECT b.id FROM civicrm_case_activity bca
2954 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2955 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
2956 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
2957 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
2961 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
2962 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2963 FROM civicrm_case_activity ca
2964 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2966 (SELECT b.id FROM civicrm_case_activity bca
2967 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2968 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
2969 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
2970 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
2977 * Add/copy relationships, when new client is added for a case
2979 * @param int $caseId
2981 * @param int $contactId
2982 * Contact id / new client id.
2984 public static function addCaseRelationships($caseId, $contactId) {
2985 // get the case role / relationships for the case
2986 $caseRelationships = new CRM_Contact_DAO_Relationship();
2987 $caseRelationships->case_id
= $caseId;
2988 $caseRelationships->find();
2989 $relationshipTypes = array();
2991 // make sure we don't add duplicate relationships of same relationship type.
2992 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
2994 CRM_Core_DAO
::storeValues($caseRelationships, $values);
2996 // add relationship for new client.
2997 $newRelationship = new CRM_Contact_DAO_Relationship();
2998 $newRelationship->copyValues($values);
2999 $newRelationship->id
= NULL;
3000 $newRelationship->case_id
= $caseId;
3001 $newRelationship->contact_id_a
= $contactId;
3002 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3003 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3005 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3006 if (!$newRelationship->find(TRUE)) {
3007 $newRelationship->save();
3010 // store relationship type of newly created relationship
3011 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3016 * Get the list of clients for a case.
3018 * @param int $caseId
3021 * associated array with client ids
3023 public static function getCaseClients($caseId) {
3025 $caseContact = new CRM_Case_DAO_CaseContact();
3026 $caseContact->case_id
= $caseId;
3027 $caseContact->orderBy('id');
3028 $caseContact->find();
3030 while ($caseContact->fetch()) {
3031 $clients[] = $caseContact->contact_id
;
3038 * @param int $caseId
3039 * @param string $direction
3041 * @param int $relTypeId
3042 * @throws \CRM_Core_Exception
3043 * @throws \CiviCRM_API3_Exception
3045 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3047 if ($direction !== 'a' && $direction !== 'b') {
3048 throw new CRM_Core_Exception('Invalid relationship direction');
3051 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3052 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3053 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3054 1 => array($caseId, 'Positive'),
3055 2 => array($cid, 'Positive'),
3056 3 => array($relTypeId, 'Positive'),
3058 while ($dao->fetch()) {
3059 civicrm_api3('relationship', 'create', array(
3062 'end_date' => 'now',
3068 * Get options for a given case field.
3069 * @see CRM_Core_DAO::buildOptions
3071 * @param string $fieldName
3072 * @param string $context
3073 * @see CRM_Core_DAO::buildOptionsContext
3074 * @param array $props
3075 * Whatever is known about this dao object.
3077 * @return array|bool
3079 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3080 $className = __CLASS__
;
3082 switch ($fieldName) {
3083 // This field is not part of this object but the api supports it
3085 $className = 'CRM_Activity_BAO_Activity';
3088 // Filter status id by case type id
3090 if (!empty($props['case_type_id'])) {
3091 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3092 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3093 if (!empty($caseType['definition']['statuses'])) {
3094 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3099 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3105 public function addSelectWhereClause() {
3106 // We always return an array with these keys, even if they are empty,
3107 // because this tells the query builder that we have considered these fields for acls
3110 // Only case admins can view deleted cases
3111 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3113 // Ensure the user has permission to view the case client
3114 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3115 if ($contactClause) {
3116 $contactClause = implode(' AND contact_id ', $contactClause);
3117 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3119 // The api gatekeeper ensures the user has at least "access my cases and activities"
3120 // so if they do not have permission to see all cases we'll assume they can only access their own
3121 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3122 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3123 $clauses['id'][] = "IN (
3124 SELECT r.case_id FROM civicrm_relationship r, civicrm_case_contact cc WHERE r.is_active = 1 AND cc.case_id = r.case_id AND (
3125 (r.contact_id_a = cc.contact_id AND r.contact_id_b = $user) OR (r.contact_id_b = cc.contact_id AND r.contact_id_a = $user)
3129 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3134 * CRM-20308: Method to get the contact id to use as from contact for email copy
3135 * 1. Activity Added by Contact's email address
3136 * 2. System Default From Address
3137 * 3. Default Organization Contact email address
3140 * @param int $activityID
3142 * @return mixed $emailFromContactId
3143 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3145 public static function getReceiptFrom($activityID) {
3146 $name = $address = NULL;
3148 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3149 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3150 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3151 // There is always a 'Added by' contact for a activity,
3152 // so we can safely use ActivityContact.Getvalue API
3153 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3154 'activity_id' => $activityID,
3155 'record_type_id' => 'Activity Source',
3156 'return' => 'contact_id',
3158 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3161 // If 'From' email address not found for Source Activity Contact then
3162 // fetch the email from domain or logged in user.
3163 if (empty($address)) {
3164 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3167 return "$name <$address>";
3173 public static function getEntityRefFilters() {
3176 'key' => 'case_id.case_type_id',
3177 'value' => ts('Case Type'),
3181 'key' => 'case_id.status_id',
3182 'value' => ts('Case Status'),
3186 foreach (CRM_Contact_BAO_Contact
::getEntityRefFilters() as $filter) {
3187 $filter +
= ['entity' => 'Contact'];
3188 $filter['key'] = 'contact_id.' . $filter['key'];
3189 $filters[] = $filter;
3195 * Fetch Case Role direction from Case Type
3197 public static function getCaseRoleDirection($caseId, $roleTypeId = NULL) {
3199 $case = civicrm_api3('Case', 'getsingle', array('id' => $caseId));
3201 catch (CiviCRM_API3_Exception
$e) {
3202 // Lack of permissions will throw an exception
3205 if (!empty($case['case_type_id'])) {
3207 $caseType = civicrm_api3('CaseType', 'getsingle', array('id' => $case['case_type_id'], 'return' => array('definition')));
3209 catch (CiviCRM_API3_Exception
$e) {
3210 // Lack of permissions will throw an exception
3211 return 'no case type found';
3213 if (!empty($caseType['definition']['caseRoles'])) {
3214 $caseRoles = array();
3215 foreach ($caseType['definition']['caseRoles'] as $key => $roleDetails) {
3216 // Check if its an a_b label
3218 $relType = civicrm_api3('RelationshipType', 'getsingle', array('label_a_b' => $roleDetails['name']));
3220 catch (CiviCRM_API3_Exception
$e) {
3222 if (!empty($relType['id'])) {
3223 $roleDetails['id'] = $relType['id'];
3224 $roleDetails['direction'] = 'b_a';
3226 // Check if its a b_a label
3228 $relTypeBa = civicrm_api3('RelationshipType', 'getsingle', array('label_b_a' => $roleDetails['name']));
3230 catch (CiviCRM_API3_Exception
$e) {
3232 if (!empty($relTypeBa['id'])) {
3233 if (!empty($roleDetails['direction'])) {
3234 $roleDetails['direction'] = 'bidrectional';
3237 $roleDetails['id'] = $relTypeBa['id'];
3238 $roleDetails['direction'] = 'a_b';
3241 $caseRoles[$roleDetails['id']] = $roleDetails;