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
20 * This class contains the functions for Case Management.
22 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
25 * Static field for all the case information that we can potentially export.
29 public static $_exportableFields = NULL;
34 public function __construct() {
35 parent
::__construct();
39 * Is CiviCase enabled?
43 public static function enabled() {
44 $config = CRM_Core_Config
::singleton();
45 return in_array('CiviCase', $config->enableComponents
);
49 * Create a case object.
51 * The function extracts all the params it needs to initialize the create a
52 * case object. the params array could contain additional unused name/value
55 * @param array $params
56 * (reference ) an assoc array of name/value pairs.
58 * @return CRM_Case_BAO_Case
60 public static function add(&$params) {
61 $caseDAO = new CRM_Case_DAO_Case();
62 $caseDAO->copyValues($params);
63 $result = $caseDAO->save();
64 // Get other case values (required by XML processor), this adds to $result array
70 * Takes an associative array and creates a case object.
72 * @param array $params
73 * (reference) an assoc array of name/value pairs.
75 * @return CRM_Case_BAO_Case
77 public static function &create(&$params) {
78 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
79 unset($params['created_date']);
80 unset($params['modified_date']);
81 $caseStatus = CRM_Case_PseudoConstant
::caseStatus('name');
82 // for resolved case the end date should set to now
83 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
84 $params['end_date'] = date("Ymd");
87 $transaction = new CRM_Core_Transaction();
89 if (!empty($params['id'])) {
90 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
93 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
96 $case = self
::add($params);
98 if (!empty($params['custom']) &&
99 is_array($params['custom'])
101 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
104 if (is_a($case, 'CRM_Core_Error')) {
105 $transaction->rollback();
109 if (!empty($params['id'])) {
110 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
113 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
115 $transaction->commit();
117 //we are not creating log for case
118 //since case log can be tracked using log for activity.
123 * Process case activity add/delete
124 * takes an associative array and
126 * @param array $params
127 * (reference ) an assoc array of name/value pairs.
130 public static function processCaseActivity(&$params) {
131 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
132 $caseActivityDAO->activity_id
= $params['activity_id'];
133 $caseActivityDAO->case_id
= $params['case_id'];
135 $caseActivityDAO->find(TRUE);
136 $caseActivityDAO->save();
140 * Get the case subject for Activity.
142 * @param int $activityId
145 * @return string|null
147 public static function getCaseSubject($activityId) {
148 $caseActivity = new CRM_Case_DAO_CaseActivity();
149 $caseActivity->activity_id
= $activityId;
150 if ($caseActivity->find(TRUE)) {
151 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
160 * @param string $colName
165 public static function getCaseType($caseId, $colName = 'title') {
167 SELECT civicrm_case_type.{$colName} FROM civicrm_case
168 LEFT JOIN civicrm_case_type ON
169 civicrm_case.case_type_id = civicrm_case_type.id
170 WHERE civicrm_case.id = %1";
172 $queryParams = [1 => [$caseId, 'Integer']];
174 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
178 * Delete the record that are associated with this case.
179 * record are deleted from case
182 * Id of the case to delete.
184 * @param bool $moveToTrash
189 public static function deleteCase($caseId, $moveToTrash = FALSE) {
190 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
193 $activities = self
::getCaseActivityDates($caseId);
195 foreach ($activities as $value) {
196 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
201 $transaction = new CRM_Core_Transaction();
203 $case = new CRM_Case_DAO_Case();
206 $result = $case->delete();
207 $transaction->commit();
210 $result = $case->is_deleted
= 1;
215 // CRM-7364, disable relationships
216 self
::enableDisableCaseRelationships($caseId, FALSE);
218 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
220 // remove case from recent items.
225 CRM_Utils_Recent
::del($caseRecent);
233 * Enable disable case related relationships.
237 * @param bool $enable
240 public static function enableDisableCaseRelationships($caseId, $enable) {
241 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
242 if (!empty($contactIds)) {
243 foreach ($contactIds as $cid) {
244 $roles = self
::getCaseRoles($cid, $caseId);
245 if (!empty($roles)) {
246 $relationshipIds = implode(',', array_keys($roles));
247 $enable = (int) $enable;
248 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
249 WHERE id IN ( {$relationshipIds} )";
250 CRM_Core_DAO
::executeQuery($query);
257 * Retrieve contact_id by case_id.
262 * @param int $contactID
263 * @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
267 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
268 $caseContact = new CRM_Case_DAO_CaseContact();
269 $caseContact->case_id
= $caseId;
270 $caseContact->find();
272 $count = $startArrayAt;
273 while ($caseContact->fetch()) {
274 if ($contactID != $caseContact->contact_id
) {
275 $contactArray[$count] = $caseContact->contact_id
;
280 return $contactArray;
284 * Look up a case using an activity ID.
286 * @param int $activityId
288 * @return int|null, case ID
290 public static function getCaseIdByActivityId($activityId) {
291 $originalId = CRM_Core_DAO
::singleValueQuery(
292 'SELECT original_id FROM civicrm_activity WHERE id = %1',
293 ['1' => [$activityId, 'Integer']]
295 $caseId = CRM_Core_DAO
::singleValueQuery(
296 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
298 '1' => [$activityId, 'Integer'],
299 '2' => [$originalId ?
$originalId : $activityId, 'Integer'],
306 * Retrieve contact names by caseId.
313 public static function getContactNames($caseId) {
316 return $contactNames;
320 SELECT contact_a.sort_name name,
321 contact_a.display_name as display_name,
323 contact_a.birth_date as birth_date,
326 FROM civicrm_contact contact_a
327 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
328 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
329 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
330 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
331 ORDER BY civicrm_case_contact.id";
333 $dao = CRM_Core_DAO
::executeQuery($query,
334 [1 => [$caseId, 'Integer']]
336 while ($dao->fetch()) {
337 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
338 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
339 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
340 $contactNames[$dao->cid
]['email'] = $dao->email
;
341 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
342 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
343 $contactNames[$dao->cid
]['role'] = ts('Client');
346 return $contactNames;
350 * Retrieve case_id by contact_id.
352 * @param int $contactID
353 * @param bool $includeDeleted
354 * Include the deleted cases in result.
355 * @param null $caseType
359 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
362 FROM civicrm_case_contact cc
363 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
365 if (isset($caseType)) {
367 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
368 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
370 if (!isset($caseType)) {
371 $query .= "WHERE cc.contact_id = %1";
373 if (!$includeDeleted) {
374 $query .= " AND ca.is_deleted = 0";
377 $params = [1 => [$contactID, 'Integer']];
378 $dao = CRM_Core_DAO
::executeQuery($query, $params);
381 while ($dao->fetch()) {
382 $caseArray[] = $dao->id
;
389 * @param string $type
391 * @param string $condition
395 public static function getCaseActivityCountQuery($type = 'upcoming', $userID, $condition = NULL) {
396 return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self
::getCaseActivityQuery($type, $userID, $condition));
400 * @param string $type
402 * @param string $condition
403 * @param string $limit
404 * @param string $order
408 public static function getCaseActivityQuery($type = 'upcoming', $userID, $condition = NULL, $limit = NULL, $order = NULL) {
410 'civicrm_case.id as case_id',
411 'civicrm_case.subject as case_subject',
412 'civicrm_contact.id as contact_id',
413 'civicrm_contact.sort_name as sort_name',
414 'civicrm_phone.phone as phone',
415 'civicrm_contact.contact_type as contact_type',
416 'civicrm_contact.contact_sub_type as contact_sub_type',
417 't_act.activity_type_id as activity_type_id',
418 'civicrm_case.case_type_id as case_type_id',
419 'civicrm_case.status_id as case_status_id',
420 't_act.status_id as status_id',
421 'civicrm_case.start_date as case_start_date',
422 "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",
423 't_act.activity_date_time as activity_date_time',
424 't_act.id as activity_id',
427 $query = CRM_Contact_BAO_Query
::appendAnyValueToSelect($selectClauses, 'case_id');
431 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
432 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id
438 // civicrm_view_case_activity_upcoming and
439 // civicrm_view_case_activity_recent are views that show the next
440 // scheduled and most recent not-scheduled activity on each case,
443 INNER JOIN civicrm_view_case_activity_$type t_act
444 ON t_act.case_id = civicrm_case.id
450 LEFT JOIN civicrm_case_activity ca4
451 ON civicrm_case.id = ca4.case_id
452 LEFT JOIN civicrm_activity t_act
453 ON t_act.id = ca4.activity_id
454 AND t_act.is_current_revision = 1
459 LEFT JOIN civicrm_phone
460 ON civicrm_phone.contact_id = civicrm_contact.id
461 AND civicrm_phone.is_primary = 1
462 LEFT JOIN civicrm_relationship case_relationship
463 ON ((case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID})
464 OR (case_relationship.contact_id_b = civicrm_case_contact.contact_id AND case_relationship.contact_id_a = {$userID}))
465 AND case_relationship.is_active
466 AND case_relationship.case_id = civicrm_case.id
467 LEFT JOIN civicrm_relationship_type case_relation_type
468 ON case_relation_type.id = case_relationship.relationship_type_id
469 AND case_relation_type.id = case_relationship.relationship_type_id
473 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
474 $query .= " WHERE (1) AND $condition ";
476 $query .= " GROUP BY case_id ";
478 $query .= ($order) ?
: ' ORDER BY activity_date_time ASC';
488 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
490 * @param bool $allCases
491 * @param array $params
492 * @param string $context
493 * @param bool $getCount
498 public static function getCases($allCases = TRUE, $params = [], $context = 'dashboard', $getCount = FALSE) {
502 // validate access for own cases.
503 if (!self
::accessCiviCase()) {
504 return $getCount ?
0 : $casesList;
507 // Return cached value instead of re-running query
508 if (isset(Civi
::$statics[__CLASS__
]['totalCount']) && $getCount) {
509 return Civi
::$statics[__CLASS__
]['totalCount'];
512 $type = CRM_Utils_Array
::value('type', $params, 'upcoming');
513 $userID = CRM_Core_Session
::getLoggedInContactID();
515 // validate access for all cases.
516 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
520 $whereClauses = ['civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1'];
523 $whereClauses[] = "(case_relationship.contact_id_b = {$userID} OR case_relationship.contact_id_a = {$userID})";
524 $whereClauses[] = 'case_relationship.is_active';
526 if (empty($params['status_id']) && ($type == 'upcoming' ||
$type == 'any')) {
527 $whereClauses[] = "civicrm_case.status_id != " . CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
530 foreach (['case_type_id', 'status_id'] as $column) {
531 if (!empty($params[$column])) {
532 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
535 $condition = implode(' AND ', $whereClauses);
537 Civi
::$statics[__CLASS__
]['totalCount'] = $totalCount = CRM_Core_DAO
::singleValueQuery(self
::getCaseActivityCountQuery($type, $userID, $condition));
541 $casesList['total'] = $totalCount;
544 if (!empty($params['rp'])) {
545 $params['offset'] = ($params['page'] - 1) * $params['rp'];
546 $params['rowCount'] = $params['rp'];
547 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
548 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
553 if (!empty($params['sortBy'])) {
554 if (strstr($params['sortBy'], 'date ')) {
555 $params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
557 $order = "ORDER BY " . $params['sortBy'];
560 $query = self
::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
561 $result = CRM_Core_DAO
::executeQuery($query);
563 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
564 $actions = CRM_Case_Selector_Search
::links();
566 // check is the user has view/edit signer permission
567 $permissions = [CRM_Core_Permission
::VIEW
];
568 if (CRM_Core_Permission
::check('access all cases and activities') ||
569 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
571 $permissions[] = CRM_Core_Permission
::EDIT
;
573 if (CRM_Core_Permission
::check('delete in CiviCase')) {
574 $permissions[] = CRM_Core_Permission
::DELETE
;
576 $mask = CRM_Core_Action
::mask($permissions);
578 // Pseudoconstants to populate labels
579 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
580 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
581 $caseTypeTitles = CRM_Case_PseudoConstant
::caseType('title', FALSE);
582 $activityTypeLabels = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
584 foreach ($result->fetchAll() as $case) {
585 $key = $case['case_id'];
586 $casesList[$key] = [];
587 $casesList[$key]['DT_RowId'] = $case['case_id'];
588 $casesList[$key]['DT_RowAttr'] = ['data-entity' => 'case', 'data-id' => $case['case_id']];
589 $casesList[$key]['DT_RowClass'] = "crm-entity";
591 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
593 CRM_Utils_System
::url('civicrm/case/details', ['caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type])
596 $phone = empty($case['phone']) ?
'' : '<br /><span class="description">' . $case['phone'] . '</span>';
597 $casesList[$key]['sort_name'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
598 CRM_Utils_System
::url('civicrm/contact/view', ['cid' => $case['contact_id']]),
604 $casesList[$key]['subject'] = $case['case_subject'];
605 $casesList[$key]['case_status'] = $caseStatuses[$case['case_status_id']] ??
NULL;
606 if ($case['case_status_id'] == CRM_Case_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
607 $casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
609 $casesList[$key]['case_type'] = $caseTypeTitles[$case['case_type_id']] ??
NULL;
610 $casesList[$key]['case_role'] = CRM_Utils_Array
::value('case_role', $case, '---');
611 $casesList[$key]['manager'] = self
::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
613 $casesList[$key]['date'] = $activityTypeLabels[$case['activity_type_id']] ??
NULL;
614 if ($actId = CRM_Utils_Array
::value('activity_id', $case)) {
615 if (self
::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
616 if ($type == 'recent') {
617 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
618 CRM_Utils_System
::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
620 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
624 $status = CRM_Utils_Date
::overdue($case['activity_date_time']) ?
'status-overdue' : 'status-scheduled';
625 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
627 CRM_Utils_System
::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
629 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
633 if (isset($case['activity_type_id']) && self
::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
634 $casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil" aria-hidden="true"></i></a>',
635 CRM_Utils_System
::url('civicrm/case/activity', ['reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId]),
640 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date
::customFormat($case['activity_date_time']);
641 $casesList[$key]['links'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
643 'id' => $case['case_id'],
644 'cid' => $case['contact_id'],
649 'case.actions.primary',
659 * Get the summary of cases counts by type and status.
661 * @param bool $allCases
665 public static function getCasesSummary($allCases = TRUE) {
668 //validate access for civicase.
669 if (!self
::accessCiviCase()) {
673 $userID = CRM_Core_Session
::getLoggedInContactID();
675 //validate access for all cases.
676 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
680 $caseTypes = CRM_Case_PseudoConstant
::caseType();
681 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
682 $caseTypes = array_flip($caseTypes);
684 // get statuses as headers for the table
685 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
686 foreach ($caseStatuses as $key => $name) {
687 $caseSummary['headers'][$key]['status'] = $name;
688 $caseSummary['headers'][$key]['url'] = $url . $key;
691 // build rows with actual data
693 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClauseA = $myCaseWhereClauseB = '';
699 $myGroupByClauseB = ' GROUP BY civicrm_case.id';
704 $myCaseWhereClauseA = " AND case_relationship.contact_id_a = {$userID} AND case_relationship.is_active ";
705 $myGroupByClauseA = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_a)";
706 $myCaseWhereClauseB = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
707 $myGroupByClauseB = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_b)";
709 $myGroupByClauseB .= ", case_status.label, status_id, case_type_id, civicrm_case.id";
710 $myGroupByClauseA = $myGroupByClauseB;
711 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
713 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
714 case_type_id, case_relationship.contact_id_b as case_contact
716 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
717 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
718 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
719 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
720 AND option_group_case_status.id = case_status.option_group_id )
721 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
722 AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
723 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
724 {$myCaseWhereClauseB} {$myGroupByClauseB}
726 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
727 case_type_id, case_relationship.contact_id_a as case_contact
729 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
730 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
731 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
732 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
733 AND option_group_case_status.id = case_status.option_group_id )
734 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
735 AND case_relationship.contact_id_a = {$userID})
736 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
737 {$myCaseWhereClauseA} {$myGroupByClauseA}";
739 $res = CRM_Core_DAO
::executeQuery($query);
740 while ($res->fetch()) {
741 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
742 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
745 $rows[$res->case_type
][$res->case_status
] = [
747 'url' => CRM_Utils_System
::url('civicrm/case/search',
748 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
753 $caseSummary['rows'] = array_merge($caseTypes, $rows);
761 * @param int $contactID
765 * @param int $relationshipID
766 * @param bool $activeOnly
769 * case role / relationships
772 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
774 SELECT rel.id as civicrm_relationship_id,
775 con.sort_name as sort_name,
776 civicrm_email.email as email,
777 civicrm_phone.phone as phone,
778 con.id as civicrm_contact_id,
779 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
780 civicrm_relationship_type.id as relation_type,
781 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
782 FROM civicrm_relationship rel
783 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
784 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))
785 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
786 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
787 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
788 AND con.is_deleted = 0';
791 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
795 1 => [$contactID, 'Positive'],
796 2 => [$caseID, 'Positive'],
799 if ($relationshipID) {
800 $query .= ' AND rel.id = %3 ';
801 $params[3] = [$relationshipID, 'Integer'];
803 $dao = CRM_Core_DAO
::executeQuery($query, $params);
806 while ($dao->fetch()) {
807 $rid = $dao->civicrm_relationship_id
;
808 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
809 $values[$rid]['relation'] = $dao->relation
;
810 $values[$rid]['name'] = $dao->sort_name
;
811 $values[$rid]['email'] = $dao->email
;
812 $values[$rid]['phone'] = $dao->phone
;
813 $values[$rid]['relation_type'] = $dao->relation_type
;
814 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
815 $values[$rid]['client_id'] = $contactID;
816 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
823 * Get Case Activities.
827 * @param array $params
829 * @param int $contactID
832 * @param null $context
834 * @param null $type (deprecated)
837 * Array of case activities
840 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
841 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
842 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
843 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
844 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
846 // CRM-5081 - formatting the dates to omit seconds.
847 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
849 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
851 ca.activity_type_id AS type,
852 ca.activity_type_id AS activity_type_id,
853 tcc.sort_name AS target_contact_name,
854 tcc.id AS target_contact_id,
855 scc.sort_name AS source_contact_name,
856 scc.id AS source_contact_id,
857 acc.sort_name AS assignee_contact_name,
858 acc.id AS assignee_contact_id,
860 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
861 ca.activity_date_time,
862 DATE_ADD(NOW(), INTERVAL 1 YEAR)
863 ), '%Y%m%d%H%i00') AS overdue_date,
864 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
865 ca.status_id AS status,
866 ca.subject AS subject,
867 ca.is_deleted AS deleted,
868 ca.priority_id AS priority,
870 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
873 FROM civicrm_case_activity cca
874 INNER JOIN civicrm_activity ca
875 ON ca.id = cca.activity_id
876 INNER JOIN civicrm_activity_contact cas
877 ON cas.activity_id = ca.id
878 AND cas.record_type_id = {$sourceID}
879 INNER JOIN civicrm_contact scc
880 ON scc.id = cas.contact_id
881 LEFT JOIN civicrm_activity_contact caa
882 ON caa.activity_id = ca.id
883 AND caa.record_type_id = {$assigneeID}
884 LEFT JOIN civicrm_contact acc
885 ON acc.id = caa.contact_id
886 LEFT JOIN civicrm_activity_contact cat
887 ON cat.activity_id = ca.id
888 AND cat.record_type_id = {$targetID}
889 LEFT JOIN civicrm_contact tcc
890 ON tcc.id = cat.contact_id
891 INNER JOIN civicrm_option_group cog
892 ON cog.name = 'activity_type'
893 INNER JOIN civicrm_option_value cov
894 ON cov.option_group_id = cog.id
895 AND cov.value = ca.activity_type_id
896 AND cov.is_active = 1
897 LEFT JOIN civicrm_entity_file ef
898 ON ef.entity_table = 'civicrm_activity'
899 AND ef.entity_id = ca.id
900 LEFT OUTER JOIN civicrm_option_group og
901 ON og.name = 'activity_status'
902 LEFT OUTER JOIN civicrm_option_value ov
903 ON ov.option_group_id=og.id
904 AND ov.name = 'Scheduled'";
907 WHERE cca.case_id= %1
908 AND ca.is_current_revision = 1';
910 if (!empty($params['source_contact_id'])) {
912 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
915 if (!empty($params['status_id'])) {
917 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
920 if (!empty($params['activity_deleted'])) {
922 AND ca.is_deleted = 1";
926 AND ca.is_deleted = 0";
929 if (!empty($params['activity_type_id'])) {
931 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
934 if (!empty($params['activity_date_low'])) {
935 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
937 if (!empty($fromActivityDate)) {
939 AND ca.activity_date_time >= '{$fromActivityDate}'";
942 if (!empty($params['activity_date_high'])) {
943 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
944 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
946 if (!empty($toActivityDate)) {
948 AND ca.activity_date_time <= '{$toActivityDate}'";
952 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
954 $sortBy = $params['sortBy'] ??
NULL;
956 // CRM-5081 - added id to act like creation date
958 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
961 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
962 $orderBy = " ORDER BY $sortBy ";
965 $page = $params['page'] ??
NULL;
966 $rp = $params['rp'] ??
NULL;
974 $start = (($page - 1) * $rp);
975 $limit = " LIMIT $start, $rp";
977 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
978 $queryParams = [1 => [$caseID, 'Integer']];
980 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
981 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
983 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
985 $compStatusValues = array_keys(
986 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
987 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
991 $userID = CRM_Core_Session
::getLoggedInContactID();
994 $caseActivities = [];
996 while ($dao->fetch()) {
997 $caseActivityId = $dao->id
;
999 //Do we have permission to access given case activity record.
1000 if (!self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID)) {
1004 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1005 //Add classes to the row, via DataTables syntax
1006 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1008 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1009 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1012 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1013 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1016 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1020 if (!empty($dao->priority
)) {
1021 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1022 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1024 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1025 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1029 //Add data to the row for inline editing, via DataTable syntax
1030 $caseActivities[$caseActivityId]['DT_RowAttr'] = [];
1031 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1032 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1034 //Activity Date and Time
1035 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1038 $caseActivities[$caseActivityId]['subject'] = $dao->subject
;
1041 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1042 . $activityTypes[$dao->type
]['label'];
1044 // Activity Target (With Contact) (There can be more than one)
1045 $targetContact = self
::formatContactLink($dao->target_contact_id
, $dao->target_contact_name
);
1046 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1047 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1050 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1051 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1055 // Activity Source Contact (Reporter) (There can only be one)
1056 $sourceContact = self
::formatContactLink($dao->source_contact_id
, $dao->source_contact_name
);
1057 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1059 // Activity Assignee (There can be more than one)
1060 $assigneeContact = self
::formatContactLink($dao->assignee_contact_id
, $dao->assignee_contact_name
);
1061 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1062 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1065 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1066 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1070 // Activity Status Label for Case activities list
1072 if ($dao->deleted
) {
1073 $deleted = '<br /> ' . ts('(deleted)');
1075 $caseActivities[$caseActivityId]['status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status
) . $deleted;
1076 // if there are file attachments we will return how many
1077 if (!empty($dao->attachment_ids
)) {
1078 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1079 $caseActivity['no_attachments'] = count($attachmentIDs);
1082 $caseActivities[$caseActivityId]['links']
1083 = CRM_Case_Selector_Search
::addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao);
1086 $caseActivitiesDT = [];
1087 $caseActivitiesDT['data'] = array_values($caseActivities);
1088 $caseActivitiesDT['recordsTotal'] = $caseCount;
1089 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1091 return $caseActivitiesDT;
1095 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1098 * @param $contactName
1102 private static function formatContactLink($contactId, $contactName) {
1103 if (empty($contactId)) {
1107 $hasViewContact = CRM_Contact_BAO_Contact_Permission
::allow($contactId);
1109 if ($hasViewContact) {
1110 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1111 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1114 return $contactName;
1119 * Get Case Related Contacts.
1121 * @param int $caseID
1123 * @param bool $includeDetails
1124 * If true include details of contacts.
1127 * array of return properties
1130 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1132 if ($includeDetails) {
1133 $caseInfo = civicrm_api3('Case', 'getsingle', [
1135 // 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
1136 'return' => ['case_type_id', 'case_type_id.name', 'case_type_id.definition', 'contact_id'],
1138 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1139 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1144 $caseClientCondition = !empty($caseInfo['client_id']) ?
"AND cc.id NOT IN (%2)" : '';
1146 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
1147 FROM civicrm_relationship cr
1148 JOIN civicrm_relationship_type crt
1149 ON crt.id = cr.relationship_type_id
1150 JOIN civicrm_contact cc
1151 ON cc.id = cr.contact_id_a
1152 AND cc.is_deleted <> 1
1153 LEFT JOIN civicrm_email ce
1154 ON ce.contact_id = cc.id
1155 AND ce.is_primary= 1
1156 LEFT JOIN civicrm_phone cp
1157 ON cp.contact_id = cc.id
1158 AND cp.is_primary= 1
1159 WHERE cr.case_id = %1
1161 {$caseClientCondition}
1163 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
1164 FROM civicrm_relationship cr
1165 JOIN civicrm_relationship_type crt
1166 ON crt.id = cr.relationship_type_id
1167 JOIN civicrm_contact cc
1168 ON cc.id = cr.contact_id_b
1169 AND cc.is_deleted <> 1
1170 LEFT JOIN civicrm_email ce
1171 ON ce.contact_id = cc.id
1172 AND ce.is_primary= 1
1173 LEFT JOIN civicrm_phone cp
1174 ON cp.contact_id = cc.id
1175 AND cp.is_primary= 1
1176 WHERE cr.case_id = %1
1178 {$caseClientCondition}
1182 1 => [$caseID, 'Integer'],
1185 if ($caseClientCondition) {
1186 $params[2] = [implode(',', $caseInfo['client_id']), 'CommaSeparatedIntegers'];
1188 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1190 while ($dao->fetch()) {
1191 if (!$includeDetails) {
1192 $values[$dao->id
] = 1;
1196 'contact_id' => $dao->id
,
1197 'display_name' => $dao->name
,
1198 'sort_name' => $dao->sort_name
,
1199 'relationship_type_id' => $dao->relationship_type_id
,
1200 'role' => $dao->role
,
1201 'email' => $dao->email
,
1202 'phone' => $dao->phone
,
1204 // Add more info about the role (creator, manager)
1205 // The XML historically has the reverse direction, so look up reverse.
1206 $role = $caseRoles[$dao->role_name_reverse
] ??
NULL;
1208 unset($role['name']);
1211 $values[] = $details;
1219 * Send e-mail copy of activity
1221 * @param int $clientId
1222 * @param int $activityId
1224 * @param array $contacts
1225 * Array of related contact.
1227 * @param null $attachments
1228 * @param int $caseId
1230 * @return bool |array
1232 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1237 $tplParams = $activityInfo = [];
1238 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1239 // If it's a case activity
1241 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1242 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1243 $anyActivity = TRUE;
1246 $anyActivity = FALSE;
1248 $tplParams['isCaseActivity'] = 1;
1249 $tplParams['client_id'] = $clientId;
1252 $anyActivity = TRUE;
1255 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1256 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1258 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1260 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1262 $activityInfo['fields'][] = ['label' => 'Case ID', 'type' => 'String', 'value' => $caseId];
1264 $tplParams['activityTypeName'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeId);
1265 $tplParams['activity'] = $activityInfo;
1266 foreach ($tplParams['activity']['fields'] as $k => $val) {
1267 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1268 $activitySubject = $val['value'];
1273 // CRM-8926 If user is not logged in, use the activity creator as userID
1274 if (!($userID = CRM_Core_Session
::getLoggedInContactID())) {
1275 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1278 //also create activities simultaneously of this copy.
1279 $activityParams = [];
1281 $activityParams['source_record_id'] = $activityId;
1282 $activityParams['source_contact_id'] = $userID;
1283 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1284 $activityParams['activity_date_time'] = date('YmdHis');
1285 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1286 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1287 $activityParams['case_id'] = $caseId;
1288 $activityParams['is_auto'] = 0;
1289 $activityParams['target_id'] = $clientId;
1291 $tplParams['activitySubject'] = $activitySubject;
1293 // if it’s a case activity, add hashed id to the template (CRM-5916)
1295 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1299 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1300 $receiptFrom = self
::getReceiptFrom($activityId);
1302 $recordedActivityParams = [];
1304 foreach ($contacts as $mail => $info) {
1305 $tplParams['contact'] = $info;
1306 self
::buildPermissionLinks($tplParams, $activityParams);
1308 $displayName = $info['display_name'] ??
NULL;
1310 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1312 'groupName' => 'msg_tpl_workflow_case',
1313 'valueName' => 'case_activity',
1314 'contactId' => $info['contact_id'] ??
NULL,
1315 'tplParams' => $tplParams,
1316 'from' => $receiptFrom,
1317 'toName' => $displayName,
1319 'attachments' => $attachments,
1323 $activityParams['subject'] = ts('%1 - copy sent to %2', [1 => $activitySubject, 2 => $displayName]);
1324 $activityParams['details'] = $message;
1326 if (!empty($result[$info['contact_id']])) {
1328 * Really only need to record one activity with all the targets combined.
1329 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1330 * but it's always the same content at the moment.
1332 if (empty($recordedActivityParams)) {
1333 $recordedActivityParams = $activityParams;
1336 $recordedActivityParams['subject'] .= "; $displayName";
1338 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1341 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1345 if (!empty($recordedActivityParams)) {
1346 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1348 //create case_activity record if its case activity.
1351 'activity_id' => $activity->id
,
1352 'case_id' => $caseId,
1354 self
::processCaseActivity($caseParams);
1362 * Retrieve count of activities having a particular type, and
1363 * associated with a particular case.
1365 * @param int $caseId
1367 * @param int $activityTypeId
1368 * ID of the activity type.
1372 public static function getCaseActivityCount($caseId, $activityTypeId) {
1374 1 => [$caseId, 'Integer'],
1375 2 => [$activityTypeId, 'Integer'],
1377 $query = "SELECT count(ca.id) as countact
1378 FROM civicrm_activity ca
1379 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1380 WHERE ca.activity_type_id = %2
1381 AND cca.case_id = %1
1382 AND ca.is_deleted = 0";
1384 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1385 if ($dao->fetch()) {
1386 return $dao->countact
;
1393 * Retrieve the scheduled activity type and date.
1395 * @param array $cases
1396 * Array of contact and case id.
1398 * @param string $type
1401 * Array of scheduled activity type and date
1405 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1406 $userID = CRM_Core_Session
::getLoggedInContactID();
1408 $caseID = implode(',', $cases['case_id']);
1409 $contactID = implode(',', $cases['contact_id']);
1411 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1412 AND civicrm_case.id IN( {$caseID})
1413 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1415 $query = self
::getCaseActivityQuery($type, $userID, $condition);
1416 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
1418 $res = CRM_Core_DAO
::executeQuery($query);
1421 while ($res->fetch()) {
1422 if ($type == 'upcoming') {
1423 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1424 $activityInfo[$res->case_id
]['type'] = $activityTypes[$res->activity_type_id
] ??
NULL;
1427 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1428 $activityInfo[$res->case_id
]['type'] = $activityTypes[$res->activity_type_id
] ??
NULL;
1432 return $activityInfo;
1436 * Combine all the exportable fields from the lower levels object.
1439 * array of exportable Fields
1441 public static function &exportableFields() {
1442 if (!self
::$_exportableFields) {
1443 if (!self
::$_exportableFields) {
1444 self
::$_exportableFields = [];
1447 $fields = CRM_Case_DAO_Case
::export();
1448 $fields['case_role'] = ['title' => ts('Role in Case')];
1449 $fields['case_type'] = [
1450 'title' => ts('Case Type'),
1451 'name' => 'case_type',
1453 $fields['case_status'] = [
1454 'title' => ts('Case Status'),
1455 'name' => 'case_status',
1458 // add custom data for cases
1459 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1461 self
::$_exportableFields = $fields;
1463 return self
::$_exportableFields;
1467 * Restore the record that are associated with this case.
1469 * @param int $caseId
1470 * Id of the case to restore.
1474 public static function restoreCase($caseId) {
1475 //restore activities
1476 $activities = self
::getCaseActivityDates($caseId);
1478 foreach ($activities as $value) {
1479 CRM_Activity_BAO_Activity
::restoreActivity($value);
1483 $case = new CRM_Case_DAO_Case();
1484 $case->id
= $caseId;
1485 $case->is_deleted
= 0;
1488 //CRM-7364, enable relationships
1489 self
::enableDisableCaseRelationships($caseId, TRUE);
1496 * @param null $showLinks
1497 * @param bool $returnOnlyCount
1498 * @param int $offset
1499 * @param int $rowCount
1503 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1504 $globalContacts = [];
1506 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1507 $settings = $settingsProcessor->run();
1508 if (!empty($settings)) {
1509 $groupInfo['name'] = $settings['groupname'];
1510 if ($groupInfo['name']) {
1511 $searchParams = ['name' => $groupInfo['name']];
1513 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1515 $groupInfo['id'] = $results['id'];
1516 $groupInfo['title'] = $results['title'];
1517 $params = [['group', '=', $groupInfo['id'], 0, 0]];
1518 $return = ['contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1];
1519 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount, FALSE);
1521 if ($returnOnlyCount) {
1522 return $globalContacts;
1526 foreach ($globalContacts as $idx => $contact) {
1527 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1533 return $globalContacts;
1537 * Convenience function to get both case contacts and global in one array.
1539 * @param int $caseId
1543 public static function getRelatedAndGlobalContacts($caseId) {
1544 $relatedContacts = self
::getRelatedContacts($caseId);
1547 $globalContacts = self
::getGlobalContacts($groupInfo);
1549 //unset values which are not required.
1550 foreach ($globalContacts as $k => & $v) {
1551 unset($v['email_id']);
1552 unset($v['group_contact_id']);
1553 unset($v['status']);
1555 $v['role'] = $groupInfo['title'];
1557 //include multiple listings for the same contact/different roles.
1558 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1559 return $relatedGlobalContacts;
1563 * Get Case ActivitiesDueDates with given criteria.
1565 * @param int $caseID
1567 * @param array $criteriaParams
1569 * @param bool $latestDate
1570 * If set newest or oldest date is selected.
1573 * case activities due dates
1576 public static function getCaseActivityDates($caseID, $criteriaParams = [], $latestDate = FALSE) {
1578 $selectDate = " ca.activity_date_time";
1579 $where = $groupBy = ' ';
1586 if (!empty($criteriaParams['activity_type_id'])) {
1587 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1588 $where .= " AND ca.is_current_revision = 1";
1589 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1592 if (!empty($criteriaParams['newest'])) {
1593 $selectDate = " max(ca.activity_date_time) ";
1596 $selectDate = " min(ca.activity_date_time) ";
1600 $query = "SELECT ca.id, {$selectDate} as activity_date
1601 FROM civicrm_activity ca
1602 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1603 WHERE cc.id = %1 {$where} {$groupBy}";
1605 $params = [1 => [$caseID, 'Integer']];
1606 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1608 while ($dao->fetch()) {
1609 $values[$dao->id
]['id'] = $dao->id
;
1610 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1616 * Create activities when Case or Other roles assigned/modified/deleted.
1618 * @param int $caseId
1619 * @param int $relationshipId
1621 * @param int $relContactId
1622 * Case role assignee contactId.
1623 * @param int $contactId
1625 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1626 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1631 if (is_array($relationshipId)) {
1632 $relationshipId = implode(',', $relationshipId);
1633 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1636 $relationshipClause = " civicrm_relationship.id = %1";
1637 $queryParam[1] = [$relationshipId, 'Positive'];
1641 SELECT cc.display_name as clientName,
1642 cca.display_name as assigneeContactName,
1643 civicrm_relationship.case_id as caseId,
1644 civicrm_relationship_type.label_a_b as relation_a_b,
1645 civicrm_relationship_type.label_b_a as relation_b_a,
1646 civicrm_relationship.contact_id_b as rel_contact_id,
1647 civicrm_relationship.contact_id_a as assign_contact_id
1648 FROM civicrm_relationship_type, civicrm_relationship
1649 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1650 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1651 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1653 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1655 while ($dao->fetch()) {
1656 // The assignee is not the client.
1657 if ($dao->rel_contact_id
!= $contactId) {
1658 $caseRelationship = $dao->relation_a_b
;
1659 $assigneContactName = $dao->clientName
;
1660 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1663 $caseRelationship = $dao->relation_b_a
;
1664 $assigneContactName = $dao->assigneeContactName
;
1665 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1669 $session = CRM_Core_Session
::singleton();
1671 'source_contact_id' => $session->get('userID'),
1672 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1673 'activity_date_time' => date('YmdHis'),
1674 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1677 //if $relContactId is passed, role is added or modified.
1678 if (!empty($relContactId)) {
1679 $activityParams['assignee_contact_id'] = $assigneContactIds;
1680 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1683 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1686 $activityParams['activity_type_id'] = $activityTypeID;
1688 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1690 //create case_activity record.
1692 'activity_id' => $activity->id
,
1693 'case_id' => $caseId,
1696 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1701 * contact which is assigned a case role of case manager.
1703 * @param int $caseType
1705 * @param int $caseId
1709 * html hyperlink of manager contact view page
1712 public static function getCaseManagerContact($caseType, $caseId) {
1713 if (!$caseType ||
!$caseId) {
1717 $caseManagerName = '---';
1718 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1720 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1722 if (!empty($managerRoleId)) {
1723 if (substr($managerRoleId, -4) == '_a_b') {
1724 $managerRoleQuery = "
1725 SELECT civicrm_contact.id as casemanager_id,
1726 civicrm_contact.sort_name as casemanager
1727 FROM civicrm_contact
1728 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
1729 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1730 WHERE civicrm_case.id = %2 AND is_active = 1";
1732 if (substr($managerRoleId, -4) == '_b_a') {
1733 $managerRoleQuery = "
1734 SELECT civicrm_contact.id as casemanager_id,
1735 civicrm_contact.sort_name as casemanager
1736 FROM civicrm_contact
1737 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
1738 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1739 WHERE civicrm_case.id = %2 AND is_active = 1";
1742 $managerRoleParams = [
1743 1 => [substr($managerRoleId, 0, -4), 'Integer'],
1744 2 => [$caseId, 'Integer'],
1747 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1748 if ($dao->fetch()) {
1749 $caseManagerName = sprintf('<a href="%s">%s</a>',
1750 CRM_Utils_System
::url('civicrm/contact/view', ['cid' => $dao->casemanager_id
]),
1756 return $caseManagerName;
1760 * @param int $contactId
1761 * @param bool $excludeDeleted
1765 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1766 $params = ['check_permissions' => TRUE];
1767 if ($excludeDeleted) {
1768 $params['is_deleted'] = 0;
1771 $params['contact_id'] = $contactId;
1774 return civicrm_api3('Case', 'getcount', $params);
1776 catch (CiviCRM_API3_Exception
$e) {
1777 // Lack of permissions will throw an exception
1783 * Retrieve related case ids for given case.
1785 * @param int $caseId
1786 * @param bool $excludeDeleted
1787 * Do not include deleted cases.
1791 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1792 //FIXME : do check for permissions.
1798 $linkActType = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Link Cases');
1799 if (!$linkActType) {
1803 $whereClause = "mainCase.id = %2";
1804 if ($excludeDeleted) {
1805 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1809 SELECT relCaseAct.case_id
1810 FROM civicrm_case mainCase
1811 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1812 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1813 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1814 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1815 WHERE $whereClause";
1817 $dao = CRM_Core_DAO
::executeQuery($query, [
1818 1 => [$linkActType, 'Integer'],
1819 2 => [$caseId, 'Integer'],
1821 $relatedCaseIds = [];
1822 while ($dao->fetch()) {
1823 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1826 return array_values($relatedCaseIds);
1830 * Retrieve related case details for given case.
1832 * @param int $caseId
1833 * @param bool $excludeDeleted
1834 * Do not include deleted cases.
1838 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1839 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1842 if (!$relatedCaseIds) {
1846 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1847 if ($excludeDeleted) {
1848 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1851 //filter for permissioned cases.
1853 $doFilterCases = FALSE;
1854 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1855 $doFilterCases = TRUE;
1856 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
1859 //2. fetch the details of related cases.
1861 SELECT relCase.id as id,
1862 civicrm_case_type.title as case_type,
1863 client.display_name as client_name,
1864 client.id as client_id,
1866 FROM civicrm_case relCase
1867 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1868 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1869 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1870 WHERE {$whereClause}";
1872 $dao = CRM_Core_DAO
::executeQuery($query);
1873 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
1874 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1875 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
1877 while ($dao->fetch()) {
1879 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
1880 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
1881 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
1882 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
1884 $clientView = $dao->client_name
;
1885 if ($hasViewContact) {
1886 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
1889 $relatedCases[$dao->id
] = [
1890 'case_id' => $dao->id
,
1891 'case_type' => $dao->case_type
,
1892 'client_name' => $clientView,
1893 'status_id' => $dao->status_id
,
1894 'case_status' => $statuses[$dao->status_id
],
1895 'links' => $caseView,
1899 return $relatedCases;
1903 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
1905 * @param int $mainContactId
1906 * @param int $otherContactId
1908 * @see CRM_Dedupe_Merger::cpTables()
1910 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
1913 public static function mergeContacts($mainContactId, $otherContactId) {
1914 self
::mergeCases($mainContactId, NULL, $otherContactId);
1918 * Function perform two task.
1919 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
1920 * 2. Merge two cases of same contact - follow CRM-5598 rules.
1922 * @param int $mainContactId
1923 * Contact id of main contact record.
1924 * @param int $mainCaseId
1925 * Case id of main case record.
1926 * @param int $otherContactId
1927 * Contact id of record which is going to merge.
1928 * @param int $otherCaseId
1929 * Case id of record which is going to merge.
1931 * @param bool $changeClient
1934 * @throws \CRM_Core_Exception
1936 public static function mergeCases(
1937 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
1938 $otherCaseId = NULL, $changeClient = FALSE) {
1939 $moveToTrash = TRUE;
1941 $duplicateContacts = FALSE;
1942 if ($mainContactId && $otherContactId &&
1943 $mainContactId != $otherContactId
1945 $duplicateContacts = TRUE;
1948 $duplicateCases = FALSE;
1949 if ($mainCaseId && $otherCaseId &&
1950 $mainCaseId != $otherCaseId
1952 $duplicateCases = TRUE;
1956 if (!$duplicateContacts && !$duplicateCases) {
1957 return $mainCaseIds;
1960 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
1961 $completedActivityStatus = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1962 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1963 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1964 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1965 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1967 $processCaseIds = [$otherCaseId];
1968 if ($duplicateContacts && !$duplicateCases) {
1969 if ($changeClient) {
1970 $processCaseIds = [$mainCaseId];
1973 //get all case ids for other contact.
1974 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
1976 if (!is_array($processCaseIds)) {
1981 $session = CRM_Core_Session
::singleton();
1982 $currentUserId = $session->get('userID');
1984 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
1986 // copy all cases and connect to main contact id.
1987 foreach ($processCaseIds as $otherCaseId) {
1988 if ($duplicateContacts) {
1989 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', ['id' => $otherCaseId]);
1990 $mainCaseId = $mainCase->id
;
1995 $mainCaseIds[] = $mainCaseId;
1996 //insert record for case contact.
1997 $otherCaseContact = new CRM_Case_DAO_CaseContact();
1998 $otherCaseContact->case_id
= $otherCaseId;
1999 $otherCaseContact->find();
2000 while ($otherCaseContact->fetch()) {
2001 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2002 $mainCaseContact->case_id
= $mainCaseId;
2003 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2004 if ($mainCaseContact->contact_id
== $otherContactId) {
2005 $mainCaseContact->contact_id
= $mainContactId;
2007 //avoid duplicate object.
2008 if (!$mainCaseContact->find(TRUE)) {
2009 $mainCaseContact->save();
2013 elseif (!$otherContactId) {
2014 $otherContactId = $mainContactId;
2017 if (!$mainCaseId ||
!$otherCaseId ||
2018 !$mainContactId ||
!$otherContactId
2023 // get all activities for other case.
2024 $otherCaseActivities = [];
2025 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2027 //for duplicate cases do not process singleton activities.
2028 $otherActivityIds = $singletonActivityIds = [];
2029 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2030 $otherActId = $otherIds['activity_id'] ??
NULL;
2031 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2034 $otherActivityIds[] = $otherActId;
2036 if ($duplicateCases) {
2037 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2040 FROM civicrm_activity
2041 WHERE activity_type_id = $openCaseType
2042 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2043 $dao = CRM_Core_DAO
::executeQuery($sql);
2044 while ($dao->fetch()) {
2045 $singletonActivityIds[] = $dao->id
;
2050 // migrate all activities and connect to main contact.
2051 $copiedActivityIds = $activityMappingIds = [];
2052 sort($otherActivityIds);
2053 foreach ($otherActivityIds as $otherActivityId) {
2055 //for duplicate cases -
2056 //do not migrate singleton activities.
2057 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2061 //migrate activity record.
2062 $otherActivity = new CRM_Activity_DAO_Activity();
2063 $otherActivity->id
= $otherActivityId;
2064 if (!$otherActivity->find(TRUE)) {
2069 $mainActivity = new CRM_Activity_DAO_Activity();
2070 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2071 $mainActivity->copyValues($mainActVals);
2072 $mainActivity->id
= NULL;
2073 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2074 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2078 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2082 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2085 $mainActivity->save();
2086 $mainActivityId = $mainActivity->id
;
2087 if (!$mainActivityId) {
2091 $activityMappingIds[$otherActivityId] = $mainActivityId;
2092 // insert log of all activities
2093 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2095 $copiedActivityIds[] = $otherActivityId;
2097 //create case activity record.
2098 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2099 $mainCaseActivity->case_id
= $mainCaseId;
2100 $mainCaseActivity->activity_id
= $mainActivityId;
2101 $mainCaseActivity->save();
2103 //migrate source activity.
2104 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2105 $otherSourceActivity->activity_id
= $otherActivityId;
2106 $otherSourceActivity->record_type_id
= $sourceID;
2107 $otherSourceActivity->find();
2108 while ($otherSourceActivity->fetch()) {
2109 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2110 $mainActivitySource->record_type_id
= $sourceID;
2111 $mainActivitySource->activity_id
= $mainActivityId;
2112 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2113 if ($mainActivitySource->contact_id
== $otherContactId) {
2114 $mainActivitySource->contact_id
= $mainContactId;
2116 //avoid duplicate object.
2117 if (!$mainActivitySource->find(TRUE)) {
2118 $mainActivitySource->save();
2122 //migrate target activities.
2123 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2124 $otherTargetActivity->activity_id
= $otherActivityId;
2125 $otherTargetActivity->record_type_id
= $targetID;
2126 $otherTargetActivity->find();
2127 while ($otherTargetActivity->fetch()) {
2128 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2129 $mainActivityTarget->record_type_id
= $targetID;
2130 $mainActivityTarget->activity_id
= $mainActivityId;
2131 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2132 if ($mainActivityTarget->contact_id
== $otherContactId) {
2133 $mainActivityTarget->contact_id
= $mainContactId;
2135 //avoid duplicate object.
2136 if (!$mainActivityTarget->find(TRUE)) {
2137 $mainActivityTarget->save();
2141 //migrate assignee activities.
2142 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2143 $otherAssigneeActivity->activity_id
= $otherActivityId;
2144 $otherAssigneeActivity->record_type_id
= $assigneeID;
2145 $otherAssigneeActivity->find();
2146 while ($otherAssigneeActivity->fetch()) {
2147 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2148 $mainAssigneeActivity->activity_id
= $mainActivityId;
2149 $mainAssigneeActivity->record_type_id
= $assigneeID;
2150 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2151 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2152 $mainAssigneeActivity->contact_id
= $mainContactId;
2154 //avoid duplicate object.
2155 if (!$mainAssigneeActivity->find(TRUE)) {
2156 $mainAssigneeActivity->save();
2160 // copy custom fields and attachments
2162 'activityID' => $otherActivityId,
2163 'mainActivityId' => $mainActivityId,
2165 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2168 //copy case relationship.
2169 if ($duplicateContacts) {
2170 //migrate relationship records.
2171 $otherRelationship = new CRM_Contact_DAO_Relationship();
2172 $otherRelationship->case_id
= $otherCaseId;
2173 $otherRelationship->find();
2174 $otherRelationshipIds = [];
2175 while ($otherRelationship->fetch()) {
2177 $updateOtherRel = FALSE;
2178 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2180 $mainRelationship = new CRM_Contact_DAO_Relationship();
2181 $mainRelationship->copyValues($otherRelVals);
2182 $mainRelationship->id
= NULL;
2183 $mainRelationship->case_id
= $mainCaseId;
2184 if ($mainRelationship->contact_id_a
== $otherContactId) {
2185 $updateOtherRel = TRUE;
2186 $mainRelationship->contact_id_a
= $mainContactId;
2189 //case creator change only when we merge user contact.
2190 if ($mainRelationship->contact_id_b
== $otherContactId) {
2191 //do not change creator for change client.
2192 if (!$changeClient) {
2193 $updateOtherRel = TRUE;
2194 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2197 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2198 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2200 //avoid duplicate object.
2201 if (!$mainRelationship->find(TRUE)) {
2202 $mainRelationship->save();
2205 //get the other relationship ids to update end date.
2206 if ($updateOtherRel) {
2207 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2211 //update other relationships end dates
2212 if (!empty($otherRelationshipIds)) {
2213 $sql = 'UPDATE civicrm_relationship
2214 SET end_date = CURDATE()
2215 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2216 CRM_Core_DAO
::executeQuery($sql);
2220 //move other case to trash.
2221 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2226 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2227 if ($changeClient) {
2228 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2229 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2231 $mergeActType = array_search('Reassigned Case', $activityTypes);
2232 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2235 2 => $otherContactDisplayName,
2236 3 => $mainContactDisplayName,
2241 elseif ($duplicateContacts) {
2242 $mergeActType = array_search('Merge Case', $activityTypes);
2243 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2246 2 => $otherContactId,
2247 3 => $mainContactId,
2253 $mergeActType = array_search('Merge Case', $activityTypes);
2254 $mergeActSubject = ts("Case %1 merged into case %2", [1 => $otherCaseId, 2 => $mainCaseId]);
2255 if (!empty($copiedActivityIds)) {
2257 SELECT id, subject, activity_date_time, activity_type_id
2258 FROM civicrm_activity
2259 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2260 $dao = CRM_Core_DAO
::executeQuery($sql);
2261 while ($dao->fetch()) {
2262 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2263 if ($dao->subject
) {
2264 $mergeActSubjectDetails .= " :: {$dao->subject}";
2266 $mergeActSubjectDetails .= "<br />";
2271 // Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2273 'subject' => $mergeActSubject,
2274 'details' => $mergeActSubjectDetails,
2275 'status_id' => $completedActivityStatus,
2276 'activity_type_id' => $mergeActType,
2277 'source_contact_id' => $currentUserId,
2278 'activity_date_time' => date('YmdHis'),
2281 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2282 $mergeActivityId = $mergeActivity->id
;
2283 if (!$mergeActivityId) {
2287 //connect merge activity to case.
2289 'case_id' => $mainCaseId,
2290 'activity_id' => $mergeActivityId,
2293 self
::processCaseActivity($mergeCaseAct);
2296 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2298 return $mainCaseIds;
2302 * Validate contact permission for
2303 * edit/view on activity record and build links.
2305 * @param array $tplParams
2306 * Params to be sent to template for sending email.
2307 * @param array $activityParams
2308 * Info of the activity.
2310 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2311 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2312 'activity_type_id', 'id'
2315 if (!empty($tplParams['isCaseActivity'])) {
2316 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2317 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2320 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2321 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2324 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2325 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2329 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2330 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2333 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2334 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2340 * Validate contact permission for
2341 * given operation on activity record.
2343 * @param int $activityId
2344 * Activity record id.
2345 * @param string $operation
2347 * @param int $actTypeId
2349 * @param int $contactId
2350 * Contact id/if not pass consider logged in.
2351 * @param bool $checkComponent
2352 * Do we need to check component enabled.
2356 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2358 if (!$actTypeId && $activityId) {
2359 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2362 if (!$activityId ||
!$operation ||
!$actTypeId) {
2366 //do check for civicase component enabled.
2367 if ($checkComponent && !self
::enabled()) {
2371 //do check for cases.
2372 $caseActOperations = [
2379 if (in_array($operation, $caseActOperations)) {
2381 if (!isset($caseCount)) {
2383 $caseCount = civicrm_api3('Case', 'getcount', [
2384 'check_permissions' => TRUE,
2385 'status_id' => ['!=' => 'Closed'],
2387 'end_date' => ['IS NULL' => 1],
2390 catch (CiviCRM_API3_Exception
$e) {
2391 // Lack of permissions will throw an exception
2395 if ($operation == 'File On Case') {
2396 $allow = !empty($caseCount);
2399 $allow = ($caseCount > 1);
2403 $actionOperations = ['view', 'edit', 'delete'];
2404 if (in_array($operation, $actionOperations)) {
2406 //do cache when user has non/supper permission.
2407 static $allowOperations;
2409 if (!is_array($allowOperations) ||
2410 !array_key_exists($operation, $allowOperations)
2414 $session = CRM_Core_Session
::singleton();
2415 $contactId = $session->get('userID');
2418 //check for permissions.
2421 'access my cases and activities',
2422 'access all cases and activities',
2425 'access my cases and activities',
2426 'access all cases and activities',
2428 'delete' => ['delete activities'],
2431 //check for core permission.
2432 $hasPermissions = [];
2433 $checkPermissions = $permissions[$operation] ??
NULL;
2434 if (is_array($checkPermissions)) {
2435 foreach ($checkPermissions as $per) {
2436 if (CRM_Core_Permission
::check($per)) {
2437 $hasPermissions[$operation][] = $per;
2443 if (!empty($hasPermissions)) {
2444 //need to check activity object specific.
2445 if (in_array($operation, [
2450 //do we have supper permission.
2451 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2452 $allowOperations[$operation] = $allow = TRUE;
2455 //user has only access to my cases and activity.
2456 //here object specific permmions come in picture.
2458 //edit - contact must be source or assignee
2459 //view - contact must be source/assignee/target
2460 $isTarget = $isAssignee = $isSource = FALSE;
2461 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2462 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2463 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2464 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2466 $target = new CRM_Activity_DAO_ActivityContact();
2467 $target->record_type_id
= $targetID;
2468 $target->activity_id
= $activityId;
2469 $target->contact_id
= $contactId;
2470 if ($target->find(TRUE)) {
2474 $assignee = new CRM_Activity_DAO_ActivityContact();
2475 $assignee->activity_id
= $activityId;
2476 $assignee->record_type_id
= $assigneeID;
2477 $assignee->contact_id
= $contactId;
2478 if ($assignee->find(TRUE)) {
2482 $source = new CRM_Activity_DAO_ActivityContact();
2483 $source->activity_id
= $activityId;
2484 $source->record_type_id
= $sourceID;
2485 $source->contact_id
= $contactId;
2486 if ($source->find(TRUE)) {
2490 if ($operation == 'edit') {
2491 if ($isAssignee ||
$isSource) {
2495 if ($operation == 'view') {
2496 if ($isTarget ||
$isAssignee ||
$isSource) {
2502 elseif (is_array($hasPermissions[$operation])) {
2503 $allowOperations[$operation] = $allow = TRUE;
2507 //contact do not have permission.
2508 $allowOperations[$operation] = FALSE;
2513 //here contact might have supper/non permission.
2514 $allow = $allowOperations[$operation];
2518 //do further only when operation is granted.
2520 $actTypeName = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $actTypeId);
2522 //do not allow multiple copy / edit action.
2533 //do not allow to delete these activities, CRM-4543
2534 $doNotDeleteNames = ['Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date'];
2536 //allow edit operation.
2537 $allowEditNames = ['Open Case'];
2539 if (CRM_Activity_BAO_Activity
::checkEditInboundEmailsPermissions()) {
2540 $allowEditNames[] = 'Inbound Email';
2543 // do not allow File on Case
2547 'Change Case Status',
2548 'Change Case Start Date',
2555 if (in_array($actTypeName, $singletonNames)) {
2557 if ($operation == 'File On Case') {
2558 $allow = !in_array($actTypeName, $doNotFileNames);
2560 if (in_array($operation, $actionOperations)) {
2562 if ($operation == 'edit') {
2563 $allow = in_array($actTypeName, $allowEditNames);
2565 elseif ($operation == 'delete') {
2566 $allow = !in_array($actTypeName, $doNotDeleteNames);
2570 if ($allow && ($operation == 'delete') &&
2571 in_array($actTypeName, $doNotDeleteNames)
2576 if ($allow && ($operation == 'File On Case') &&
2577 in_array($actTypeName, $doNotFileNames)
2582 //check settings file for masking actions
2583 //on the basis the activity types
2584 //hide Edit link if activity type is NOT editable
2585 //(special case activities).CRM-5871
2586 if ($allow && in_array($operation, $actionOperations)) {
2587 static $actionFilter = [];
2588 if (!array_key_exists($operation, $actionFilter)) {
2589 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2590 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2592 if (array_key_exists($operation, $actionFilter[$operation]) &&
2593 in_array($actTypeId, $actionFilter[$operation][$operation])
2604 * Since we drop 'access CiviCase', allow access
2605 * if user has 'access my cases and activities'
2606 * or 'access all cases and activities'
2608 public static function accessCiviCase() {
2609 if (!self
::enabled()) {
2613 if (CRM_Core_Permission
::check('access my cases and activities') ||
2614 CRM_Core_Permission
::check('access all cases and activities')
2623 * Verify user has permission to access a case.
2625 * @param int $caseId
2626 * @param bool $denyClosed
2627 * Set TRUE if one wants closed cases to be treated as inaccessible.
2631 public static function accessCase($caseId, $denyClosed = TRUE) {
2632 if (!$caseId ||
!self
::enabled()) {
2636 $params = ['id' => $caseId, 'check_permissions' => TRUE];
2637 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2638 $params['status_id'] = ['!=' => 'Closed'];
2641 return (bool) civicrm_api3('Case', 'getcount', $params);
2643 catch (CiviCRM_API3_Exception
$e) {
2644 // Lack of permissions will throw an exception
2650 * Check whether activity is a case Activity.
2652 * @param int $activityID
2657 public static function isCaseActivity($activityID) {
2658 $isCaseActivity = FALSE;
2660 $params = [1 => [$activityID, 'Integer']];
2661 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2662 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2663 $isCaseActivity = TRUE;
2667 return $isCaseActivity;
2671 * Get all the case type ids currently in use.
2675 public static function getUsedCaseType() {
2676 static $caseTypeIds;
2678 if (!is_array($caseTypeIds)) {
2679 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2681 $dao = CRM_Core_DAO
::executeQuery($query);
2683 while ($dao->fetch()) {
2684 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2687 $caseTypeIds[] = $typeId[1];
2691 return $caseTypeIds;
2695 * Get all the case status ids currently in use.
2699 public static function getUsedCaseStatuses() {
2700 static $caseStatusIds;
2702 if (!is_array($caseStatusIds)) {
2703 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2705 $dao = CRM_Core_DAO
::executeQuery($query);
2706 $caseStatusIds = [];
2707 while ($dao->fetch()) {
2708 $caseStatusIds[] = $dao->status_id
;
2712 return $caseStatusIds;
2716 * Get all the encounter medium ids currently in use.
2720 public static function getUsedEncounterMediums() {
2723 if (!is_array($mediumIds)) {
2724 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2726 $dao = CRM_Core_DAO
::executeQuery($query);
2728 while ($dao->fetch()) {
2729 $mediumIds[] = $dao->medium_id
;
2737 * Check case configuration.
2739 * @param int $contactId
2743 public static function isCaseConfigured($contactId = NULL) {
2744 $configured = array_fill_keys(['configured', 'allowToAddNewCase', 'redirectToCaseAdmin'], FALSE);
2746 //lets check for case configured.
2747 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2748 $configured['configured'] = (bool) $allCasesCount;
2749 if (!$configured['configured']) {
2750 //do check for case type and case status.
2751 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2752 if (!empty($caseTypes)) {
2753 $configured['configured'] = TRUE;
2754 if (!$configured['configured']) {
2755 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2756 if (!empty($caseStatuses)) {
2757 $configured['configured'] = TRUE;
2762 if ($configured['configured']) {
2763 //do check for active case type and case status.
2764 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2765 if (!empty($caseTypes)) {
2766 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2767 if (!empty($caseStatuses)) {
2768 $configured['allowToAddNewCase'] = TRUE;
2772 //do we need to redirect user to case admin.
2773 if (!$configured['allowToAddNewCase'] && $contactId) {
2774 //check for current contact case count.
2775 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2776 //redirect user to case admin page.
2777 if (!$currentContatCasesCount) {
2778 $configured['redirectToCaseAdmin'] = TRUE;
2787 * Used during case component enablement and during ugprade.
2791 public static function createCaseViews() {
2792 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2793 $dao = new CRM_Core_DAO();
2795 $sql = self
::createCaseViewsQuery('upcoming');
2797 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2801 // Above error doesn't get caught?
2802 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2803 if (is_null($doublecheck)) {
2807 $sql = self
::createCaseViewsQuery('recent');
2809 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2813 // Above error doesn't get caught?
2814 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2815 if (is_null($doublecheck)) {
2823 * Helper function, also used by the upgrade in case of error
2825 * @param string $section
2829 public static function createCaseViewsQuery($section = 'upcoming') {
2831 $scheduled_id = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2834 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2835 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2836 FROM civicrm_case_activity ca
2837 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2839 (SELECT b.id FROM civicrm_case_activity bca
2840 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2841 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
2842 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
2843 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
2847 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
2848 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2849 FROM civicrm_case_activity ca
2850 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2852 (SELECT b.id FROM civicrm_case_activity bca
2853 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2854 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
2855 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
2856 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
2863 * Add/copy relationships, when new client is added for a case
2865 * @param int $caseId
2867 * @param int $contactId
2868 * Contact id / new client id.
2870 public static function addCaseRelationships($caseId, $contactId) {
2871 // get the case role / relationships for the case
2872 $caseRelationships = new CRM_Contact_DAO_Relationship();
2873 $caseRelationships->case_id
= $caseId;
2874 $caseRelationships->find();
2875 $relationshipTypes = [];
2877 // make sure we don't add duplicate relationships of same relationship type.
2878 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
2880 CRM_Core_DAO
::storeValues($caseRelationships, $values);
2882 // add relationship for new client.
2883 $newRelationship = new CRM_Contact_DAO_Relationship();
2884 $newRelationship->copyValues($values);
2885 $newRelationship->id
= NULL;
2886 $newRelationship->case_id
= $caseId;
2887 $newRelationship->contact_id_a
= $contactId;
2888 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
2889 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
2891 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
2892 if (!$newRelationship->find(TRUE)) {
2893 $newRelationship->save();
2896 // store relationship type of newly created relationship
2897 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
2902 * Get the list of clients for a case.
2904 * @param int $caseId
2907 * associated array with client ids
2909 public static function getCaseClients($caseId) {
2911 $caseContact = new CRM_Case_DAO_CaseContact();
2912 $caseContact->case_id
= $caseId;
2913 $caseContact->orderBy('id');
2914 $caseContact->find();
2916 while ($caseContact->fetch()) {
2917 $clients[] = $caseContact->contact_id
;
2924 * @param int $caseId
2925 * @param string $direction
2927 * @param int $relTypeId
2929 * @throws \CRM_Core_Exception
2930 * @throws \CiviCRM_API3_Exception
2932 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
2934 if ($direction !== 'a' && $direction !== 'b') {
2935 throw new CRM_Core_Exception('Invalid relationship direction');
2938 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
2939 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
2940 $dao = CRM_Core_DAO
::executeQuery($sql, [
2941 1 => [$caseId, 'Positive'],
2942 2 => [$cid, 'Positive'],
2943 3 => [$relTypeId, 'Positive'],
2945 while ($dao->fetch()) {
2946 civicrm_api3('relationship', 'create', [
2949 'end_date' => 'now',
2955 * Get options for a given case field.
2957 * @param string $fieldName
2958 * @param string $context
2959 * @param array $props
2960 * Whatever is known about this dao object.
2962 * @return array|bool
2963 * @throws \CiviCRM_API3_Exception
2965 * @see CRM_Core_DAO::buildOptionsContext
2966 * @see CRM_Core_DAO::buildOptions
2969 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2970 $className = __CLASS__
;
2972 switch ($fieldName) {
2973 // This field is not part of this object but the api supports it
2975 $className = 'CRM_Activity_BAO_Activity';
2978 // Filter status id by case type id
2980 if (!empty($props['case_type_id'])) {
2981 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
2982 $caseType = civicrm_api3('CaseType', 'getsingle', [$idField => $props['case_type_id'], 'return' => 'definition']);
2983 if (!empty($caseType['definition']['statuses'])) {
2984 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
2989 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
2995 public function addSelectWhereClause() {
2996 // We always return an array with these keys, even if they are empty,
2997 // because this tells the query builder that we have considered these fields for acls
3000 // Only case admins can view deleted cases
3001 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
[] : ["= 0"],
3003 // Ensure the user has permission to view the case client
3004 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3005 if ($contactClause) {
3006 $contactClause = implode(' AND contact_id ', $contactClause);
3007 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3009 // The api gatekeeper ensures the user has at least "access my cases and activities"
3010 // so if they do not have permission to see all cases we'll assume they can only access their own
3011 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3012 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3013 $clauses['id'][] = "IN (
3014 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 (
3015 (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)
3019 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3024 * CRM-20308: Method to get the contact id to use as from contact for email copy
3025 * 1. Activity Added by Contact's email address
3026 * 2. System Default From Address
3027 * 3. Default Organization Contact email address
3030 * @param int $activityID
3032 * @return mixed $emailFromContactId
3034 * @throws \CiviCRM_API3_Exception
3035 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3037 public static function getReceiptFrom($activityID) {
3038 $name = $address = NULL;
3040 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3041 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3042 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3043 // There is always a 'Added by' contact for a activity,
3044 // so we can safely use ActivityContact.Getvalue API
3045 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', [
3046 'activity_id' => $activityID,
3047 'record_type_id' => 'Activity Source',
3048 'return' => 'contact_id',
3050 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3053 // If 'From' email address not found for Source Activity Contact then
3054 // fetch the email from domain or logged in user.
3055 if (empty($address)) {
3056 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3059 return "$name <$address>";
3065 public static function getEntityRefFilters() {
3068 'key' => 'case_id.case_type_id',
3069 'value' => ts('Case Type'),
3073 'key' => 'case_id.status_id',
3074 'value' => ts('Case Status'),
3078 foreach (CRM_Contact_BAO_Contact
::getEntityRefFilters() as $filter) {
3079 $filter +
= ['entity' => 'Contact'];
3080 $filter['key'] = 'contact_id.' . $filter['key'];
3081 $filters[] = $filter;
3087 * Fetch Case Role direction from Case Type
3089 public static function getCaseRoleDirection($caseId, $roleTypeId = NULL) {
3091 $case = civicrm_api3('Case', 'getsingle', ['id' => $caseId]);
3093 catch (CiviCRM_API3_Exception
$e) {
3094 // Lack of permissions will throw an exception
3097 if (!empty($case['case_type_id'])) {
3099 $caseType = civicrm_api3('CaseType', 'getsingle', ['id' => $case['case_type_id'], 'return' => ['definition']]);
3101 catch (CiviCRM_API3_Exception
$e) {
3102 // Lack of permissions will throw an exception
3103 return 'no case type found';
3105 if (!empty($caseType['definition']['caseRoles'])) {
3107 foreach ($caseType['definition']['caseRoles'] as $key => $roleDetails) {
3108 // Check if its an a_b label
3110 $relType = civicrm_api3('RelationshipType', 'getsingle', ['label_a_b' => $roleDetails['name']]);
3112 catch (CiviCRM_API3_Exception
$e) {
3114 if (!empty($relType['id'])) {
3115 $roleDetails['id'] = $relType['id'];
3116 $roleDetails['direction'] = 'b_a';
3118 // Check if its a b_a label
3120 $relTypeBa = civicrm_api3('RelationshipType', 'getsingle', ['label_b_a' => $roleDetails['name']]);
3122 catch (CiviCRM_API3_Exception
$e) {
3124 if (!empty($relTypeBa['id'])) {
3125 if (!empty($roleDetails['direction'])) {
3126 $roleDetails['direction'] = 'bidrectional';
3129 $roleDetails['id'] = $relTypeBa['id'];
3130 $roleDetails['direction'] = 'a_b';
3133 $caseRoles[$roleDetails['id']] = $roleDetails;