3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class contains the functions for Case Management.
21 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
24 * Static field for all the case information that we can potentially export.
28 public static $_exportableFields = NULL;
33 public function __construct() {
34 parent
::__construct();
38 * Is CiviCase enabled?
42 public static function enabled() {
43 $config = CRM_Core_Config
::singleton();
44 return in_array('CiviCase', $config->enableComponents
);
48 * Create a case object.
50 * The function extracts all the params it needs to initialize the create a
51 * case object. the params array could contain additional unused name/value
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
57 * @return CRM_Case_BAO_Case
59 public static function add(&$params) {
60 $caseDAO = new CRM_Case_DAO_Case();
61 $caseDAO->copyValues($params);
62 $result = $caseDAO->save();
63 // Get other case values (required by XML processor), this adds to $result array
69 * Takes an associative array and creates a case object.
71 * @param array $params
72 * (reference) an assoc array of name/value pairs.
74 * @return CRM_Case_BAO_Case
76 public static function &create(&$params) {
77 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
78 unset($params['created_date']);
79 unset($params['modified_date']);
80 $caseStatus = CRM_Case_PseudoConstant
::caseStatus('name');
81 // for resolved case the end date should set to now
82 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
83 $params['end_date'] = date("Ymd");
86 $transaction = new CRM_Core_Transaction();
88 if (!empty($params['id'])) {
89 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
92 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
95 $case = self
::add($params);
97 if (!empty($params['custom']) &&
98 is_array($params['custom'])
100 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
103 if (is_a($case, 'CRM_Core_Error')) {
104 $transaction->rollback();
108 if (!empty($params['id'])) {
109 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
112 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
114 $transaction->commit();
116 //we are not creating log for case
117 //since case log can be tracked using log for activity.
122 * Process case activity add/delete
123 * takes an associative array and
125 * @param array $params
126 * (reference ) an assoc array of name/value pairs.
129 public static function processCaseActivity(&$params) {
130 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
131 $caseActivityDAO->activity_id
= $params['activity_id'];
132 $caseActivityDAO->case_id
= $params['case_id'];
134 $caseActivityDAO->find(TRUE);
135 $caseActivityDAO->save();
139 * Get the case subject for Activity.
141 * @param int $activityId
144 * @return string|null
146 public static function getCaseSubject($activityId) {
147 $caseActivity = new CRM_Case_DAO_CaseActivity();
148 $caseActivity->activity_id
= $activityId;
149 if ($caseActivity->find(TRUE)) {
150 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
159 * @param string $colName
164 public static function getCaseType($caseId, $colName = 'title') {
166 SELECT civicrm_case_type.{$colName} FROM civicrm_case
167 LEFT JOIN civicrm_case_type ON
168 civicrm_case.case_type_id = civicrm_case_type.id
169 WHERE civicrm_case.id = %1";
171 $queryParams = [1 => [$caseId, 'Integer']];
173 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
177 * Delete the record that are associated with this case.
178 * record are deleted from case
181 * Id of the case to delete.
183 * @param bool $moveToTrash
188 public static function deleteCase($caseId, $moveToTrash = FALSE) {
189 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
192 $activities = self
::getCaseActivityDates($caseId);
194 foreach ($activities as $value) {
195 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
200 $transaction = new CRM_Core_Transaction();
202 $case = new CRM_Case_DAO_Case();
205 $result = $case->delete();
206 $transaction->commit();
209 $result = $case->is_deleted
= 1;
214 // CRM-7364, disable relationships
215 self
::enableDisableCaseRelationships($caseId, FALSE);
217 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
219 // remove case from recent items.
224 CRM_Utils_Recent
::del($caseRecent);
232 * Enable disable case related relationships.
236 * @param bool $enable
239 public static function enableDisableCaseRelationships($caseId, $enable) {
240 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
241 if (!empty($contactIds)) {
242 foreach ($contactIds as $cid) {
243 $roles = self
::getCaseRoles($cid, $caseId);
244 if (!empty($roles)) {
245 $relationshipIds = implode(',', array_keys($roles));
246 $enable = (int) $enable;
247 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
248 WHERE id IN ( {$relationshipIds} )";
249 CRM_Core_DAO
::executeQuery($query);
256 * Retrieve contact_id by case_id.
261 * @param int $contactID
262 * @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
266 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
267 $caseContact = new CRM_Case_DAO_CaseContact();
268 $caseContact->case_id
= $caseId;
269 $caseContact->find();
271 $count = $startArrayAt;
272 while ($caseContact->fetch()) {
273 if ($contactID != $caseContact->contact_id
) {
274 $contactArray[$count] = $caseContact->contact_id
;
279 return $contactArray;
283 * Look up a case using an activity ID.
285 * @param int $activityId
287 * @return int, case ID
289 public static function getCaseIdByActivityId($activityId) {
290 $originalId = CRM_Core_DAO
::singleValueQuery(
291 'SELECT original_id FROM civicrm_activity WHERE id = %1',
292 ['1' => [$activityId, 'Integer']]
294 $caseId = CRM_Core_DAO
::singleValueQuery(
295 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
297 '1' => [$activityId, 'Integer'],
298 '2' => [$originalId ?
$originalId : $activityId, 'Integer'],
305 * Retrieve contact names by caseId.
312 public static function getContactNames($caseId) {
315 return $contactNames;
319 SELECT contact_a.sort_name name,
320 contact_a.display_name as display_name,
322 contact_a.birth_date as birth_date,
325 FROM civicrm_contact contact_a
326 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
327 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
328 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
329 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
330 ORDER BY civicrm_case_contact.id";
332 $dao = CRM_Core_DAO
::executeQuery($query,
333 [1 => [$caseId, 'Integer']]
335 while ($dao->fetch()) {
336 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
337 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
338 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
339 $contactNames[$dao->cid
]['email'] = $dao->email
;
340 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
341 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
342 $contactNames[$dao->cid
]['role'] = ts('Client');
345 return $contactNames;
349 * Retrieve case_id by contact_id.
351 * @param int $contactID
352 * @param bool $includeDeleted
353 * Include the deleted cases in result.
354 * @param null $caseType
358 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
361 FROM civicrm_case_contact cc
362 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
364 if (isset($caseType)) {
366 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
367 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
369 if (!isset($caseType)) {
370 $query .= "WHERE cc.contact_id = %1";
372 if (!$includeDeleted) {
373 $query .= " AND ca.is_deleted = 0";
376 $params = [1 => [$contactID, 'Integer']];
377 $dao = CRM_Core_DAO
::executeQuery($query, $params);
380 while ($dao->fetch()) {
381 $caseArray[] = $dao->id
;
388 * @param string $type
390 * @param string $condition
394 public static function getCaseActivityCountQuery($type = 'upcoming', $userID, $condition = NULL) {
395 return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self
::getCaseActivityQuery($type, $userID, $condition));
399 * @param string $type
401 * @param string $condition
402 * @param string $limit
403 * @param string $order
407 public static function getCaseActivityQuery($type = 'upcoming', $userID, $condition = NULL, $limit = NULL, $order = NULL) {
409 'civicrm_case.id as case_id',
410 'civicrm_case.subject as case_subject',
411 'civicrm_contact.id as contact_id',
412 'civicrm_contact.sort_name as sort_name',
413 'civicrm_phone.phone as phone',
414 'civicrm_contact.contact_type as contact_type',
415 'civicrm_contact.contact_sub_type as contact_sub_type',
416 't_act.activity_type_id as activity_type_id',
417 'civicrm_case.case_type_id as case_type_id',
418 'civicrm_case.status_id as case_status_id',
419 't_act.status_id as status_id',
420 'civicrm_case.start_date as case_start_date',
421 "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",
422 't_act.activity_date_time as activity_date_time',
423 't_act.id as activity_id',
426 $query = CRM_Contact_BAO_Query
::appendAnyValueToSelect($selectClauses, 'case_id');
430 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
431 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id
437 // civicrm_view_case_activity_upcoming and
438 // civicrm_view_case_activity_recent are views that show the next
439 // scheduled and most recent not-scheduled activity on each case,
442 INNER JOIN civicrm_view_case_activity_$type t_act
443 ON t_act.case_id = civicrm_case.id
449 LEFT JOIN civicrm_case_activity ca4
450 ON civicrm_case.id = ca4.case_id
451 LEFT JOIN civicrm_activity t_act
452 ON t_act.id = ca4.activity_id
453 AND t_act.is_current_revision = 1
458 LEFT JOIN civicrm_phone
459 ON civicrm_phone.contact_id = civicrm_contact.id
460 AND civicrm_phone.is_primary = 1
461 LEFT JOIN civicrm_relationship case_relationship
462 ON ((case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID})
463 OR (case_relationship.contact_id_b = civicrm_case_contact.contact_id AND case_relationship.contact_id_a = {$userID}))
464 AND case_relationship.is_active
465 AND case_relationship.case_id = civicrm_case.id
466 LEFT JOIN civicrm_relationship_type case_relation_type
467 ON case_relation_type.id = case_relationship.relationship_type_id
468 AND case_relation_type.id = case_relationship.relationship_type_id
472 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
473 $query .= " WHERE (1) AND $condition ";
475 $query .= " GROUP BY case_id ";
477 $query .= ($order) ?
: ' ORDER BY activity_date_time ASC';
487 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
489 * @param bool $allCases
490 * @param array $params
491 * @param string $context
492 * @param bool $getCount
497 public static function getCases($allCases = TRUE, $params = [], $context = 'dashboard', $getCount = FALSE) {
501 // validate access for own cases.
502 if (!self
::accessCiviCase()) {
503 return $getCount ?
0 : $casesList;
506 // Return cached value instead of re-running query
507 if (isset(Civi
::$statics[__CLASS__
]['totalCount']) && $getCount) {
508 return Civi
::$statics[__CLASS__
]['totalCount'];
511 $type = CRM_Utils_Array
::value('type', $params, 'upcoming');
512 $userID = CRM_Core_Session
::singleton()->get('userID');
514 // validate access for all cases.
515 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
519 $whereClauses = ['civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1'];
522 $whereClauses[] = "(case_relationship.contact_id_b = {$userID} OR case_relationship.contact_id_a = {$userID})";
523 $whereClauses[] = 'case_relationship.is_active';
525 if (empty($params['status_id']) && ($type == 'upcoming' ||
$type == 'any')) {
526 $whereClauses[] = "civicrm_case.status_id != " . CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
529 foreach (['case_type_id', 'status_id'] as $column) {
530 if (!empty($params[$column])) {
531 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
534 $condition = implode(' AND ', $whereClauses);
536 Civi
::$statics[__CLASS__
]['totalCount'] = $totalCount = CRM_Core_DAO
::singleValueQuery(self
::getCaseActivityCountQuery($type, $userID, $condition));
540 $casesList['total'] = $totalCount;
543 if (!empty($params['rp'])) {
544 $params['offset'] = ($params['page'] - 1) * $params['rp'];
545 $params['rowCount'] = $params['rp'];
546 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
547 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
552 if (!empty($params['sortBy'])) {
553 if (strstr($params['sortBy'], 'date ')) {
554 $params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
556 $order = "ORDER BY " . $params['sortBy'];
559 $query = self
::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
560 $result = CRM_Core_DAO
::executeQuery($query);
562 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
563 $actions = CRM_Case_Selector_Search
::links();
565 // check is the user has view/edit signer permission
566 $permissions = [CRM_Core_Permission
::VIEW
];
567 if (CRM_Core_Permission
::check('access all cases and activities') ||
568 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
570 $permissions[] = CRM_Core_Permission
::EDIT
;
572 if (CRM_Core_Permission
::check('delete in CiviCase')) {
573 $permissions[] = CRM_Core_Permission
::DELETE
;
575 $mask = CRM_Core_Action
::mask($permissions);
577 // Pseudoconstants to populate labels
578 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
579 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
580 $caseTypeTitles = CRM_Case_PseudoConstant
::caseType('title', FALSE);
581 $activityTypeLabels = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
583 foreach ($result->fetchAll() as $case) {
584 $key = $case['case_id'];
585 $casesList[$key] = [];
586 $casesList[$key]['DT_RowId'] = $case['case_id'];
587 $casesList[$key]['DT_RowAttr'] = ['data-entity' => 'case', 'data-id' => $case['case_id']];
588 $casesList[$key]['DT_RowClass'] = "crm-entity";
590 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
592 CRM_Utils_System
::url('civicrm/case/details', ['caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type])
595 $phone = empty($case['phone']) ?
'' : '<br /><span class="description">' . $case['phone'] . '</span>';
596 $casesList[$key]['contact_id'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
597 CRM_Utils_System
::url('civicrm/contact/view', ['cid' => $case['contact_id']]),
603 $casesList[$key]['subject'] = $case['case_subject'];
604 $casesList[$key]['case_status'] = CRM_Utils_Array
::value($case['case_status_id'], $caseStatuses);
605 if ($case['case_status_id'] == CRM_Case_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
606 $casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
608 $casesList[$key]['case_type'] = CRM_Utils_Array
::value($case['case_type_id'], $caseTypeTitles);
609 $casesList[$key]['case_role'] = CRM_Utils_Array
::value('case_role', $case, '---');
610 $casesList[$key]['manager'] = self
::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
612 $casesList[$key]['date'] = CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels);
613 if ($actId = CRM_Utils_Array
::value('activity_id', $case)) {
614 if (self
::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
615 if ($type == 'recent') {
616 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
617 CRM_Utils_System
::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
619 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
623 $status = CRM_Utils_Date
::overdue($case['activity_date_time']) ?
'status-overdue' : 'status-scheduled';
624 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
626 CRM_Utils_System
::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
628 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
632 if (isset($case['activity_type_id']) && self
::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
633 $casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil"></i></a>',
634 CRM_Utils_System
::url('civicrm/case/activity', ['reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId]),
639 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date
::customFormat($case['activity_date_time']);
640 $casesList[$key]['links'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
642 'id' => $case['case_id'],
643 'cid' => $case['contact_id'],
648 'case.actions.primary',
658 * Get the summary of cases counts by type and status.
660 * @param bool $allCases
664 public static function getCasesSummary($allCases = TRUE) {
667 //validate access for civicase.
668 if (!self
::accessCiviCase()) {
672 $userID = CRM_Core_Session
::singleton()->get('userID');
674 //validate access for all cases.
675 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
679 $caseTypes = CRM_Case_PseudoConstant
::caseType();
680 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
681 $caseTypes = array_flip($caseTypes);
683 // get statuses as headers for the table
684 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
685 foreach ($caseStatuses as $key => $name) {
686 $caseSummary['headers'][$key]['status'] = $name;
687 $caseSummary['headers'][$key]['url'] = $url . $key;
690 // build rows with actual data
692 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClauseA = $myCaseWhereClauseB = '';
698 $myGroupByClauseB = ' GROUP BY civicrm_case.id';
703 $myCaseWhereClauseA = " AND case_relationship.contact_id_a = {$userID} AND case_relationship.is_active ";
704 $myGroupByClauseA = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_a)";
705 $myCaseWhereClauseB = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
706 $myGroupByClauseB = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_b)";
708 $myGroupByClauseB .= ", case_status.label, status_id, case_type_id, civicrm_case.id";
709 $myGroupByClauseA = $myGroupByClauseB;
710 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
712 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
713 case_type_id, case_relationship.contact_id_b as case_contact
715 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
716 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
717 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
718 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
719 AND option_group_case_status.id = case_status.option_group_id )
720 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
721 AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
722 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
723 {$myCaseWhereClauseB} {$myGroupByClauseB}
725 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
726 case_type_id, case_relationship.contact_id_a as case_contact
728 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
729 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
730 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
731 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
732 AND option_group_case_status.id = case_status.option_group_id )
733 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
734 AND case_relationship.contact_id_a = {$userID})
735 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
736 {$myCaseWhereClauseA} {$myGroupByClauseA}";
738 $res = CRM_Core_DAO
::executeQuery($query);
739 while ($res->fetch()) {
740 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
741 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
744 $rows[$res->case_type
][$res->case_status
] = [
746 'url' => CRM_Utils_System
::url('civicrm/case/search',
747 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
752 $caseSummary['rows'] = array_merge($caseTypes, $rows);
760 * @param int $contactID
764 * @param int $relationshipID
765 * @param bool $activeOnly
768 * case role / relationships
771 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
773 SELECT rel.id as civicrm_relationship_id,
774 con.sort_name as sort_name,
775 civicrm_email.email as email,
776 civicrm_phone.phone as phone,
777 con.id as civicrm_contact_id,
778 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
779 civicrm_relationship_type.id as relation_type,
780 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
781 FROM civicrm_relationship rel
782 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
783 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))
784 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
785 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
786 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
787 AND con.is_deleted = 0';
790 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
794 1 => [$contactID, 'Positive'],
795 2 => [$caseID, 'Positive'],
798 if ($relationshipID) {
799 $query .= ' AND rel.id = %3 ';
800 $params[3] = [$relationshipID, 'Integer'];
802 $dao = CRM_Core_DAO
::executeQuery($query, $params);
805 while ($dao->fetch()) {
806 $rid = $dao->civicrm_relationship_id
;
807 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
808 $values[$rid]['relation'] = $dao->relation
;
809 $values[$rid]['name'] = $dao->sort_name
;
810 $values[$rid]['email'] = $dao->email
;
811 $values[$rid]['phone'] = $dao->phone
;
812 $values[$rid]['relation_type'] = $dao->relation_type
;
813 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
814 $values[$rid]['client_id'] = $contactID;
815 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
822 * Get Case Activities.
826 * @param array $params
828 * @param int $contactID
831 * @param null $context
833 * @param null $type (deprecated)
836 * Array of case activities
839 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
840 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
841 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
842 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
843 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
845 // CRM-5081 - formatting the dates to omit seconds.
846 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
848 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
850 ca.activity_type_id AS type,
851 ca.activity_type_id AS activity_type_id,
852 tcc.sort_name AS target_contact_name,
853 tcc.id AS target_contact_id,
854 scc.sort_name AS source_contact_name,
855 scc.id AS source_contact_id,
856 acc.sort_name AS assignee_contact_name,
857 acc.id AS assignee_contact_id,
859 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
860 ca.activity_date_time,
861 DATE_ADD(NOW(), INTERVAL 1 YEAR)
862 ), '%Y%m%d%H%i00') AS overdue_date,
863 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
864 ca.status_id AS status,
865 ca.subject AS subject,
866 ca.is_deleted AS deleted,
867 ca.priority_id AS priority,
869 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
872 FROM civicrm_case_activity cca
873 INNER JOIN civicrm_activity ca
874 ON ca.id = cca.activity_id
875 INNER JOIN civicrm_activity_contact cas
876 ON cas.activity_id = ca.id
877 AND cas.record_type_id = {$sourceID}
878 INNER JOIN civicrm_contact scc
879 ON scc.id = cas.contact_id
880 LEFT JOIN civicrm_activity_contact caa
881 ON caa.activity_id = ca.id
882 AND caa.record_type_id = {$assigneeID}
883 LEFT JOIN civicrm_contact acc
884 ON acc.id = caa.contact_id
885 LEFT JOIN civicrm_activity_contact cat
886 ON cat.activity_id = ca.id
887 AND cat.record_type_id = {$targetID}
888 LEFT JOIN civicrm_contact tcc
889 ON tcc.id = cat.contact_id
890 INNER JOIN civicrm_option_group cog
891 ON cog.name = 'activity_type'
892 INNER JOIN civicrm_option_value cov
893 ON cov.option_group_id = cog.id
894 AND cov.value = ca.activity_type_id
895 AND cov.is_active = 1
896 LEFT JOIN civicrm_entity_file ef
897 ON ef.entity_table = 'civicrm_activity'
898 AND ef.entity_id = ca.id
899 LEFT OUTER JOIN civicrm_option_group og
900 ON og.name = 'activity_status'
901 LEFT OUTER JOIN civicrm_option_value ov
902 ON ov.option_group_id=og.id
903 AND ov.name = 'Scheduled'";
906 WHERE cca.case_id= %1
907 AND ca.is_current_revision = 1';
909 if (!empty($params['source_contact_id'])) {
911 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
914 if (!empty($params['status_id'])) {
916 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
919 if (!empty($params['activity_deleted'])) {
921 AND ca.is_deleted = 1";
925 AND ca.is_deleted = 0";
928 if (!empty($params['activity_type_id'])) {
930 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
933 if (!empty($params['activity_date_low'])) {
934 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
936 if (!empty($fromActivityDate)) {
938 AND ca.activity_date_time >= '{$fromActivityDate}'";
941 if (!empty($params['activity_date_high'])) {
942 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
943 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
945 if (!empty($toActivityDate)) {
947 AND ca.activity_date_time <= '{$toActivityDate}'";
951 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
953 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
955 // CRM-5081 - added id to act like creation date
957 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
960 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
961 $orderBy = " ORDER BY $sortBy ";
964 $page = CRM_Utils_Array
::value('page', $params);
965 $rp = CRM_Utils_Array
::value('rp', $params);
973 $start = (($page - 1) * $rp);
974 $limit = " LIMIT $start, $rp";
976 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
977 $queryParams = [1 => [$caseID, 'Integer']];
979 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
980 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
982 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
984 $compStatusValues = array_keys(
985 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
986 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
990 $userID = CRM_Core_Session
::getLoggedInContactID();
993 $caseActivities = [];
995 while ($dao->fetch()) {
996 $caseActivityId = $dao->id
;
998 //Do we have permission to access given case activity record.
999 if (!self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID)) {
1003 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1004 //Add classes to the row, via DataTables syntax
1005 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1007 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1008 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1011 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1012 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1015 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1019 if (!empty($dao->priority
)) {
1020 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1021 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1023 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1024 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1028 //Add data to the row for inline editing, via DataTable syntax
1029 $caseActivities[$caseActivityId]['DT_RowAttr'] = [];
1030 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1031 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1033 //Activity Date and Time
1034 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1037 $caseActivities[$caseActivityId]['subject'] = $dao->subject
;
1040 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1041 . $activityTypes[$dao->type
]['label'];
1043 // Activity Target (With Contact) (There can be more than one)
1044 $targetContact = self
::formatContactLink($dao->target_contact_id
, $dao->target_contact_name
);
1045 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1046 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1049 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1050 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1054 // Activity Source Contact (Reporter) (There can only be one)
1055 $sourceContact = self
::formatContactLink($dao->source_contact_id
, $dao->source_contact_name
);
1056 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1058 // Activity Assignee (There can be more than one)
1059 $assigneeContact = self
::formatContactLink($dao->assignee_contact_id
, $dao->assignee_contact_name
);
1060 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1061 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1064 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1065 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1069 // Activity Status Label for Case activities list
1071 if ($dao->deleted
) {
1072 $deleted = '<br /> ' . ts('(deleted)');
1074 $caseActivities[$caseActivityId]['status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status
) . $deleted;
1075 // if there are file attachments we will return how many
1076 if (!empty($dao->attachment_ids
)) {
1077 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1078 $caseActivity['no_attachments'] = count($attachmentIDs);
1081 $caseActivities[$caseActivityId]['links']
1082 = CRM_Case_Selector_Search
::addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao);
1085 $caseActivitiesDT = [];
1086 $caseActivitiesDT['data'] = array_values($caseActivities);
1087 $caseActivitiesDT['recordsTotal'] = $caseCount;
1088 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1090 return $caseActivitiesDT;
1094 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1097 * @param $contactName
1101 private static function formatContactLink($contactId, $contactName) {
1102 if (empty($contactId)) {
1106 $hasViewContact = CRM_Contact_BAO_Contact_Permission
::allow($contactId);
1108 if ($hasViewContact) {
1109 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1110 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1113 return $contactName;
1118 * Get Case Related Contacts.
1120 * @param int $caseID
1122 * @param bool $includeDetails
1123 * If true include details of contacts.
1126 * array of return properties
1129 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1131 if ($includeDetails) {
1132 $caseInfo = civicrm_api3('Case', 'getsingle', [
1134 // 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
1135 'return' => ['case_type_id', 'case_type_id.name', 'case_type_id.definition', 'contact_id'],
1137 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1138 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1144 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, crt.name_a_b as role_name_reverse, ce.email, cp.phone
1145 FROM civicrm_relationship cr
1146 JOIN civicrm_relationship_type crt
1147 ON crt.id = cr.relationship_type_id
1148 JOIN civicrm_contact cc
1149 ON cc.id = cr.contact_id_a
1150 AND cc.is_deleted <> 1
1151 LEFT JOIN civicrm_email ce
1152 ON ce.contact_id = cc.id
1153 AND ce.is_primary= 1
1154 LEFT JOIN civicrm_phone cp
1155 ON cp.contact_id = cc.id
1156 AND cp.is_primary= 1
1157 WHERE cr.case_id = %1
1159 AND cc.id NOT IN (%2)
1161 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, crt.name_b_a as role_name_reverse, ce.email, cp.phone
1162 FROM civicrm_relationship cr
1163 JOIN civicrm_relationship_type crt
1164 ON crt.id = cr.relationship_type_id
1165 JOIN civicrm_contact cc
1166 ON cc.id = cr.contact_id_b
1167 AND cc.is_deleted <> 1
1168 LEFT JOIN civicrm_email ce
1169 ON ce.contact_id = cc.id
1170 AND ce.is_primary= 1
1171 LEFT JOIN civicrm_phone cp
1172 ON cp.contact_id = cc.id
1173 AND cp.is_primary= 1
1174 WHERE cr.case_id = %1
1176 AND cc.id NOT IN (%2)
1179 1 => [$caseID, 'Integer'],
1180 2 => [implode(',', $caseInfo['client_id']), 'String'],
1182 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1184 while ($dao->fetch()) {
1185 if (!$includeDetails) {
1186 $values[$dao->id
] = 1;
1190 'contact_id' => $dao->id
,
1191 'display_name' => $dao->name
,
1192 'sort_name' => $dao->sort_name
,
1193 'relationship_type_id' => $dao->relationship_type_id
,
1194 'role' => $dao->role
,
1195 'email' => $dao->email
,
1196 'phone' => $dao->phone
,
1198 // Add more info about the role (creator, manager)
1199 // The XML historically has the reverse direction, so look up reverse.
1200 $role = CRM_Utils_Array
::value($dao->role_name_reverse
, $caseRoles);
1202 unset($role['name']);
1205 $values[] = $details;
1213 * Send e-mail copy of activity
1215 * @param int $clientId
1216 * @param int $activityId
1218 * @param array $contacts
1219 * Array of related contact.
1221 * @param null $attachments
1222 * @param int $caseId
1224 * @return bool |array
1226 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1231 $tplParams = $activityInfo = [];
1232 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1233 // If it's a case activity
1235 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1236 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1237 $anyActivity = TRUE;
1240 $anyActivity = FALSE;
1242 $tplParams['isCaseActivity'] = 1;
1243 $tplParams['client_id'] = $clientId;
1246 $anyActivity = TRUE;
1249 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1250 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1252 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1254 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1256 $activityInfo['fields'][] = ['label' => 'Case ID', 'type' => 'String', 'value' => $caseId];
1258 $tplParams['activityTypeName'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeId);
1259 $tplParams['activity'] = $activityInfo;
1260 foreach ($tplParams['activity']['fields'] as $k => $val) {
1261 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1262 $activitySubject = $val['value'];
1266 $session = CRM_Core_Session
::singleton();
1267 // CRM-8926 If user is not logged in, use the activity creator as userID
1268 if (!($userID = $session->get('userID'))) {
1269 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1272 //also create activities simultaneously of this copy.
1273 $activityParams = [];
1275 $activityParams['source_record_id'] = $activityId;
1276 $activityParams['source_contact_id'] = $userID;
1277 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1278 $activityParams['activity_date_time'] = date('YmdHis');
1279 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1280 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1281 $activityParams['case_id'] = $caseId;
1282 $activityParams['is_auto'] = 0;
1283 $activityParams['target_id'] = $clientId;
1285 $tplParams['activitySubject'] = $activitySubject;
1287 // if it’s a case activity, add hashed id to the template (CRM-5916)
1289 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1293 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1294 $receiptFrom = self
::getReceiptFrom($activityId);
1296 $recordedActivityParams = [];
1298 foreach ($contacts as $mail => $info) {
1299 $tplParams['contact'] = $info;
1300 self
::buildPermissionLinks($tplParams, $activityParams);
1302 $displayName = CRM_Utils_Array
::value('display_name', $info);
1304 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1306 'groupName' => 'msg_tpl_workflow_case',
1307 'valueName' => 'case_activity',
1308 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1309 'tplParams' => $tplParams,
1310 'from' => $receiptFrom,
1311 'toName' => $displayName,
1313 'attachments' => $attachments,
1317 $activityParams['subject'] = ts('%1 - copy sent to %2', [1 => $activitySubject, 2 => $displayName]);
1318 $activityParams['details'] = $message;
1320 if (!empty($result[$info['contact_id']])) {
1322 * Really only need to record one activity with all the targets combined.
1323 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1324 * but it's always the same content at the moment.
1326 if (empty($recordedActivityParams)) {
1327 $recordedActivityParams = $activityParams;
1330 $recordedActivityParams['subject'] .= "; $displayName";
1332 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1335 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1339 if (!empty($recordedActivityParams)) {
1340 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1342 //create case_activity record if its case activity.
1345 'activity_id' => $activity->id
,
1346 'case_id' => $caseId,
1348 self
::processCaseActivity($caseParams);
1356 * Retrieve count of activities having a particular type, and
1357 * associated with a particular case.
1359 * @param int $caseId
1361 * @param int $activityTypeId
1362 * ID of the activity type.
1366 public static function getCaseActivityCount($caseId, $activityTypeId) {
1368 1 => [$caseId, 'Integer'],
1369 2 => [$activityTypeId, 'Integer'],
1371 $query = "SELECT count(ca.id) as countact
1372 FROM civicrm_activity ca
1373 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1374 WHERE ca.activity_type_id = %2
1375 AND cca.case_id = %1
1376 AND ca.is_deleted = 0";
1378 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1379 if ($dao->fetch()) {
1380 return $dao->countact
;
1387 * Retrieve the scheduled activity type and date.
1389 * @param array $cases
1390 * Array of contact and case id.
1392 * @param string $type
1395 * Array of scheduled activity type and date
1399 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1400 $session = CRM_Core_Session
::singleton();
1401 $userID = $session->get('userID');
1403 $caseID = implode(',', $cases['case_id']);
1404 $contactID = implode(',', $cases['contact_id']);
1406 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1407 AND civicrm_case.id IN( {$caseID})
1408 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1410 $query = self
::getCaseActivityQuery($type, $userID, $condition);
1411 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
1413 $res = CRM_Core_DAO
::executeQuery($query);
1416 while ($res->fetch()) {
1417 if ($type == 'upcoming') {
1418 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1419 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1422 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1423 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1427 return $activityInfo;
1431 * Combine all the exportable fields from the lower levels object.
1434 * array of exportable Fields
1436 public static function &exportableFields() {
1437 if (!self
::$_exportableFields) {
1438 if (!self
::$_exportableFields) {
1439 self
::$_exportableFields = [];
1442 $fields = CRM_Case_DAO_Case
::export();
1443 $fields['case_role'] = ['title' => ts('Role in Case')];
1444 $fields['case_type'] = [
1445 'title' => ts('Case Type'),
1446 'name' => 'case_type',
1448 $fields['case_status'] = [
1449 'title' => ts('Case Status'),
1450 'name' => 'case_status',
1453 // add custom data for cases
1454 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1456 self
::$_exportableFields = $fields;
1458 return self
::$_exportableFields;
1462 * Restore the record that are associated with this case.
1464 * @param int $caseId
1465 * Id of the case to restore.
1469 public static function restoreCase($caseId) {
1470 //restore activities
1471 $activities = self
::getCaseActivityDates($caseId);
1473 foreach ($activities as $value) {
1474 CRM_Activity_BAO_Activity
::restoreActivity($value);
1478 $case = new CRM_Case_DAO_Case();
1479 $case->id
= $caseId;
1480 $case->is_deleted
= 0;
1483 //CRM-7364, enable relationships
1484 self
::enableDisableCaseRelationships($caseId, TRUE);
1491 * @param null $showLinks
1492 * @param bool $returnOnlyCount
1493 * @param int $offset
1494 * @param int $rowCount
1498 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1499 $globalContacts = [];
1501 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1502 $settings = $settingsProcessor->run();
1503 if (!empty($settings)) {
1504 $groupInfo['name'] = $settings['groupname'];
1505 if ($groupInfo['name']) {
1506 $searchParams = ['name' => $groupInfo['name']];
1508 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1510 $groupInfo['id'] = $results['id'];
1511 $groupInfo['title'] = $results['title'];
1512 $params = [['group', '=', $groupInfo['id'], 0, 0]];
1513 $return = ['contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1];
1514 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount, FALSE);
1516 if ($returnOnlyCount) {
1517 return $globalContacts;
1521 foreach ($globalContacts as $idx => $contact) {
1522 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1528 return $globalContacts;
1532 * Convenience function to get both case contacts and global in one array.
1534 * @param int $caseId
1538 public static function getRelatedAndGlobalContacts($caseId) {
1539 $relatedContacts = self
::getRelatedContacts($caseId);
1542 $globalContacts = self
::getGlobalContacts($groupInfo);
1544 //unset values which are not required.
1545 foreach ($globalContacts as $k => & $v) {
1546 unset($v['email_id']);
1547 unset($v['group_contact_id']);
1548 unset($v['status']);
1550 $v['role'] = $groupInfo['title'];
1552 //include multiple listings for the same contact/different roles.
1553 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1554 return $relatedGlobalContacts;
1558 * Get Case ActivitiesDueDates with given criteria.
1560 * @param int $caseID
1562 * @param array $criteriaParams
1564 * @param bool $latestDate
1565 * If set newest or oldest date is selected.
1568 * case activities due dates
1571 public static function getCaseActivityDates($caseID, $criteriaParams = [], $latestDate = FALSE) {
1573 $selectDate = " ca.activity_date_time";
1574 $where = $groupBy = ' ';
1581 if (!empty($criteriaParams['activity_type_id'])) {
1582 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1583 $where .= " AND ca.is_current_revision = 1";
1584 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1587 if (!empty($criteriaParams['newest'])) {
1588 $selectDate = " max(ca.activity_date_time) ";
1591 $selectDate = " min(ca.activity_date_time) ";
1595 $query = "SELECT ca.id, {$selectDate} as activity_date
1596 FROM civicrm_activity ca
1597 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1598 WHERE cc.id = %1 {$where} {$groupBy}";
1600 $params = [1 => [$caseID, 'Integer']];
1601 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1603 while ($dao->fetch()) {
1604 $values[$dao->id
]['id'] = $dao->id
;
1605 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1611 * Create activities when Case or Other roles assigned/modified/deleted.
1613 * @param int $caseId
1614 * @param int $relationshipId
1616 * @param int $relContactId
1617 * Case role assignee contactId.
1618 * @param int $contactId
1620 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1621 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1626 if (is_array($relationshipId)) {
1627 $relationshipId = implode(',', $relationshipId);
1628 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1631 $relationshipClause = " civicrm_relationship.id = %1";
1632 $queryParam[1] = [$relationshipId, 'Positive'];
1636 SELECT cc.display_name as clientName,
1637 cca.display_name as assigneeContactName,
1638 civicrm_relationship.case_id as caseId,
1639 civicrm_relationship_type.label_a_b as relation_a_b,
1640 civicrm_relationship_type.label_b_a as relation_b_a,
1641 civicrm_relationship.contact_id_b as rel_contact_id,
1642 civicrm_relationship.contact_id_a as assign_contact_id
1643 FROM civicrm_relationship_type, civicrm_relationship
1644 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1645 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1646 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1648 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1650 while ($dao->fetch()) {
1651 // The assignee is not the client.
1652 if ($dao->rel_contact_id
!= $contactId) {
1653 $caseRelationship = $dao->relation_a_b
;
1654 $assigneContactName = $dao->clientName
;
1655 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1658 $caseRelationship = $dao->relation_b_a
;
1659 $assigneContactName = $dao->assigneeContactName
;
1660 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1664 $session = CRM_Core_Session
::singleton();
1666 'source_contact_id' => $session->get('userID'),
1667 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1668 'activity_date_time' => date('YmdHis'),
1669 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1672 //if $relContactId is passed, role is added or modified.
1673 if (!empty($relContactId)) {
1674 $activityParams['assignee_contact_id'] = $assigneContactIds;
1675 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1678 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1681 $activityParams['activity_type_id'] = $activityTypeID;
1683 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1685 //create case_activity record.
1687 'activity_id' => $activity->id
,
1688 'case_id' => $caseId,
1691 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1696 * contact which is assigned a case role of case manager.
1698 * @param int $caseType
1700 * @param int $caseId
1704 * html hyperlink of manager contact view page
1707 public static function getCaseManagerContact($caseType, $caseId) {
1708 if (!$caseType ||
!$caseId) {
1712 $caseManagerName = '---';
1713 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1715 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1717 if (!empty($managerRoleId)) {
1718 if (substr($managerRoleId, -4) == '_a_b') {
1719 $managerRoleQuery = "
1720 SELECT civicrm_contact.id as casemanager_id,
1721 civicrm_contact.sort_name as casemanager
1722 FROM civicrm_contact
1723 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
1724 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1725 WHERE civicrm_case.id = %2 AND is_active = 1";
1727 if (substr($managerRoleId, -4) == '_b_a') {
1728 $managerRoleQuery = "
1729 SELECT civicrm_contact.id as casemanager_id,
1730 civicrm_contact.sort_name as casemanager
1731 FROM civicrm_contact
1732 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
1733 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1734 WHERE civicrm_case.id = %2 AND is_active = 1";
1737 $managerRoleParams = [
1738 1 => [substr($managerRoleId, 0, -4), 'Integer'],
1739 2 => [$caseId, 'Integer'],
1742 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1743 if ($dao->fetch()) {
1744 $caseManagerName = sprintf('<a href="%s">%s</a>',
1745 CRM_Utils_System
::url('civicrm/contact/view', ['cid' => $dao->casemanager_id
]),
1751 return $caseManagerName;
1755 * @param int $contactId
1756 * @param bool $excludeDeleted
1760 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1761 $params = ['check_permissions' => TRUE];
1762 if ($excludeDeleted) {
1763 $params['is_deleted'] = 0;
1766 $params['contact_id'] = $contactId;
1769 return civicrm_api3('Case', 'getcount', $params);
1771 catch (CiviCRM_API3_Exception
$e) {
1772 // Lack of permissions will throw an exception
1778 * Retrieve related case ids for given case.
1780 * @param int $caseId
1781 * @param bool $excludeDeleted
1782 * Do not include deleted cases.
1786 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1787 //FIXME : do check for permissions.
1793 $linkActType = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Link Cases');
1794 if (!$linkActType) {
1798 $whereClause = "mainCase.id = %2";
1799 if ($excludeDeleted) {
1800 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1804 SELECT relCaseAct.case_id
1805 FROM civicrm_case mainCase
1806 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1807 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1808 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1809 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1810 WHERE $whereClause";
1812 $dao = CRM_Core_DAO
::executeQuery($query, [
1813 1 => [$linkActType, 'Integer'],
1814 2 => [$caseId, 'Integer'],
1816 $relatedCaseIds = [];
1817 while ($dao->fetch()) {
1818 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1821 return array_values($relatedCaseIds);
1825 * Retrieve related case details for given case.
1827 * @param int $caseId
1828 * @param bool $excludeDeleted
1829 * Do not include deleted cases.
1833 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1834 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1837 if (!$relatedCaseIds) {
1841 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1842 if ($excludeDeleted) {
1843 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1846 //filter for permissioned cases.
1848 $doFilterCases = FALSE;
1849 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1850 $doFilterCases = TRUE;
1851 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
1854 //2. fetch the details of related cases.
1856 SELECT relCase.id as id,
1857 civicrm_case_type.title as case_type,
1858 client.display_name as client_name,
1859 client.id as client_id,
1861 FROM civicrm_case relCase
1862 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1863 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1864 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1865 WHERE {$whereClause}";
1867 $dao = CRM_Core_DAO
::executeQuery($query);
1868 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
1869 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1870 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
1872 while ($dao->fetch()) {
1874 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
1875 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
1876 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
1877 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
1879 $clientView = $dao->client_name
;
1880 if ($hasViewContact) {
1881 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
1884 $relatedCases[$dao->id
] = [
1885 'case_id' => $dao->id
,
1886 'case_type' => $dao->case_type
,
1887 'client_name' => $clientView,
1888 'case_status' => $statuses[$dao->status_id
],
1889 'links' => $caseView,
1893 return $relatedCases;
1897 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
1899 * @param int $mainContactId
1900 * @param int $otherContactId
1902 * @see CRM_Dedupe_Merger::cpTables()
1904 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
1907 public static function mergeContacts($mainContactId, $otherContactId) {
1908 self
::mergeCases($mainContactId, NULL, $otherContactId);
1912 * Function perform two task.
1913 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
1914 * 2. Merge two cases of same contact - follow CRM-5598 rules.
1916 * @param int $mainContactId
1917 * Contact id of main contact record.
1918 * @param int $mainCaseId
1919 * Case id of main case record.
1920 * @param int $otherContactId
1921 * Contact id of record which is going to merge.
1922 * @param int $otherCaseId
1923 * Case id of record which is going to merge.
1925 * @param bool $changeClient
1928 * @throws \CRM_Core_Exception
1930 public static function mergeCases(
1931 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
1932 $otherCaseId = NULL, $changeClient = FALSE) {
1933 $moveToTrash = TRUE;
1935 $duplicateContacts = FALSE;
1936 if ($mainContactId && $otherContactId &&
1937 $mainContactId != $otherContactId
1939 $duplicateContacts = TRUE;
1942 $duplicateCases = FALSE;
1943 if ($mainCaseId && $otherCaseId &&
1944 $mainCaseId != $otherCaseId
1946 $duplicateCases = TRUE;
1950 if (!$duplicateContacts && !$duplicateCases) {
1951 return $mainCaseIds;
1954 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
1955 $completedActivityStatus = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1956 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1957 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1958 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1959 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1961 $processCaseIds = [$otherCaseId];
1962 if ($duplicateContacts && !$duplicateCases) {
1963 if ($changeClient) {
1964 $processCaseIds = [$mainCaseId];
1967 //get all case ids for other contact.
1968 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
1970 if (!is_array($processCaseIds)) {
1975 $session = CRM_Core_Session
::singleton();
1976 $currentUserId = $session->get('userID');
1978 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
1980 // copy all cases and connect to main contact id.
1981 foreach ($processCaseIds as $otherCaseId) {
1982 if ($duplicateContacts) {
1983 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', ['id' => $otherCaseId]);
1984 $mainCaseId = $mainCase->id
;
1989 $mainCaseIds[] = $mainCaseId;
1990 //insert record for case contact.
1991 $otherCaseContact = new CRM_Case_DAO_CaseContact();
1992 $otherCaseContact->case_id
= $otherCaseId;
1993 $otherCaseContact->find();
1994 while ($otherCaseContact->fetch()) {
1995 $mainCaseContact = new CRM_Case_DAO_CaseContact();
1996 $mainCaseContact->case_id
= $mainCaseId;
1997 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
1998 if ($mainCaseContact->contact_id
== $otherContactId) {
1999 $mainCaseContact->contact_id
= $mainContactId;
2001 //avoid duplicate object.
2002 if (!$mainCaseContact->find(TRUE)) {
2003 $mainCaseContact->save();
2007 elseif (!$otherContactId) {
2008 $otherContactId = $mainContactId;
2011 if (!$mainCaseId ||
!$otherCaseId ||
2012 !$mainContactId ||
!$otherContactId
2017 // get all activities for other case.
2018 $otherCaseActivities = [];
2019 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2021 //for duplicate cases do not process singleton activities.
2022 $otherActivityIds = $singletonActivityIds = [];
2023 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2024 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2025 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2028 $otherActivityIds[] = $otherActId;
2030 if ($duplicateCases) {
2031 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2034 FROM civicrm_activity
2035 WHERE activity_type_id = $openCaseType
2036 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2037 $dao = CRM_Core_DAO
::executeQuery($sql);
2038 while ($dao->fetch()) {
2039 $singletonActivityIds[] = $dao->id
;
2044 // migrate all activities and connect to main contact.
2045 $copiedActivityIds = $activityMappingIds = [];
2046 sort($otherActivityIds);
2047 foreach ($otherActivityIds as $otherActivityId) {
2049 //for duplicate cases -
2050 //do not migrate singleton activities.
2051 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2055 //migrate activity record.
2056 $otherActivity = new CRM_Activity_DAO_Activity();
2057 $otherActivity->id
= $otherActivityId;
2058 if (!$otherActivity->find(TRUE)) {
2063 $mainActivity = new CRM_Activity_DAO_Activity();
2064 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2065 $mainActivity->copyValues($mainActVals);
2066 $mainActivity->id
= NULL;
2067 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2068 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2072 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2076 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2079 $mainActivity->save();
2080 $mainActivityId = $mainActivity->id
;
2081 if (!$mainActivityId) {
2085 $activityMappingIds[$otherActivityId] = $mainActivityId;
2086 // insert log of all activities
2087 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2089 $copiedActivityIds[] = $otherActivityId;
2091 //create case activity record.
2092 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2093 $mainCaseActivity->case_id
= $mainCaseId;
2094 $mainCaseActivity->activity_id
= $mainActivityId;
2095 $mainCaseActivity->save();
2097 //migrate source activity.
2098 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2099 $otherSourceActivity->activity_id
= $otherActivityId;
2100 $otherSourceActivity->record_type_id
= $sourceID;
2101 $otherSourceActivity->find();
2102 while ($otherSourceActivity->fetch()) {
2103 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2104 $mainActivitySource->record_type_id
= $sourceID;
2105 $mainActivitySource->activity_id
= $mainActivityId;
2106 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2107 if ($mainActivitySource->contact_id
== $otherContactId) {
2108 $mainActivitySource->contact_id
= $mainContactId;
2110 //avoid duplicate object.
2111 if (!$mainActivitySource->find(TRUE)) {
2112 $mainActivitySource->save();
2116 //migrate target activities.
2117 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2118 $otherTargetActivity->activity_id
= $otherActivityId;
2119 $otherTargetActivity->record_type_id
= $targetID;
2120 $otherTargetActivity->find();
2121 while ($otherTargetActivity->fetch()) {
2122 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2123 $mainActivityTarget->record_type_id
= $targetID;
2124 $mainActivityTarget->activity_id
= $mainActivityId;
2125 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2126 if ($mainActivityTarget->contact_id
== $otherContactId) {
2127 $mainActivityTarget->contact_id
= $mainContactId;
2129 //avoid duplicate object.
2130 if (!$mainActivityTarget->find(TRUE)) {
2131 $mainActivityTarget->save();
2135 //migrate assignee activities.
2136 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2137 $otherAssigneeActivity->activity_id
= $otherActivityId;
2138 $otherAssigneeActivity->record_type_id
= $assigneeID;
2139 $otherAssigneeActivity->find();
2140 while ($otherAssigneeActivity->fetch()) {
2141 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2142 $mainAssigneeActivity->activity_id
= $mainActivityId;
2143 $mainAssigneeActivity->record_type_id
= $assigneeID;
2144 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2145 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2146 $mainAssigneeActivity->contact_id
= $mainContactId;
2148 //avoid duplicate object.
2149 if (!$mainAssigneeActivity->find(TRUE)) {
2150 $mainAssigneeActivity->save();
2154 // copy custom fields and attachments
2156 'activityID' => $otherActivityId,
2157 'mainActivityId' => $mainActivityId,
2159 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2162 //copy case relationship.
2163 if ($duplicateContacts) {
2164 //migrate relationship records.
2165 $otherRelationship = new CRM_Contact_DAO_Relationship();
2166 $otherRelationship->case_id
= $otherCaseId;
2167 $otherRelationship->find();
2168 $otherRelationshipIds = [];
2169 while ($otherRelationship->fetch()) {
2171 $updateOtherRel = FALSE;
2172 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2174 $mainRelationship = new CRM_Contact_DAO_Relationship();
2175 $mainRelationship->copyValues($otherRelVals);
2176 $mainRelationship->id
= NULL;
2177 $mainRelationship->case_id
= $mainCaseId;
2178 if ($mainRelationship->contact_id_a
== $otherContactId) {
2179 $updateOtherRel = TRUE;
2180 $mainRelationship->contact_id_a
= $mainContactId;
2183 //case creator change only when we merge user contact.
2184 if ($mainRelationship->contact_id_b
== $otherContactId) {
2185 //do not change creator for change client.
2186 if (!$changeClient) {
2187 $updateOtherRel = TRUE;
2188 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2191 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2192 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2194 //avoid duplicate object.
2195 if (!$mainRelationship->find(TRUE)) {
2196 $mainRelationship->save();
2199 //get the other relationship ids to update end date.
2200 if ($updateOtherRel) {
2201 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2205 //update other relationships end dates
2206 if (!empty($otherRelationshipIds)) {
2207 $sql = 'UPDATE civicrm_relationship
2208 SET end_date = CURDATE()
2209 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2210 CRM_Core_DAO
::executeQuery($sql);
2214 //move other case to trash.
2215 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2220 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2221 if ($changeClient) {
2222 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2223 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2225 $mergeActType = array_search('Reassigned Case', $activityTypes);
2226 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2229 2 => $otherContactDisplayName,
2230 3 => $mainContactDisplayName,
2235 elseif ($duplicateContacts) {
2236 $mergeActType = array_search('Merge Case', $activityTypes);
2237 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2240 2 => $otherContactId,
2241 3 => $mainContactId,
2247 $mergeActType = array_search('Merge Case', $activityTypes);
2248 $mergeActSubject = ts("Case %1 merged into case %2", [1 => $otherCaseId, 2 => $mainCaseId]);
2249 if (!empty($copiedActivityIds)) {
2251 SELECT id, subject, activity_date_time, activity_type_id
2252 FROM civicrm_activity
2253 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2254 $dao = CRM_Core_DAO
::executeQuery($sql);
2255 while ($dao->fetch()) {
2256 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2257 if ($dao->subject
) {
2258 $mergeActSubjectDetails .= " :: {$dao->subject}";
2260 $mergeActSubjectDetails .= "<br />";
2265 // Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2267 'subject' => $mergeActSubject,
2268 'details' => $mergeActSubjectDetails,
2269 'status_id' => $completedActivityStatus,
2270 'activity_type_id' => $mergeActType,
2271 'source_contact_id' => $currentUserId,
2272 'activity_date_time' => date('YmdHis'),
2275 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2276 $mergeActivityId = $mergeActivity->id
;
2277 if (!$mergeActivityId) {
2281 //connect merge activity to case.
2283 'case_id' => $mainCaseId,
2284 'activity_id' => $mergeActivityId,
2287 self
::processCaseActivity($mergeCaseAct);
2290 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2292 return $mainCaseIds;
2296 * Validate contact permission for
2297 * edit/view on activity record and build links.
2299 * @param array $tplParams
2300 * Params to be sent to template for sending email.
2301 * @param array $activityParams
2302 * Info of the activity.
2304 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2305 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2306 'activity_type_id', 'id'
2309 if (!empty($tplParams['isCaseActivity'])) {
2310 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2311 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2314 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2315 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2318 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2319 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2323 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2324 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2327 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2328 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2334 * Validate contact permission for
2335 * given operation on activity record.
2337 * @param int $activityId
2338 * Activity record id.
2339 * @param string $operation
2341 * @param int $actTypeId
2343 * @param int $contactId
2344 * Contact id/if not pass consider logged in.
2345 * @param bool $checkComponent
2346 * Do we need to check component enabled.
2350 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2352 if (!$actTypeId && $activityId) {
2353 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2356 if (!$activityId ||
!$operation ||
!$actTypeId) {
2360 //do check for civicase component enabled.
2361 if ($checkComponent && !self
::enabled()) {
2365 //do check for cases.
2366 $caseActOperations = [
2373 if (in_array($operation, $caseActOperations)) {
2375 if (!isset($caseCount)) {
2377 $caseCount = civicrm_api3('Case', 'getcount', [
2378 'check_permissions' => TRUE,
2379 'status_id' => ['!=' => 'Closed'],
2381 'end_date' => ['IS NULL' => 1],
2384 catch (CiviCRM_API3_Exception
$e) {
2385 // Lack of permissions will throw an exception
2389 if ($operation == 'File On Case') {
2390 $allow = !empty($caseCount);
2393 $allow = ($caseCount > 1);
2397 $actionOperations = ['view', 'edit', 'delete'];
2398 if (in_array($operation, $actionOperations)) {
2400 //do cache when user has non/supper permission.
2401 static $allowOperations;
2403 if (!is_array($allowOperations) ||
2404 !array_key_exists($operation, $allowOperations)
2408 $session = CRM_Core_Session
::singleton();
2409 $contactId = $session->get('userID');
2412 //check for permissions.
2415 'access my cases and activities',
2416 'access all cases and activities',
2419 'access my cases and activities',
2420 'access all cases and activities',
2422 'delete' => ['delete activities'],
2425 //check for core permission.
2426 $hasPermissions = [];
2427 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2428 if (is_array($checkPermissions)) {
2429 foreach ($checkPermissions as $per) {
2430 if (CRM_Core_Permission
::check($per)) {
2431 $hasPermissions[$operation][] = $per;
2437 if (!empty($hasPermissions)) {
2438 //need to check activity object specific.
2439 if (in_array($operation, [
2444 //do we have supper permission.
2445 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2446 $allowOperations[$operation] = $allow = TRUE;
2449 //user has only access to my cases and activity.
2450 //here object specific permmions come in picture.
2452 //edit - contact must be source or assignee
2453 //view - contact must be source/assignee/target
2454 $isTarget = $isAssignee = $isSource = FALSE;
2455 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2456 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2457 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2458 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2460 $target = new CRM_Activity_DAO_ActivityContact();
2461 $target->record_type_id
= $targetID;
2462 $target->activity_id
= $activityId;
2463 $target->contact_id
= $contactId;
2464 if ($target->find(TRUE)) {
2468 $assignee = new CRM_Activity_DAO_ActivityContact();
2469 $assignee->activity_id
= $activityId;
2470 $assignee->record_type_id
= $assigneeID;
2471 $assignee->contact_id
= $contactId;
2472 if ($assignee->find(TRUE)) {
2476 $source = new CRM_Activity_DAO_ActivityContact();
2477 $source->activity_id
= $activityId;
2478 $source->record_type_id
= $sourceID;
2479 $source->contact_id
= $contactId;
2480 if ($source->find(TRUE)) {
2484 if ($operation == 'edit') {
2485 if ($isAssignee ||
$isSource) {
2489 if ($operation == 'view') {
2490 if ($isTarget ||
$isAssignee ||
$isSource) {
2496 elseif (is_array($hasPermissions[$operation])) {
2497 $allowOperations[$operation] = $allow = TRUE;
2501 //contact do not have permission.
2502 $allowOperations[$operation] = FALSE;
2507 //here contact might have supper/non permission.
2508 $allow = $allowOperations[$operation];
2512 //do further only when operation is granted.
2514 $actTypeName = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $actTypeId);
2516 //do not allow multiple copy / edit action.
2527 //do not allow to delete these activities, CRM-4543
2528 $doNotDeleteNames = ['Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date'];
2530 //allow edit operation.
2531 $allowEditNames = ['Open Case'];
2533 if (CRM_Activity_BAO_Activity
::checkEditInboundEmailsPermissions()) {
2534 $allowEditNames[] = 'Inbound Email';
2537 // do not allow File on Case
2541 'Change Case Status',
2542 'Change Case Start Date',
2549 if (in_array($actTypeName, $singletonNames)) {
2551 if ($operation == 'File On Case') {
2552 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2554 if (in_array($operation, $actionOperations)) {
2556 if ($operation == 'edit') {
2557 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2559 elseif ($operation == 'delete') {
2560 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2564 if ($allow && ($operation == 'delete') &&
2565 in_array($actTypeName, $doNotDeleteNames)
2570 if ($allow && ($operation == 'File On Case') &&
2571 in_array($actTypeName, $doNotFileNames)
2576 //check settings file for masking actions
2577 //on the basis the activity types
2578 //hide Edit link if activity type is NOT editable
2579 //(special case activities).CRM-5871
2580 if ($allow && in_array($operation, $actionOperations)) {
2581 static $actionFilter = [];
2582 if (!array_key_exists($operation, $actionFilter)) {
2583 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2584 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2586 if (array_key_exists($operation, $actionFilter[$operation]) &&
2587 in_array($actTypeId, $actionFilter[$operation][$operation])
2598 * Since we drop 'access CiviCase', allow access
2599 * if user has 'access my cases and activities'
2600 * or 'access all cases and activities'
2602 public static function accessCiviCase() {
2603 if (!self
::enabled()) {
2607 if (CRM_Core_Permission
::check('access my cases and activities') ||
2608 CRM_Core_Permission
::check('access all cases and activities')
2617 * Verify user has permission to access a case.
2619 * @param int $caseId
2620 * @param bool $denyClosed
2621 * Set TRUE if one wants closed cases to be treated as inaccessible.
2625 public static function accessCase($caseId, $denyClosed = TRUE) {
2626 if (!$caseId ||
!self
::enabled()) {
2630 $params = ['id' => $caseId, 'check_permissions' => TRUE];
2631 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2632 $params['status_id'] = ['!=' => 'Closed'];
2635 return (bool) civicrm_api3('Case', 'getcount', $params);
2637 catch (CiviCRM_API3_Exception
$e) {
2638 // Lack of permissions will throw an exception
2644 * Check whether activity is a case Activity.
2646 * @param int $activityID
2651 public static function isCaseActivity($activityID) {
2652 $isCaseActivity = FALSE;
2654 $params = [1 => [$activityID, 'Integer']];
2655 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2656 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2657 $isCaseActivity = TRUE;
2661 return $isCaseActivity;
2665 * Get all the case type ids currently in use.
2669 public static function getUsedCaseType() {
2670 static $caseTypeIds;
2672 if (!is_array($caseTypeIds)) {
2673 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2675 $dao = CRM_Core_DAO
::executeQuery($query);
2677 while ($dao->fetch()) {
2678 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2681 $caseTypeIds[] = $typeId[1];
2685 return $caseTypeIds;
2689 * Get all the case status ids currently in use.
2693 public static function getUsedCaseStatuses() {
2694 static $caseStatusIds;
2696 if (!is_array($caseStatusIds)) {
2697 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2699 $dao = CRM_Core_DAO
::executeQuery($query);
2700 $caseStatusIds = [];
2701 while ($dao->fetch()) {
2702 $caseStatusIds[] = $dao->status_id
;
2706 return $caseStatusIds;
2710 * Get all the encounter medium ids currently in use.
2714 public static function getUsedEncounterMediums() {
2717 if (!is_array($mediumIds)) {
2718 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2720 $dao = CRM_Core_DAO
::executeQuery($query);
2722 while ($dao->fetch()) {
2723 $mediumIds[] = $dao->medium_id
;
2731 * Check case configuration.
2733 * @param int $contactId
2737 public static function isCaseConfigured($contactId = NULL) {
2738 $configured = array_fill_keys(['configured', 'allowToAddNewCase', 'redirectToCaseAdmin'], FALSE);
2740 //lets check for case configured.
2741 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2742 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2743 if (!$configured['configured']) {
2744 //do check for case type and case status.
2745 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2746 if (!empty($caseTypes)) {
2747 $configured['configured'] = TRUE;
2748 if (!$configured['configured']) {
2749 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2750 if (!empty($caseStatuses)) {
2751 $configured['configured'] = TRUE;
2756 if ($configured['configured']) {
2757 //do check for active case type and case status.
2758 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2759 if (!empty($caseTypes)) {
2760 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2761 if (!empty($caseStatuses)) {
2762 $configured['allowToAddNewCase'] = TRUE;
2766 //do we need to redirect user to case admin.
2767 if (!$configured['allowToAddNewCase'] && $contactId) {
2768 //check for current contact case count.
2769 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2770 //redirect user to case admin page.
2771 if (!$currentContatCasesCount) {
2772 $configured['redirectToCaseAdmin'] = TRUE;
2781 * Used during case component enablement and during ugprade.
2785 public static function createCaseViews() {
2786 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2787 $dao = new CRM_Core_DAO();
2789 $sql = self
::createCaseViewsQuery('upcoming');
2791 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2795 // Above error doesn't get caught?
2796 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2797 if (is_null($doublecheck)) {
2801 $sql = self
::createCaseViewsQuery('recent');
2803 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2807 // Above error doesn't get caught?
2808 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2809 if (is_null($doublecheck)) {
2817 * Helper function, also used by the upgrade in case of error
2819 * @param string $section
2823 public static function createCaseViewsQuery($section = 'upcoming') {
2825 $scheduled_id = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2828 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2829 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2830 FROM civicrm_case_activity ca
2831 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2833 (SELECT b.id FROM civicrm_case_activity bca
2834 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2835 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
2836 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
2837 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
2841 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
2842 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2843 FROM civicrm_case_activity ca
2844 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2846 (SELECT b.id FROM civicrm_case_activity bca
2847 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2848 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
2849 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
2850 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
2857 * Add/copy relationships, when new client is added for a case
2859 * @param int $caseId
2861 * @param int $contactId
2862 * Contact id / new client id.
2864 public static function addCaseRelationships($caseId, $contactId) {
2865 // get the case role / relationships for the case
2866 $caseRelationships = new CRM_Contact_DAO_Relationship();
2867 $caseRelationships->case_id
= $caseId;
2868 $caseRelationships->find();
2869 $relationshipTypes = [];
2871 // make sure we don't add duplicate relationships of same relationship type.
2872 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
2874 CRM_Core_DAO
::storeValues($caseRelationships, $values);
2876 // add relationship for new client.
2877 $newRelationship = new CRM_Contact_DAO_Relationship();
2878 $newRelationship->copyValues($values);
2879 $newRelationship->id
= NULL;
2880 $newRelationship->case_id
= $caseId;
2881 $newRelationship->contact_id_a
= $contactId;
2882 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
2883 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
2885 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
2886 if (!$newRelationship->find(TRUE)) {
2887 $newRelationship->save();
2890 // store relationship type of newly created relationship
2891 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
2896 * Get the list of clients for a case.
2898 * @param int $caseId
2901 * associated array with client ids
2903 public static function getCaseClients($caseId) {
2905 $caseContact = new CRM_Case_DAO_CaseContact();
2906 $caseContact->case_id
= $caseId;
2907 $caseContact->orderBy('id');
2908 $caseContact->find();
2910 while ($caseContact->fetch()) {
2911 $clients[] = $caseContact->contact_id
;
2918 * @param int $caseId
2919 * @param string $direction
2921 * @param int $relTypeId
2923 * @throws \CRM_Core_Exception
2924 * @throws \CiviCRM_API3_Exception
2926 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
2928 if ($direction !== 'a' && $direction !== 'b') {
2929 throw new CRM_Core_Exception('Invalid relationship direction');
2932 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
2933 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
2934 $dao = CRM_Core_DAO
::executeQuery($sql, [
2935 1 => [$caseId, 'Positive'],
2936 2 => [$cid, 'Positive'],
2937 3 => [$relTypeId, 'Positive'],
2939 while ($dao->fetch()) {
2940 civicrm_api3('relationship', 'create', [
2943 'end_date' => 'now',
2949 * Get options for a given case field.
2951 * @param string $fieldName
2952 * @param string $context
2953 * @param array $props
2954 * Whatever is known about this dao object.
2956 * @return array|bool
2957 * @throws \CiviCRM_API3_Exception
2959 * @see CRM_Core_DAO::buildOptionsContext
2960 * @see CRM_Core_DAO::buildOptions
2963 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2964 $className = __CLASS__
;
2966 switch ($fieldName) {
2967 // This field is not part of this object but the api supports it
2969 $className = 'CRM_Activity_BAO_Activity';
2972 // Filter status id by case type id
2974 if (!empty($props['case_type_id'])) {
2975 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
2976 $caseType = civicrm_api3('CaseType', 'getsingle', [$idField => $props['case_type_id'], 'return' => 'definition']);
2977 if (!empty($caseType['definition']['statuses'])) {
2978 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
2983 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
2989 public function addSelectWhereClause() {
2990 // We always return an array with these keys, even if they are empty,
2991 // because this tells the query builder that we have considered these fields for acls
2994 // Only case admins can view deleted cases
2995 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
[] : ["= 0"],
2997 // Ensure the user has permission to view the case client
2998 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
2999 if ($contactClause) {
3000 $contactClause = implode(' AND contact_id ', $contactClause);
3001 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3003 // The api gatekeeper ensures the user has at least "access my cases and activities"
3004 // so if they do not have permission to see all cases we'll assume they can only access their own
3005 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3006 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3007 $clauses['id'][] = "IN (
3008 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 (
3009 (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)
3013 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3018 * CRM-20308: Method to get the contact id to use as from contact for email copy
3019 * 1. Activity Added by Contact's email address
3020 * 2. System Default From Address
3021 * 3. Default Organization Contact email address
3024 * @param int $activityID
3026 * @return mixed $emailFromContactId
3028 * @throws \CiviCRM_API3_Exception
3029 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3031 public static function getReceiptFrom($activityID) {
3032 $name = $address = NULL;
3034 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3035 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3036 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3037 // There is always a 'Added by' contact for a activity,
3038 // so we can safely use ActivityContact.Getvalue API
3039 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', [
3040 'activity_id' => $activityID,
3041 'record_type_id' => 'Activity Source',
3042 'return' => 'contact_id',
3044 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3047 // If 'From' email address not found for Source Activity Contact then
3048 // fetch the email from domain or logged in user.
3049 if (empty($address)) {
3050 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3053 return "$name <$address>";
3059 public static function getEntityRefFilters() {
3062 'key' => 'case_id.case_type_id',
3063 'value' => ts('Case Type'),
3067 'key' => 'case_id.status_id',
3068 'value' => ts('Case Status'),
3072 foreach (CRM_Contact_BAO_Contact
::getEntityRefFilters() as $filter) {
3073 $filter +
= ['entity' => 'Contact'];
3074 $filter['key'] = 'contact_id.' . $filter['key'];
3075 $filters[] = $filter;
3081 * Fetch Case Role direction from Case Type
3083 public static function getCaseRoleDirection($caseId, $roleTypeId = NULL) {
3085 $case = civicrm_api3('Case', 'getsingle', ['id' => $caseId]);
3087 catch (CiviCRM_API3_Exception
$e) {
3088 // Lack of permissions will throw an exception
3091 if (!empty($case['case_type_id'])) {
3093 $caseType = civicrm_api3('CaseType', 'getsingle', ['id' => $case['case_type_id'], 'return' => ['definition']]);
3095 catch (CiviCRM_API3_Exception
$e) {
3096 // Lack of permissions will throw an exception
3097 return 'no case type found';
3099 if (!empty($caseType['definition']['caseRoles'])) {
3101 foreach ($caseType['definition']['caseRoles'] as $key => $roleDetails) {
3102 // Check if its an a_b label
3104 $relType = civicrm_api3('RelationshipType', 'getsingle', ['label_a_b' => $roleDetails['name']]);
3106 catch (CiviCRM_API3_Exception
$e) {
3108 if (!empty($relType['id'])) {
3109 $roleDetails['id'] = $relType['id'];
3110 $roleDetails['direction'] = 'b_a';
3112 // Check if its a b_a label
3114 $relTypeBa = civicrm_api3('RelationshipType', 'getsingle', ['label_b_a' => $roleDetails['name']]);
3116 catch (CiviCRM_API3_Exception
$e) {
3118 if (!empty($relTypeBa['id'])) {
3119 if (!empty($roleDetails['direction'])) {
3120 $roleDetails['direction'] = 'bidrectional';
3123 $roleDetails['id'] = $relTypeBa['id'];
3124 $roleDetails['direction'] = 'a_b';
3127 $caseRoles[$roleDetails['id']] = $roleDetails;