Merge pull request #22657 from totten/master-queue-facade-c
[civicrm-core.git] / CRM / Case / BAO / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18
19 /**
20 * This class contains the functions for Case Management.
21 */
22 class CRM_Case_BAO_Case extends CRM_Case_DAO_Case {
23
24 /**
25 * Static field for all the case information that we can potentially export.
26 *
27 * @var array
28 */
29 public static $_exportableFields = NULL;
30
31 /**
32 * Is CiviCase enabled?
33 *
34 * @return bool
35 */
36 public static function enabled() {
37 $config = CRM_Core_Config::singleton();
38 return in_array('CiviCase', $config->enableComponents);
39 }
40
41 /**
42 * Create a case object.
43 *
44 * The function extracts all the params it needs to initialize the create a
45 * case object. the params array could contain additional unused name/value
46 * pairs
47 *
48 * @param array $params
49 * (reference ) an assoc array of name/value pairs.
50 *
51 * @return CRM_Case_DAO_Case
52 */
53 public static function add(&$params) {
54 $caseDAO = new CRM_Case_DAO_Case();
55 $caseDAO->copyValues($params);
56 $result = $caseDAO->save();
57 // Get other case values (required by XML processor), this adds to $result array
58 $caseDAO->find(TRUE);
59 return $result;
60 }
61
62 /**
63 * Takes an associative array and creates a case object.
64 *
65 * @param array $params
66 * (reference) an assoc array of name/value pairs.
67 *
68 * @return CRM_Case_DAO_Case
69 */
70 public static function &create(&$params) {
71 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
72 unset($params['created_date']);
73 unset($params['modified_date']);
74 $caseStatus = CRM_Case_PseudoConstant::caseStatus('name');
75 // for resolved case the end date should set to now
76 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
77 $params['end_date'] = date("Ymd");
78 }
79
80 $transaction = new CRM_Core_Transaction();
81
82 if (!empty($params['id'])) {
83 CRM_Utils_Hook::pre('edit', 'Case', $params['id'], $params);
84 }
85 else {
86 CRM_Utils_Hook::pre('create', 'Case', NULL, $params);
87 }
88
89 $case = self::add($params);
90
91 if (!empty($params['custom']) &&
92 is_array($params['custom'])
93 ) {
94 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_case', $case->id);
95 }
96
97 if (is_a($case, 'CRM_Core_Error')) {
98 $transaction->rollback();
99 return $case;
100 }
101
102 if (!empty($params['id'])) {
103 CRM_Utils_Hook::post('edit', 'Case', $case->id, $case);
104 }
105 else {
106 CRM_Utils_Hook::post('create', 'Case', $case->id, $case);
107 }
108 $transaction->commit();
109
110 //we are not creating log for case
111 //since case log can be tracked using log for activity.
112 return $case;
113 }
114
115 /**
116 * Process case activity add/delete
117 * takes an associative array and
118 *
119 * @param array $params
120 * (reference ) an assoc array of name/value pairs.
121 *
122 */
123 public static function processCaseActivity(&$params) {
124 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
125 $caseActivityDAO->activity_id = $params['activity_id'];
126 $caseActivityDAO->case_id = $params['case_id'];
127
128 $caseActivityDAO->find(TRUE);
129 $caseActivityDAO->save();
130 }
131
132 /**
133 * Get the case subject for Activity.
134 *
135 * @param int $activityId
136 * Activity id.
137 *
138 * @return string|null
139 */
140 public static function getCaseSubject($activityId) {
141 $caseActivity = new CRM_Case_DAO_CaseActivity();
142 $caseActivity->activity_id = $activityId;
143 if ($caseActivity->find(TRUE)) {
144 return CRM_Core_DAO::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id, 'subject');
145 }
146 return NULL;
147 }
148
149 /**
150 * Get the case type.
151 *
152 * @param int $caseId
153 * @param string $colName
154 *
155 * @return string
156 * case type
157 */
158 public static function getCaseType($caseId, $colName = 'title') {
159 $query = "
160 SELECT civicrm_case_type.{$colName} FROM civicrm_case
161 LEFT JOIN civicrm_case_type ON
162 civicrm_case.case_type_id = civicrm_case_type.id
163 WHERE civicrm_case.id = %1";
164
165 $queryParams = [1 => [$caseId, 'Integer']];
166
167 return CRM_Core_DAO::singleValueQuery($query, $queryParams);
168 }
169
170 /**
171 * Delete the record that are associated with this case.
172 * record are deleted from case
173 *
174 * @param int $caseId
175 * Id of the case to delete.
176 *
177 * @param bool $moveToTrash
178 *
179 * @return bool
180 * is successful
181 */
182 public static function deleteCase($caseId, $moveToTrash = FALSE) {
183 CRM_Utils_Hook::pre('delete', 'Case', $caseId);
184
185 //delete activities
186 $activities = self::getCaseActivityDates($caseId);
187 if ($activities) {
188 foreach ($activities as $value) {
189 CRM_Activity_BAO_Activity::deleteActivity($value, $moveToTrash);
190 }
191 }
192
193 if (!$moveToTrash) {
194 $transaction = new CRM_Core_Transaction();
195 }
196 $case = new CRM_Case_DAO_Case();
197 $case->id = $caseId;
198 if (!$moveToTrash) {
199 $result = $case->delete();
200 $transaction->commit();
201 }
202 else {
203 $result = $case->is_deleted = 1;
204 $case->save();
205 }
206
207 if ($result) {
208 // CRM-7364, disable relationships
209 self::enableDisableCaseRelationships($caseId, FALSE);
210
211 CRM_Utils_Hook::post('delete', 'Case', $caseId, $case);
212
213 return TRUE;
214 }
215
216 return FALSE;
217 }
218
219 /**
220 * @param int $id
221 * @return bool
222 */
223 public static function del($id) {
224 return self::deleteCase($id);
225 }
226
227 /**
228 * Enable disable case related relationships.
229 *
230 * @param int $caseId
231 * Case id.
232 * @param bool $enable
233 * Action.
234 */
235 public static function enableDisableCaseRelationships($caseId, $enable) {
236 $contactIds = self::retrieveContactIdsByCaseId($caseId);
237 if (!empty($contactIds)) {
238 foreach ($contactIds as $cid) {
239 $roles = self::getCaseRoles($cid, $caseId);
240 if (!empty($roles)) {
241 $relationshipIds = implode(',', array_keys($roles));
242 $enable = (int) $enable;
243 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
244 WHERE id IN ( {$relationshipIds} )";
245 CRM_Core_DAO::executeQuery($query);
246 }
247 }
248 }
249 }
250
251 /**
252 * Retrieve contact_id by case_id.
253 *
254 * @param int $caseId
255 * ID of the case.
256 *
257 * @param int $contactID
258 * @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
259 *
260 * @return array
261 */
262 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
263 $caseContact = new CRM_Case_DAO_CaseContact();
264 $caseContact->case_id = $caseId;
265 $caseContact->find();
266 $contactArray = [];
267 $count = $startArrayAt;
268 while ($caseContact->fetch()) {
269 if ($contactID != $caseContact->contact_id) {
270 $contactArray[$count] = $caseContact->contact_id;
271 $count++;
272 }
273 }
274
275 return $contactArray;
276 }
277
278 /**
279 * Look up a case using an activity ID.
280 *
281 * @param int $activityId
282 *
283 * @return int|null, case ID
284 */
285 public static function getCaseIdByActivityId($activityId) {
286 $originalId = CRM_Core_DAO::singleValueQuery(
287 'SELECT original_id FROM civicrm_activity WHERE id = %1',
288 ['1' => [$activityId, 'Integer']]
289 );
290 $caseId = CRM_Core_DAO::singleValueQuery(
291 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
292 [
293 '1' => [$activityId, 'Integer'],
294 '2' => [$originalId ? $originalId : $activityId, 'Integer'],
295 ]
296 );
297 return $caseId;
298 }
299
300 /**
301 * Retrieve contact names by caseId.
302 *
303 * @param int $caseId
304 * ID of the case.
305 *
306 * @return array
307 */
308 public static function getContactNames($caseId) {
309 $contactNames = [];
310 if (!$caseId) {
311 return $contactNames;
312 }
313
314 $query = "
315 SELECT contact_a.sort_name name,
316 contact_a.display_name as display_name,
317 contact_a.id cid,
318 contact_a.birth_date as birth_date,
319 ce.email as email,
320 cp.phone as phone
321 FROM civicrm_contact contact_a
322 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
323 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
324 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
325 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
326 ORDER BY civicrm_case_contact.id";
327
328 $dao = CRM_Core_DAO::executeQuery($query,
329 [1 => [$caseId, 'Integer']]
330 );
331 while ($dao->fetch()) {
332 $contactNames[$dao->cid]['contact_id'] = $dao->cid;
333 $contactNames[$dao->cid]['sort_name'] = $dao->name;
334 $contactNames[$dao->cid]['display_name'] = $dao->display_name;
335 $contactNames[$dao->cid]['email'] = $dao->email;
336 $contactNames[$dao->cid]['phone'] = $dao->phone;
337 $contactNames[$dao->cid]['birth_date'] = $dao->birth_date;
338 $contactNames[$dao->cid]['role'] = ts('Client');
339 }
340
341 return $contactNames;
342 }
343
344 /**
345 * Retrieve case_id by contact_id.
346 *
347 * @param int $contactID
348 * @param bool $includeDeleted
349 * Include the deleted cases in result.
350 * @param null $caseType
351 *
352 * @return array
353 */
354 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
355 $query = "
356 SELECT ca.id as id
357 FROM civicrm_case_contact cc
358 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
359 ";
360 if (isset($caseType)) {
361 $query .=
362 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
363 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
364 }
365 if (!isset($caseType)) {
366 $query .= "WHERE cc.contact_id = %1";
367 }
368 if (!$includeDeleted) {
369 $query .= " AND ca.is_deleted = 0";
370 }
371
372 $params = [1 => [$contactID, 'Integer']];
373 $dao = CRM_Core_DAO::executeQuery($query, $params);
374
375 $caseArray = [];
376 while ($dao->fetch()) {
377 $caseArray[] = $dao->id;
378 }
379
380 return $caseArray;
381 }
382
383 /**
384 * @param string $type
385 * @param int $userID
386 * @param string $condition
387 *
388 * @return string
389 */
390 public static function getCaseActivityCountQuery($type, $userID, $condition = NULL) {
391 return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self::getCaseActivityQuery($type, $userID, $condition));
392 }
393
394 /**
395 * @param string $type
396 * @param int $userID
397 * @param string $condition
398 * @param string $limit
399 * @param string $order
400 *
401 * @return string
402 */
403 public static function getCaseActivityQuery($type, $userID, $condition = NULL, $limit = NULL, $order = NULL) {
404 $selectClauses = [
405 'civicrm_case.id as case_id',
406 'civicrm_case.subject as case_subject',
407 'civicrm_contact.id as contact_id',
408 'civicrm_contact.sort_name as sort_name',
409 'civicrm_phone.phone as phone',
410 'civicrm_contact.contact_type as contact_type',
411 'civicrm_contact.contact_sub_type as contact_sub_type',
412 't_act.activity_type_id as activity_type_id',
413 'civicrm_case.case_type_id as case_type_id',
414 'civicrm_case.status_id as case_status_id',
415 't_act.status_id as status_id',
416 'civicrm_case.start_date as case_start_date',
417 "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",
418 't_act.activity_date_time as activity_date_time',
419 't_act.id as activity_id',
420 ];
421
422 $query = CRM_Contact_BAO_Query::appendAnyValueToSelect($selectClauses, 'case_id');
423
424 $query .= <<<HERESQL
425 FROM civicrm_case
426 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
427 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id
428 HERESQL;
429
430 // 'upcoming' and 'recent' show the next scheduled and most recent
431 // not-scheduled activity on each case, respectively.
432 $scheduled_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
433 switch ($type) {
434 case 'upcoming':
435 $query .= <<<HERESQL
436 INNER JOIN (SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
437 FROM civicrm_case_activity ca
438 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
439 WHERE a.id =
440 (SELECT b.id FROM civicrm_case_activity bca
441 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
442 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
443 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
444 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)) t_act
445 ON t_act.case_id = civicrm_case.id
446 HERESQL;
447 break;
448
449 case 'recent':
450 $query .= <<<HERESQL
451 INNER JOIN (SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
452 FROM civicrm_case_activity ca
453 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
454 WHERE a.id =
455 (SELECT b.id FROM civicrm_case_activity bca
456 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
457 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
458 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
459 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)) t_act
460 ON t_act.case_id = civicrm_case.id
461 HERESQL;
462 break;
463
464 case 'any':
465 $query .= <<<HERESQL
466 LEFT JOIN civicrm_case_activity ca4
467 ON civicrm_case.id = ca4.case_id
468 LEFT JOIN civicrm_activity t_act
469 ON t_act.id = ca4.activity_id
470 AND t_act.is_current_revision = 1
471 HERESQL;
472 }
473
474 $query .= <<<HERESQL
475 LEFT JOIN civicrm_phone
476 ON civicrm_phone.contact_id = civicrm_contact.id
477 AND civicrm_phone.is_primary = 1
478 LEFT JOIN civicrm_relationship case_relationship
479 ON ((case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID})
480 OR (case_relationship.contact_id_b = civicrm_case_contact.contact_id AND case_relationship.contact_id_a = {$userID}))
481 AND case_relationship.is_active
482 AND case_relationship.case_id = civicrm_case.id
483 LEFT JOIN civicrm_relationship_type case_relation_type
484 ON case_relation_type.id = case_relationship.relationship_type_id
485 AND case_relation_type.id = case_relationship.relationship_type_id
486 HERESQL;
487
488 if ($condition) {
489 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
490 $query .= " WHERE (1) AND $condition ";
491 }
492 $query .= " GROUP BY case_id ";
493
494 $query .= ($order) ?: ' ORDER BY activity_date_time ASC';
495
496 if ($limit) {
497 $query .= $limit;
498 }
499
500 return $query;
501 }
502
503 /**
504 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
505 *
506 * @param bool $allCases
507 * @param array $params
508 * @param string $context
509 * @param bool $getCount
510 *
511 * @return array
512 * Array of Cases
513 */
514 public static function getCases($allCases = TRUE, $params = [], $context = 'dashboard', $getCount = FALSE) {
515 $condition = NULL;
516 $casesList = [];
517
518 // validate access for own cases.
519 if (!self::accessCiviCase()) {
520 return $getCount ? 0 : $casesList;
521 }
522
523 // Return cached value instead of re-running query
524 if (isset(Civi::$statics[__CLASS__]['totalCount']) && $getCount) {
525 return Civi::$statics[__CLASS__]['totalCount'];
526 }
527
528 $type = CRM_Utils_Array::value('type', $params, 'upcoming');
529 $userID = CRM_Core_Session::getLoggedInContactID();
530
531 // validate access for all cases.
532 if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
533 $allCases = FALSE;
534 }
535
536 $whereClauses = ['civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1'];
537
538 if (!$allCases) {
539 $whereClauses[] = "(case_relationship.contact_id_b = {$userID} OR case_relationship.contact_id_a = {$userID})";
540 $whereClauses[] = 'case_relationship.is_active';
541 }
542 if (empty($params['status_id']) && $type == 'upcoming') {
543 $whereClauses[] = "civicrm_case.status_id != " . CRM_Core_PseudoConstant::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
544 }
545
546 foreach (['case_type_id', 'status_id'] as $column) {
547 if (!empty($params[$column])) {
548 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
549 }
550 }
551 $condition = implode(' AND ', $whereClauses);
552
553 Civi::$statics[__CLASS__]['totalCount'] = $totalCount = CRM_Core_DAO::singleValueQuery(self::getCaseActivityCountQuery($type, $userID, $condition));
554 if ($getCount) {
555 return $totalCount;
556 }
557 $casesList['total'] = $totalCount;
558
559 $limit = '';
560 if (!empty($params['rp'])) {
561 $params['offset'] = ($params['page'] - 1) * $params['rp'];
562 $params['rowCount'] = $params['rp'];
563 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
564 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
565 }
566 }
567
568 $order = NULL;
569 if (!empty($params['sortBy'])) {
570 if (strstr($params['sortBy'], 'date ')) {
571 $params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
572 }
573 $order = "ORDER BY " . $params['sortBy'];
574 }
575
576 $query = self::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
577 $result = CRM_Core_DAO::executeQuery($query);
578
579 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
580 $actions = CRM_Case_Selector_Search::links();
581
582 // check is the user has view/edit signer permission
583 $permissions = [CRM_Core_Permission::VIEW];
584 if (CRM_Core_Permission::check('access all cases and activities') ||
585 (!$allCases && CRM_Core_Permission::check('access my cases and activities'))
586 ) {
587 $permissions[] = CRM_Core_Permission::EDIT;
588 }
589 if (CRM_Core_Permission::check('delete in CiviCase')) {
590 $permissions[] = CRM_Core_Permission::DELETE;
591 }
592 $mask = CRM_Core_Action::mask($permissions);
593
594 // Pseudoconstants to populate labels
595 $caseStatuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
596 $caseTypes = CRM_Case_PseudoConstant::caseType('name');
597 $caseTypeTitles = CRM_Case_PseudoConstant::caseType('title', FALSE);
598 $activityTypeLabels = CRM_Activity_BAO_Activity::buildOptions('activity_type_id');
599
600 foreach ($result->fetchAll() as $case) {
601 $key = $case['case_id'];
602 $casesList[$key] = [];
603 $casesList[$key]['DT_RowId'] = $case['case_id'];
604 $casesList[$key]['DT_RowAttr'] = ['data-entity' => 'case', 'data-id' => $case['case_id']];
605 $casesList[$key]['DT_RowClass'] = "crm-entity";
606
607 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
608 ts('Activities'),
609 CRM_Utils_System::url('civicrm/case/details', ['caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type])
610 );
611
612 $phone = empty($case['phone']) ? '' : '<br /><span class="description">' . $case['phone'] . '</span>';
613 $casesList[$key]['sort_name'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
614 CRM_Utils_System::url('civicrm/contact/view', ['cid' => $case['contact_id']]),
615 $case['sort_name'],
616 $phone,
617 ts('Case ID'),
618 $case['case_id']
619 );
620 $casesList[$key]['subject'] = $case['case_subject'];
621 $casesList[$key]['case_status'] = $caseStatuses[$case['case_status_id']] ?? NULL;
622 if ($case['case_status_id'] == CRM_Case_PseudoConstant::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
623 $casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
624 }
625 $casesList[$key]['case_type'] = $caseTypeTitles[$case['case_type_id']] ?? NULL;
626 $casesList[$key]['case_role'] = CRM_Utils_Array::value('case_role', $case, '---');
627 $casesList[$key]['manager'] = self::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
628
629 $casesList[$key]['date'] = $activityTypeLabels[$case['activity_type_id']] ?? NULL;
630 if ($actId = CRM_Utils_Array::value('activity_id', $case)) {
631 if (self::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
632 if ($type == 'recent') {
633 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
634 CRM_Utils_System::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
635 ts('View activity'),
636 CRM_Utils_Array::value($case['activity_type_id'], $activityTypeLabels)
637 );
638 }
639 else {
640 $status = CRM_Utils_Date::overdue($case['activity_date_time']) ? 'status-overdue' : 'status-scheduled';
641 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> &nbsp;&nbsp;',
642 $status,
643 CRM_Utils_System::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
644 ts('View activity'),
645 CRM_Utils_Array::value($case['activity_type_id'], $activityTypeLabels)
646 );
647 }
648 }
649 if (isset($case['activity_type_id']) && self::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
650 $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>',
651 CRM_Utils_System::url('civicrm/case/activity', ['reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId]),
652 ts('Edit activity')
653 );
654 }
655 }
656 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date::customFormat($case['activity_date_time']);
657 $casesList[$key]['links'] = CRM_Core_Action::formLink($actions['primaryActions'], $mask,
658 [
659 'id' => $case['case_id'],
660 'cid' => $case['contact_id'],
661 'cxt' => $context,
662 ],
663 ts('more'),
664 FALSE,
665 'case.actions.primary',
666 'Case',
667 $case['case_id']
668 );
669 }
670
671 return $casesList;
672 }
673
674 /**
675 * Get the summary of cases counts by type and status.
676 *
677 * @param bool $allCases
678 *
679 * @return array
680 */
681 public static function getCasesSummary($allCases = TRUE) {
682 $caseSummary = [];
683
684 //validate access for civicase.
685 if (!self::accessCiviCase()) {
686 return $caseSummary;
687 }
688
689 $userID = CRM_Core_Session::getLoggedInContactID();
690
691 //validate access for all cases.
692 if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
693 $allCases = FALSE;
694 }
695
696 $caseTypes = CRM_Case_PseudoConstant::caseType();
697 $caseStatuses = CRM_Case_PseudoConstant::caseStatus();
698 $caseTypes = array_flip($caseTypes);
699
700 // get statuses as headers for the table
701 $url = CRM_Utils_System::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
702 foreach ($caseStatuses as $key => $name) {
703 $caseSummary['headers'][$key]['status'] = $name;
704 $caseSummary['headers'][$key]['url'] = $url . $key;
705 }
706
707 // build rows with actual data
708 $rows = [];
709 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClauseA = $myCaseWhereClauseB = '';
710
711 if ($allCases) {
712 $userID = 'null';
713 $all = 1;
714 $case_owner = 1;
715 $myGroupByClauseB = ' GROUP BY civicrm_case.id';
716 }
717 else {
718 $all = 0;
719 $case_owner = 2;
720 $myCaseWhereClauseA = " AND case_relationship.contact_id_a = {$userID} AND case_relationship.is_active ";
721 $myGroupByClauseA = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_a)";
722 $myCaseWhereClauseB = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
723 $myGroupByClauseB = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_b)";
724 }
725 $myGroupByClauseB .= ", case_status.label, status_id, case_type_id, civicrm_case.id";
726 $myGroupByClauseA = $myGroupByClauseB;
727 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
728 $query = "
729 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
730 case_type_id, case_relationship.contact_id_b as case_contact
731 FROM civicrm_case
732 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
733 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
734 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
735 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
736 AND option_group_case_status.id = case_status.option_group_id )
737 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
738 AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
739 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
740 {$myCaseWhereClauseB} {$myGroupByClauseB}
741 UNION
742 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
743 case_type_id, case_relationship.contact_id_a as case_contact
744 FROM civicrm_case
745 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
746 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
747 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
748 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
749 AND option_group_case_status.id = case_status.option_group_id )
750 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
751 AND case_relationship.contact_id_a = {$userID})
752 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
753 {$myCaseWhereClauseA} {$myGroupByClauseA}";
754
755 $res = CRM_Core_DAO::executeQuery($query);
756 while ($res->fetch()) {
757 if (!isset($rows[$res->case_type])) {
758 $rows[$res->case_type] = array_fill_keys($caseStatuses, []);
759 }
760 if (!empty($rows[$res->case_type]) && !empty($rows[$res->case_type][$res->case_status])) {
761 $rows[$res->case_type][$res->case_status]['count'] = $rows[$res->case_type][$res->case_status]['count'] + 1;
762 }
763 else {
764 $rows[$res->case_type][$res->case_status] = [
765 'count' => 1,
766 'url' => CRM_Utils_System::url('civicrm/case/search',
767 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
768 ),
769 ];
770 }
771 }
772 $caseSummary['rows'] = array_merge($caseTypes, $rows);
773
774 return $caseSummary;
775 }
776
777 /**
778 * Get Case roles.
779 *
780 * @param int $contactID
781 * Contact id.
782 * @param int $caseID
783 * Case id.
784 * @param int $relationshipID
785 * @param bool $activeOnly
786 *
787 * @return array
788 * case role / relationships
789 *
790 */
791 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
792 $query = '
793 SELECT rel.id as civicrm_relationship_id,
794 con.sort_name as sort_name,
795 civicrm_email.email as email,
796 civicrm_phone.phone as phone,
797 con.id as civicrm_contact_id,
798 rel.is_active as is_active,
799 rel.end_date as end_date,
800 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
801 civicrm_relationship_type.id as relation_type,
802 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
803 FROM civicrm_relationship rel
804 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
805 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))
806 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
807 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
808 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
809 AND con.is_deleted = 0';
810
811 if ($activeOnly) {
812 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
813 }
814
815 $params = [
816 1 => [$contactID, 'Positive'],
817 2 => [$caseID, 'Positive'],
818 ];
819
820 if ($relationshipID) {
821 $query .= ' AND rel.id = %3 ';
822 $params[3] = [$relationshipID, 'Integer'];
823 }
824
825 $dao = CRM_Core_DAO::executeQuery($query, $params);
826
827 $values = [];
828 while ($dao->fetch()) {
829 $rid = $dao->civicrm_relationship_id;
830 $values[$rid]['cid'] = $dao->civicrm_contact_id;
831 $values[$rid]['relation'] = $dao->relation;
832 $values[$rid]['sort_name'] = $dao->sort_name;
833 $values[$rid]['email'] = $dao->email;
834 $values[$rid]['phone'] = $dao->phone;
835 $values[$rid]['is_active'] = $dao->is_active;
836 $values[$rid]['end_date'] = $dao->end_date;
837 $values[$rid]['relation_type'] = $dao->relation_type;
838 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id;
839 $values[$rid]['client_id'] = $contactID;
840 $values[$rid]['relationship_direction'] = $dao->relationship_direction;
841 }
842
843 return $values;
844 }
845
846 /**
847 * Get Case Activities.
848 *
849 * @param int $caseID
850 * Case id.
851 * @param array $params
852 * Posted params.
853 * @param int $contactID
854 * Contact id.
855 *
856 * @param null $context
857 * @param int $userID
858 * @param null $type (deprecated)
859 *
860 * @return array
861 * Array of case activities
862 *
863 */
864 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
865 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
866 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
867 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
868 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
869
870 // CRM-5081 - formatting the dates to omit seconds.
871 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
872 $select = "
873 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
874 ca.id AS id,
875 ca.activity_type_id AS type,
876 ca.activity_type_id AS activity_type_id,
877 tcc.sort_name AS target_contact_name,
878 tcc.id AS target_contact_id,
879 scc.sort_name AS source_contact_name,
880 scc.id AS source_contact_id,
881 acc.sort_name AS assignee_contact_name,
882 acc.id AS assignee_contact_id,
883 DATE_FORMAT(
884 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
885 ca.activity_date_time,
886 DATE_ADD(NOW(), INTERVAL 1 YEAR)
887 ), '%Y%m%d%H%i00') AS overdue_date,
888 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
889 ca.status_id AS status,
890 ca.subject AS subject,
891 ca.is_deleted AS deleted,
892 ca.priority_id AS priority,
893 ca.weight AS weight,
894 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
895
896 $from = "
897 FROM civicrm_case_activity cca
898 INNER JOIN civicrm_activity ca
899 ON ca.id = cca.activity_id
900 INNER JOIN civicrm_activity_contact cas
901 ON cas.activity_id = ca.id
902 AND cas.record_type_id = {$sourceID}
903 INNER JOIN civicrm_contact scc
904 ON scc.id = cas.contact_id
905 LEFT JOIN civicrm_activity_contact caa
906 ON caa.activity_id = ca.id
907 AND caa.record_type_id = {$assigneeID}
908 LEFT JOIN civicrm_contact acc
909 ON acc.id = caa.contact_id
910 LEFT JOIN civicrm_activity_contact cat
911 ON cat.activity_id = ca.id
912 AND cat.record_type_id = {$targetID}
913 LEFT JOIN civicrm_contact tcc
914 ON tcc.id = cat.contact_id
915 INNER JOIN civicrm_option_group cog
916 ON cog.name = 'activity_type'
917 INNER JOIN civicrm_option_value cov
918 ON cov.option_group_id = cog.id
919 AND cov.value = ca.activity_type_id
920 AND cov.is_active = 1
921 LEFT JOIN civicrm_entity_file ef
922 ON ef.entity_table = 'civicrm_activity'
923 AND ef.entity_id = ca.id
924 LEFT OUTER JOIN civicrm_option_group og
925 ON og.name = 'activity_status'
926 LEFT OUTER JOIN civicrm_option_value ov
927 ON ov.option_group_id=og.id
928 AND ov.name = 'Scheduled'";
929
930 $where = '
931 WHERE cca.case_id= %1
932 AND ca.is_current_revision = 1';
933
934 if (!empty($params['source_contact_id'])) {
935 $where .= "
936 AND cas.contact_id = " . CRM_Utils_Type::escape($params['source_contact_id'], 'Integer');
937 }
938
939 if (!empty($params['status_id'])) {
940 $where .= "
941 AND ca.status_id = " . CRM_Utils_Type::escape($params['status_id'], 'Integer');
942 }
943
944 if (!empty($params['activity_deleted'])) {
945 $where .= "
946 AND ca.is_deleted = 1";
947 }
948 else {
949 $where .= "
950 AND ca.is_deleted = 0";
951 }
952
953 if (!empty($params['activity_type_id'])) {
954 $where .= "
955 AND ca.activity_type_id = " . CRM_Utils_Type::escape($params['activity_type_id'], 'Integer');
956 }
957
958 if (!empty($params['activity_date_low'])) {
959 $fromActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_low']), 'Date');
960 }
961 if (!empty($fromActivityDate)) {
962 $where .= "
963 AND ca.activity_date_time >= '{$fromActivityDate}'";
964 }
965
966 if (!empty($params['activity_date_high'])) {
967 $toActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_high']), 'Date');
968 $toActivityDate = $toActivityDate ? $toActivityDate + 235959 : NULL;
969 }
970 if (!empty($toActivityDate)) {
971 $where .= "
972 AND ca.activity_date_time <= '{$toActivityDate}'";
973 }
974
975 $groupBy = "
976 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
977
978 $sortBy = $params['sortBy'] ?? NULL;
979 if (!$sortBy) {
980 // CRM-5081 - added id to act like creation date
981 $orderBy = "
982 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
983 }
984 else {
985 $sortBy = CRM_Utils_Type::escape($sortBy, 'String');
986 $orderBy = " ORDER BY $sortBy ";
987 }
988
989 $page = $params['page'] ?? NULL;
990 $rp = $params['rp'] ?? NULL;
991
992 if (!$page) {
993 $page = 1;
994 }
995 if (!$rp) {
996 $rp = 10;
997 }
998 $start = (($page - 1) * $rp);
999 $limit = " LIMIT $start, $rp";
1000
1001 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1002 $queryParams = [1 => [$caseID, 'Integer']];
1003
1004 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
1005 $caseCount = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
1006
1007 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
1008
1009 $compStatusValues = array_keys(
1010 CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::COMPLETED) +
1011 CRM_Activity_BAO_Activity::getStatusesByType(CRM_Activity_BAO_Activity::CANCELLED)
1012 );
1013
1014 if (!$userID) {
1015 $userID = CRM_Core_Session::getLoggedInContactID();
1016 }
1017
1018 $caseActivities = [];
1019
1020 while ($dao->fetch()) {
1021 $caseActivityId = $dao->id;
1022
1023 //Do we have permission to access given case activity record.
1024 if (!self::checkPermission($caseActivityId, 'view', $dao->activity_type_id, $userID)) {
1025 continue;
1026 }
1027
1028 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1029 //Add classes to the row, via DataTables syntax
1030 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1031
1032 if (CRM_Utils_Array::crmInArray($dao->status, $compStatusValues)) {
1033 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1034 }
1035 else {
1036 if (CRM_Utils_Date::overdue($dao->display_date)) {
1037 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1038 }
1039 else {
1040 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1041 }
1042 }
1043
1044 if (!empty($dao->priority)) {
1045 if ($dao->priority == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1046 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1047 }
1048 elseif ($dao->priority == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1049 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1050 }
1051 }
1052
1053 //Add data to the row for inline editing, via DataTable syntax
1054 $caseActivities[$caseActivityId]['DT_RowAttr'] = [];
1055 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1056 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1057
1058 //Activity Date and Time
1059 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date::customFormat($dao->display_date);
1060
1061 //Activity Subject
1062 $caseActivities[$caseActivityId]['subject'] = $dao->subject;
1063
1064 //Activity Type
1065 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type]['icon']) ? '<span class="crm-i ' . $activityTypes[$dao->type]['icon'] . '"></span> ' : '')
1066 . $activityTypes[$dao->type]['label'];
1067
1068 // Activity Target (With Contact) (There can be more than one)
1069 $targetContact = self::formatContactLink($dao->target_contact_id, $dao->target_contact_name);
1070 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1071 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1072 }
1073 else {
1074 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1075 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1076 }
1077 }
1078
1079 // Activity Source Contact (Reporter) (There can only be one)
1080 $sourceContact = self::formatContactLink($dao->source_contact_id, $dao->source_contact_name);
1081 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1082
1083 // Activity Assignee (There can be more than one)
1084 $assigneeContact = self::formatContactLink($dao->assignee_contact_id, $dao->assignee_contact_name);
1085 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1086 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1087 }
1088 else {
1089 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1090 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1091 }
1092 }
1093
1094 // Activity Status Label for Case activities list
1095 $deleted = '';
1096 if ($dao->deleted) {
1097 $deleted = '<br /> ' . ts('(deleted)');
1098 }
1099 $caseActivities[$caseActivityId]['status_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status) . $deleted;
1100 // if there are file attachments we will return how many
1101 if (!empty($dao->attachment_ids)) {
1102 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids));
1103 $caseActivity['no_attachments'] = count($attachmentIDs);
1104 }
1105
1106 $caseActivities[$caseActivityId]['links']
1107 = CRM_Case_Selector_Search::addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao);
1108 }
1109
1110 $caseActivitiesDT = [];
1111 $caseActivitiesDT['data'] = array_values($caseActivities);
1112 $caseActivitiesDT['recordsTotal'] = $caseCount;
1113 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1114
1115 return $caseActivitiesDT;
1116 }
1117
1118 /**
1119 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1120 *
1121 * @param int $contactId
1122 * @param string $contactName
1123 *
1124 * @return string
1125 */
1126 private static function formatContactLink($contactId, $contactName) {
1127 if (empty($contactId)) {
1128 return NULL;
1129 }
1130
1131 $hasViewContact = CRM_Contact_BAO_Contact_Permission::allow($contactId);
1132
1133 if ($hasViewContact) {
1134 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1135 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1136 }
1137 else {
1138 return $contactName;
1139 }
1140 }
1141
1142 /**
1143 * Get Case Related Contacts.
1144 *
1145 * @param int $caseID
1146 * Case id.
1147 * @param bool $includeDetails
1148 * If true include details of contacts.
1149 *
1150 * @return array
1151 * array of return properties
1152 *
1153 */
1154 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1155 $caseRoles = [];
1156 if ($includeDetails) {
1157 $caseInfo = civicrm_api3('Case', 'getsingle', [
1158 'id' => $caseID,
1159 // 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
1160 'return' => ['case_type_id', 'case_type_id.name', 'case_type_id.definition', 'contact_id'],
1161 ]);
1162 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1163 $caseRoles = CRM_Utils_Array::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1164 }
1165 }
1166
1167 $values = [];
1168 $caseClientCondition = !empty($caseInfo['client_id']) ? "AND cc.id NOT IN (%2)" : '';
1169 $query = <<<HERESQL
1170 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
1171 FROM civicrm_relationship cr
1172 JOIN civicrm_relationship_type crt
1173 ON crt.id = cr.relationship_type_id
1174 JOIN civicrm_contact cc
1175 ON cc.id = cr.contact_id_a
1176 AND cc.is_deleted <> 1
1177 LEFT JOIN civicrm_email ce
1178 ON ce.contact_id = cc.id
1179 AND ce.is_primary= 1
1180 LEFT JOIN civicrm_phone cp
1181 ON cp.contact_id = cc.id
1182 AND cp.is_primary= 1
1183 WHERE cr.case_id = %1
1184 AND cr.is_active
1185 {$caseClientCondition}
1186 UNION
1187 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
1188 FROM civicrm_relationship cr
1189 JOIN civicrm_relationship_type crt
1190 ON crt.id = cr.relationship_type_id
1191 JOIN civicrm_contact cc
1192 ON cc.id = cr.contact_id_b
1193 AND cc.is_deleted <> 1
1194 LEFT JOIN civicrm_email ce
1195 ON ce.contact_id = cc.id
1196 AND ce.is_primary= 1
1197 LEFT JOIN civicrm_phone cp
1198 ON cp.contact_id = cc.id
1199 AND cp.is_primary= 1
1200 WHERE cr.case_id = %1
1201 AND cr.is_active
1202 {$caseClientCondition}
1203 HERESQL;
1204
1205 $params = [
1206 1 => [$caseID, 'Integer'],
1207 ];
1208
1209 if ($caseClientCondition) {
1210 $params[2] = [implode(',', $caseInfo['client_id']), 'CommaSeparatedIntegers'];
1211 }
1212 $dao = CRM_Core_DAO::executeQuery($query, $params);
1213
1214 while ($dao->fetch()) {
1215 if (!$includeDetails) {
1216 $values[$dao->id] = 1;
1217 }
1218 else {
1219 $details = [
1220 'contact_id' => $dao->id,
1221 'display_name' => $dao->name,
1222 'sort_name' => $dao->sort_name,
1223 'relationship_type_id' => $dao->relationship_type_id,
1224 'role' => $dao->role,
1225 'email' => $dao->email,
1226 'phone' => $dao->phone,
1227 ];
1228 // Add more info about the role (creator, manager)
1229 // The XML historically has the reverse direction, so look up reverse.
1230 $role = $caseRoles[$dao->role_name_reverse] ?? NULL;
1231 if ($role) {
1232 unset($role['name']);
1233 $details += $role;
1234 }
1235 $values[] = $details;
1236 }
1237 }
1238
1239 return $values;
1240 }
1241
1242 /**
1243 * Send e-mail copy of activity
1244 *
1245 * @param int $clientId
1246 * @param int $activityId
1247 * Activity Id.
1248 * @param array $contacts
1249 * Array of related contact.
1250 *
1251 * @param null $attachments
1252 * @param int $caseId
1253 *
1254 * @return bool |array
1255 */
1256 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments, $caseId) {
1257 if (!$activityId) {
1258 return FALSE;
1259 }
1260
1261 $tplParams = $activityInfo = [];
1262 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1263 // If it's a case activity
1264 if ($caseId) {
1265 $nonCaseActivityTypes = CRM_Core_PseudoConstant::activityType();
1266 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1267 $anyActivity = TRUE;
1268 }
1269 else {
1270 $anyActivity = FALSE;
1271 }
1272 $tplParams['isCaseActivity'] = 1;
1273 $tplParams['client_id'] = $clientId;
1274 }
1275 else {
1276 $anyActivity = TRUE;
1277 }
1278
1279 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1280 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1281
1282 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1283
1284 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1285 if ($caseId) {
1286 $activityInfo['fields'][] = ['label' => 'Case ID', 'type' => 'String', 'value' => $caseId];
1287 }
1288 $tplParams['activityTypeName'] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeId);
1289 $tplParams['activity'] = $activityInfo;
1290 foreach ($tplParams['activity']['fields'] as $k => $val) {
1291 if (CRM_Utils_Array::value('label', $val) == ts('Subject')) {
1292 $activitySubject = $val['value'];
1293 break;
1294 }
1295 }
1296
1297 // CRM-8926 If user is not logged in, use the activity creator as userID
1298 if (!($userID = CRM_Core_Session::getLoggedInContactID())) {
1299 $userID = CRM_Activity_BAO_Activity::getSourceContactID($activityId);
1300 }
1301
1302 //also create activities simultaneously of this copy.
1303 $activityParams = [];
1304
1305 $activityParams['source_record_id'] = $activityId;
1306 $activityParams['source_contact_id'] = $userID;
1307 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1308 $activityParams['activity_date_time'] = date('YmdHis');
1309 $activityParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1310 $activityParams['medium_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1311 $activityParams['case_id'] = $caseId;
1312 $activityParams['is_auto'] = 0;
1313 $activityParams['target_id'] = $clientId;
1314
1315 $tplParams['activitySubject'] = $activitySubject;
1316
1317 // if it’s a case activity, add hashed id to the template (CRM-5916)
1318 if ($caseId) {
1319 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY . $caseId), 0, 7);
1320 }
1321
1322 $result = [];
1323 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1324 $receiptFrom = self::getReceiptFrom($activityId);
1325
1326 $recordedActivityParams = [];
1327
1328 foreach ($contacts as $mail => $info) {
1329 $tplParams['contact'] = $info;
1330 self::buildPermissionLinks($tplParams, $activityParams);
1331
1332 $displayName = $info['display_name'] ?? NULL;
1333
1334 list($result[CRM_Utils_Array::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1335 [
1336 'groupName' => 'msg_tpl_workflow_case',
1337 'valueName' => 'case_activity',
1338 'contactId' => $info['contact_id'] ?? NULL,
1339 'tplParams' => $tplParams,
1340 'from' => $receiptFrom,
1341 'toName' => $displayName,
1342 'toEmail' => $mail,
1343 'attachments' => $attachments,
1344 ]
1345 );
1346
1347 $activityParams['subject'] = ts('%1 - copy sent to %2', [1 => $activitySubject, 2 => $displayName]);
1348 $activityParams['details'] = $message;
1349
1350 if (!empty($result[$info['contact_id']])) {
1351 /*
1352 * Really only need to record one activity with all the targets combined.
1353 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1354 * but it's always the same content at the moment.
1355 */
1356 if (empty($recordedActivityParams)) {
1357 $recordedActivityParams = $activityParams;
1358 }
1359 else {
1360 $recordedActivityParams['subject'] .= "; $displayName";
1361 }
1362 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1363 }
1364 else {
1365 unset($result[CRM_Utils_Array::value('contact_id', $info)]);
1366 }
1367 }
1368
1369 if (!empty($recordedActivityParams)) {
1370 $activity = CRM_Activity_BAO_Activity::create($recordedActivityParams);
1371
1372 //create case_activity record if its case activity.
1373 if ($caseId) {
1374 $caseParams = [
1375 'activity_id' => $activity->id,
1376 'case_id' => $caseId,
1377 ];
1378 self::processCaseActivity($caseParams);
1379 }
1380 }
1381
1382 return $result;
1383 }
1384
1385 /**
1386 * Retrieve count of activities having a particular type, and
1387 * associated with a particular case.
1388 *
1389 * @param int $caseId
1390 * ID of the case.
1391 * @param int $activityTypeId
1392 * ID of the activity type.
1393 *
1394 * @return array
1395 */
1396 public static function getCaseActivityCount($caseId, $activityTypeId) {
1397 $queryParam = [
1398 1 => [$caseId, 'Integer'],
1399 2 => [$activityTypeId, 'Integer'],
1400 ];
1401 $query = "SELECT count(ca.id) as countact
1402 FROM civicrm_activity ca
1403 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1404 WHERE ca.activity_type_id = %2
1405 AND cca.case_id = %1
1406 AND ca.is_deleted = 0";
1407
1408 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1409 if ($dao->fetch()) {
1410 return $dao->countact;
1411 }
1412
1413 return FALSE;
1414 }
1415
1416 /**
1417 * Retrieve the scheduled activity type and date.
1418 *
1419 * @param array $cases
1420 * Array of contact and case id.
1421 *
1422 * @param string $type
1423 *
1424 * @return array
1425 * Array of scheduled activity type and date
1426 *
1427 *
1428 */
1429 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1430 $userID = CRM_Core_Session::getLoggedInContactID();
1431
1432 $caseID = implode(',', $cases['case_id']);
1433 $contactID = implode(',', $cases['contact_id']);
1434
1435 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1436 AND civicrm_case.id IN( {$caseID})
1437 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1438
1439 $query = self::getCaseActivityQuery($type, $userID, $condition);
1440 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id');
1441
1442 $res = CRM_Core_DAO::executeQuery($query);
1443
1444 $activityInfo = [];
1445 while ($res->fetch()) {
1446 if ($type == 'upcoming') {
1447 $activityInfo[$res->case_id]['date'] = $res->activity_date_time;
1448 $activityInfo[$res->case_id]['type'] = $activityTypes[$res->activity_type_id] ?? NULL;
1449 }
1450 else {
1451 $activityInfo[$res->case_id]['date'] = $res->activity_date_time;
1452 $activityInfo[$res->case_id]['type'] = $activityTypes[$res->activity_type_id] ?? NULL;
1453 }
1454 }
1455
1456 return $activityInfo;
1457 }
1458
1459 /**
1460 * Combine all the exportable fields from the lower levels object.
1461 *
1462 * @return array
1463 * array of exportable Fields
1464 */
1465 public static function &exportableFields() {
1466 if (!self::$_exportableFields) {
1467 if (!self::$_exportableFields) {
1468 self::$_exportableFields = [];
1469 }
1470
1471 $fields = CRM_Case_DAO_Case::export();
1472 $fields['case_role'] = ['title' => ts('Role in Case')];
1473 $fields['case_type'] = [
1474 'title' => ts('Case Type'),
1475 'name' => 'case_type',
1476 ];
1477 $fields['case_status'] = [
1478 'title' => ts('Case Status'),
1479 'name' => 'case_status',
1480 ];
1481
1482 // add custom data for cases
1483 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Case'));
1484
1485 self::$_exportableFields = $fields;
1486 }
1487 return self::$_exportableFields;
1488 }
1489
1490 /**
1491 * Restore the record that are associated with this case.
1492 *
1493 * @param int $caseId
1494 * Id of the case to restore.
1495 *
1496 * @return bool
1497 */
1498 public static function restoreCase($caseId) {
1499 //restore activities
1500 $activities = self::getCaseActivityDates($caseId);
1501 if ($activities) {
1502 foreach ($activities as $value) {
1503 CRM_Activity_BAO_Activity::restoreActivity($value);
1504 }
1505 }
1506 //restore case
1507 $case = new CRM_Case_DAO_Case();
1508 $case->id = $caseId;
1509 $case->is_deleted = 0;
1510 $case->save();
1511
1512 //CRM-7364, enable relationships
1513 self::enableDisableCaseRelationships($caseId, TRUE);
1514 return TRUE;
1515 }
1516
1517 /**
1518 * @param array $groupInfo
1519 * @param null $sort
1520 * @param bool $showLinks
1521 * @param bool $returnOnlyCount
1522 * @param int $offset
1523 * @param int $rowCount
1524 *
1525 * @return array
1526 */
1527 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = FALSE, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1528 $globalContacts = [];
1529
1530 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1531 $settings = $settingsProcessor->run();
1532 if (!empty($settings)) {
1533 $groupInfo['name'] = $settings['groupname'];
1534 if ($groupInfo['name']) {
1535 $searchParams = ['name' => $groupInfo['name']];
1536 $results = [];
1537 CRM_Contact_BAO_Group::retrieve($searchParams, $results);
1538 if ($results) {
1539 $groupInfo['id'] = $results['id'];
1540 $groupInfo['title'] = $results['title'];
1541 $params = [['group', '=', $groupInfo['id'], 0, 0]];
1542 $return = ['contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1];
1543 list($globalContacts) = CRM_Contact_BAO_Query::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount, FALSE);
1544
1545 if ($returnOnlyCount) {
1546 return $globalContacts;
1547 }
1548
1549 if ($showLinks) {
1550 foreach ($globalContacts as $idx => $contact) {
1551 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1552 }
1553 }
1554 }
1555 }
1556 }
1557 return $globalContacts;
1558 }
1559
1560 /**
1561 * Convenience function to get both case contacts and global in one array.
1562 *
1563 * @param int $caseId
1564 *
1565 * @return array
1566 */
1567 public static function getRelatedAndGlobalContacts($caseId) {
1568 $relatedContacts = self::getRelatedContacts($caseId);
1569
1570 $groupInfo = [];
1571 $globalContacts = self::getGlobalContacts($groupInfo);
1572
1573 //unset values which are not required.
1574 foreach ($globalContacts as $k => & $v) {
1575 unset($v['email_id']);
1576 unset($v['group_contact_id']);
1577 unset($v['status']);
1578 unset($v['phone']);
1579 $v['role'] = $groupInfo['title'];
1580 }
1581 //include multiple listings for the same contact/different roles.
1582 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1583 return $relatedGlobalContacts;
1584 }
1585
1586 /**
1587 * Get Case ActivitiesDueDates with given criteria.
1588 *
1589 * @param int $caseID
1590 * Case id.
1591 * @param array $criteriaParams
1592 * Given criteria.
1593 * @param bool $latestDate
1594 * If set newest or oldest date is selected.
1595 *
1596 * @return array
1597 * case activities due dates
1598 *
1599 */
1600 public static function getCaseActivityDates($caseID, $criteriaParams = [], $latestDate = FALSE) {
1601 $values = [];
1602 $selectDate = " ca.activity_date_time";
1603 $where = $groupBy = ' ';
1604
1605 if (!$caseID) {
1606 return NULL;
1607 }
1608
1609 if ($latestDate) {
1610 if (!empty($criteriaParams['activity_type_id'])) {
1611 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type::escape($criteriaParams['activity_type_id'], 'Integer');
1612 $where .= " AND ca.is_current_revision = 1";
1613 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1614 }
1615
1616 if (!empty($criteriaParams['newest'])) {
1617 $selectDate = " max(ca.activity_date_time) ";
1618 }
1619 else {
1620 $selectDate = " min(ca.activity_date_time) ";
1621 }
1622 }
1623
1624 $query = "SELECT ca.id, {$selectDate} as activity_date
1625 FROM civicrm_activity ca
1626 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1627 WHERE cc.id = %1 {$where} {$groupBy}";
1628
1629 $params = [1 => [$caseID, 'Integer']];
1630 $dao = CRM_Core_DAO::executeQuery($query, $params);
1631
1632 while ($dao->fetch()) {
1633 $values[$dao->id]['id'] = $dao->id;
1634 $values[$dao->id]['activity_date'] = $dao->activity_date;
1635 }
1636 return $values;
1637 }
1638
1639 /**
1640 * Create activities when Case or Other roles assigned/modified/deleted.
1641 *
1642 * @param int $caseId
1643 * @param int $relationshipId
1644 * Relationship id.
1645 * @param int $relContactId
1646 * Case role assignee contactId.
1647 * @param int $contactId
1648 */
1649 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1650 if (!$caseId || !$relationshipId || empty($relationshipId)) {
1651 return;
1652 }
1653
1654 $queryParam = [];
1655 if (is_array($relationshipId)) {
1656 $relationshipId = implode(',', $relationshipId);
1657 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1658 }
1659 else {
1660 $relationshipClause = " civicrm_relationship.id = %1";
1661 $queryParam[1] = [$relationshipId, 'Positive'];
1662 }
1663
1664 $query = "
1665 SELECT cc.display_name as clientName,
1666 cca.display_name as assigneeContactName,
1667 civicrm_relationship.case_id as caseId,
1668 civicrm_relationship_type.label_a_b as relation_a_b,
1669 civicrm_relationship_type.label_b_a as relation_b_a,
1670 civicrm_relationship.contact_id_b as rel_contact_id,
1671 civicrm_relationship.contact_id_a as assign_contact_id
1672 FROM civicrm_relationship_type, civicrm_relationship
1673 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1674 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1675 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1676
1677 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1678
1679 while ($dao->fetch()) {
1680 // The assignee is not the client.
1681 if ($dao->rel_contact_id != $contactId) {
1682 $caseRelationship = $dao->relation_a_b;
1683 $assigneContactName = $dao->clientName;
1684 $assigneContactIds[$dao->rel_contact_id] = $dao->rel_contact_id;
1685 }
1686 else {
1687 $caseRelationship = $dao->relation_b_a;
1688 $assigneContactName = $dao->assigneeContactName;
1689 $assigneContactIds[$dao->assign_contact_id] = $dao->assign_contact_id;
1690 }
1691 }
1692
1693 $session = CRM_Core_Session::singleton();
1694 $activityParams = [
1695 'source_contact_id' => $session->get('userID'),
1696 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1697 'activity_date_time' => date('YmdHis'),
1698 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1699 ];
1700
1701 //if $relContactId is passed, role is added or modified.
1702 if (!empty($relContactId)) {
1703 $activityParams['assignee_contact_id'] = $assigneContactIds;
1704 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1705 }
1706 else {
1707 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1708 }
1709
1710 $activityParams['activity_type_id'] = $activityTypeID;
1711
1712 $activity = CRM_Activity_BAO_Activity::create($activityParams);
1713
1714 //create case_activity record.
1715 $caseParams = [
1716 'activity_id' => $activity->id,
1717 'case_id' => $caseId,
1718 ];
1719
1720 CRM_Case_BAO_Case::processCaseActivity($caseParams);
1721 }
1722
1723 /**
1724 * Get case manger
1725 * contact which is assigned a case role of case manager.
1726 *
1727 * @param int $caseType
1728 * Case type.
1729 * @param int $caseId
1730 * Case id.
1731 *
1732 * @return string
1733 * html hyperlink of manager contact view page
1734 *
1735 */
1736 public static function getCaseManagerContact($caseType, $caseId) {
1737 if (!$caseType || !$caseId) {
1738 return NULL;
1739 }
1740
1741 $caseManagerName = '---';
1742 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1743
1744 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1745
1746 if (!empty($managerRoleId)) {
1747 if (substr($managerRoleId, -4) == '_a_b') {
1748 $managerRoleQuery = "
1749 SELECT civicrm_contact.id as casemanager_id,
1750 civicrm_contact.sort_name as casemanager,
1751 civicrm_relationship.is_active,
1752 civicrm_relationship.end_date
1753 FROM civicrm_contact
1754 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
1755 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1756 WHERE civicrm_case.id = %2";
1757 }
1758 if (substr($managerRoleId, -4) == '_b_a') {
1759 $managerRoleQuery = "
1760 SELECT civicrm_contact.id as casemanager_id,
1761 civicrm_contact.sort_name as casemanager,
1762 civicrm_relationship.is_active,
1763 civicrm_relationship.end_date
1764 FROM civicrm_contact
1765 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
1766 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1767 WHERE civicrm_case.id = %2";
1768 }
1769
1770 $managerRoleParams = [
1771 1 => [substr($managerRoleId, 0, -4), 'Integer'],
1772 2 => [$caseId, 'Integer'],
1773 ];
1774
1775 $dao = CRM_Core_DAO::executeQuery($managerRoleQuery, $managerRoleParams);
1776 // Pull an array of ALL case managers related to the case.
1777 $caseManagerNameArray = [];
1778 while ($dao->fetch()) {
1779 $caseManagerNameArray[$dao->casemanager_id]['casemanager_id'] = $dao->casemanager_id;
1780 $caseManagerNameArray[$dao->casemanager_id]['is_active'] = $dao->is_active;
1781 $caseManagerNameArray[$dao->casemanager_id]['end_date'] = $dao->end_date;
1782 $caseManagerNameArray[$dao->casemanager_id]['casemanager'] = $dao->casemanager;
1783 }
1784
1785 // Look for an active case manager, when no active case manager (like a closed case) show the most recently expired case manager.
1786 // Get the index of the manager if set to active
1787 $activekey = array_search(1, array_combine(array_keys($caseManagerNameArray), array_column($caseManagerNameArray, 'is_active')));
1788 if (!empty($activekey)) {
1789 $caseManagerName = sprintf('<a href="%s">%s</a>',
1790 CRM_Utils_System::url('civicrm/contact/view', ['cid' => $activekey]), $caseManagerNameArray[$activekey]['casemanager']
1791 );
1792 }
1793 elseif (!empty($caseManagerNameArray)) {
1794 // if there is no active case manager, get the index of the most recent end_date
1795 $max = array_search(max(array_combine(array_keys($caseManagerNameArray), array_column($caseManagerNameArray, 'end_date'))), array_combine(array_keys($caseManagerNameArray), array_column($caseManagerNameArray, 'end_date')));
1796 $caseManagerName = sprintf('<a href="%s">%s</a>',
1797 CRM_Utils_System::url('civicrm/contact/view', ['cid' => $max]), $caseManagerNameArray[$max]['casemanager']
1798 );
1799 }
1800 }
1801
1802 return $caseManagerName;
1803 }
1804
1805 /**
1806 * @param int $contactId
1807 * @param bool $excludeDeleted
1808 *
1809 * @return int
1810 */
1811 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1812 $params = ['check_permissions' => TRUE];
1813 if ($excludeDeleted) {
1814 $params['is_deleted'] = 0;
1815 }
1816 if ($contactId) {
1817 $params['contact_id'] = $contactId;
1818 }
1819 try {
1820 return civicrm_api3('Case', 'getcount', $params);
1821 }
1822 catch (CiviCRM_API3_Exception $e) {
1823 // Lack of permissions will throw an exception
1824 return 0;
1825 }
1826 }
1827
1828 /**
1829 * Retrieve related case ids for given case.
1830 *
1831 * @param int $caseId
1832 * @param bool $excludeDeleted
1833 * Do not include deleted cases.
1834 *
1835 * @return array
1836 */
1837 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1838 //FIXME : do check for permissions.
1839
1840 if (!$caseId) {
1841 return [];
1842 }
1843
1844 $linkActType = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Link Cases');
1845 if (!$linkActType) {
1846 return [];
1847 }
1848
1849 $whereClause = "mainCase.id = %2";
1850 if ($excludeDeleted) {
1851 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1852 }
1853
1854 $query = "
1855 SELECT relCaseAct.case_id
1856 FROM civicrm_case mainCase
1857 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1858 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1859 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1860 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1861 WHERE $whereClause";
1862
1863 $dao = CRM_Core_DAO::executeQuery($query, [
1864 1 => [$linkActType, 'Integer'],
1865 2 => [$caseId, 'Integer'],
1866 ]);
1867 $relatedCaseIds = [];
1868 while ($dao->fetch()) {
1869 $relatedCaseIds[$dao->case_id] = $dao->case_id;
1870 }
1871
1872 return array_values($relatedCaseIds);
1873 }
1874
1875 /**
1876 * Retrieve related case details for given case.
1877 *
1878 * @param int $caseId
1879 * @param bool $excludeDeleted
1880 * Do not include deleted cases.
1881 *
1882 * @return array
1883 */
1884 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1885 $relatedCaseIds = self::getRelatedCaseIds($caseId, $excludeDeleted);
1886 $relatedCases = [];
1887
1888 if (!$relatedCaseIds) {
1889 return [];
1890 }
1891
1892 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1893 if ($excludeDeleted) {
1894 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1895 }
1896
1897 //filter for permissioned cases.
1898 $filterCases = [];
1899 $doFilterCases = FALSE;
1900 if (!CRM_Core_Permission::check('access all cases and activities')) {
1901 $doFilterCases = TRUE;
1902 $filterCases = CRM_Case_BAO_Case::getCases(FALSE);
1903 }
1904
1905 //2. fetch the details of related cases.
1906 $query = "
1907 SELECT relCase.id as id,
1908 civicrm_case_type.title as case_type,
1909 client.display_name as client_name,
1910 client.id as client_id,
1911 relCase.status_id
1912 FROM civicrm_case relCase
1913 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1914 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1915 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1916 WHERE {$whereClause}";
1917
1918 $dao = CRM_Core_DAO::executeQuery($query);
1919 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=");
1920 $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
1921 $statuses = CRM_Case_BAO_Case::buildOptions('status_id');
1922
1923 while ($dao->fetch()) {
1924 $caseView = NULL;
1925 if (!$doFilterCases || array_key_exists($dao->id, $filterCases)) {
1926 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
1927 $caseViewUrl = CRM_Utils_System::url("civicrm/contact/view/case", $caseViewStr);
1928 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
1929 }
1930 $clientView = $dao->client_name;
1931 if ($hasViewContact) {
1932 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
1933 }
1934
1935 $relatedCases[$dao->id] = [
1936 'case_id' => $dao->id,
1937 'case_type' => $dao->case_type,
1938 'client_name' => $clientView,
1939 'status_id' => $dao->status_id,
1940 'case_status' => $statuses[$dao->status_id],
1941 'links' => $caseView,
1942 ];
1943 }
1944
1945 return $relatedCases;
1946 }
1947
1948 /**
1949 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
1950 *
1951 * @param int $mainContactId
1952 * @param int $otherContactId
1953 *
1954 * @see CRM_Dedupe_Merger::cpTables()
1955 *
1956 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
1957 *
1958 */
1959 public static function mergeContacts($mainContactId, $otherContactId) {
1960 self::mergeCases($mainContactId, NULL, $otherContactId);
1961 }
1962
1963 /**
1964 * Function perform two task.
1965 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
1966 * 2. Merge two cases of same contact - follow CRM-5598 rules.
1967 *
1968 * @param int $mainContactId
1969 * Contact id of main contact record.
1970 * @param int $mainCaseId
1971 * Case id of main case record.
1972 * @param int $otherContactId
1973 * Contact id of record which is going to merge.
1974 * @param int $otherCaseId
1975 * Case id of record which is going to merge.
1976 *
1977 * @param bool $changeClient
1978 *
1979 * @return int|null
1980 * @throws \CRM_Core_Exception
1981 */
1982 public static function mergeCases(
1983 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
1984 $otherCaseId = NULL, $changeClient = FALSE) {
1985 $moveToTrash = TRUE;
1986
1987 $duplicateContacts = FALSE;
1988 if ($mainContactId && $otherContactId &&
1989 $mainContactId != $otherContactId
1990 ) {
1991 $duplicateContacts = TRUE;
1992 }
1993
1994 $duplicateCases = FALSE;
1995 if ($mainCaseId && $otherCaseId &&
1996 $mainCaseId != $otherCaseId
1997 ) {
1998 $duplicateCases = TRUE;
1999 }
2000
2001 $mainCaseIds = [];
2002 if (!$duplicateContacts && !$duplicateCases) {
2003 return $mainCaseIds;
2004 }
2005
2006 $activityTypes = CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate');
2007 $completedActivityStatus = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
2008 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2009 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2010 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2011 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2012
2013 $processCaseIds = [$otherCaseId];
2014 if ($duplicateContacts && !$duplicateCases) {
2015 if ($changeClient) {
2016 $processCaseIds = [$mainCaseId];
2017 }
2018 else {
2019 //get all case ids for other contact.
2020 $processCaseIds = self::retrieveCaseIdsByContactId($otherContactId, TRUE);
2021 }
2022 if (!is_array($processCaseIds)) {
2023 return;
2024 }
2025 }
2026
2027 $session = CRM_Core_Session::singleton();
2028 $currentUserId = $session->get('userID');
2029
2030 CRM_Utils_Hook::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2031
2032 // copy all cases and connect to main contact id.
2033 foreach ($processCaseIds as $otherCaseId) {
2034 if ($duplicateContacts) {
2035 $mainCase = CRM_Core_DAO::copyGeneric('CRM_Case_DAO_Case', ['id' => $otherCaseId]);
2036 $mainCaseId = $mainCase->id;
2037 if (!$mainCaseId) {
2038 continue;
2039 }
2040
2041 $mainCaseIds[] = $mainCaseId;
2042 //insert record for case contact.
2043 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2044 $otherCaseContact->case_id = $otherCaseId;
2045 $otherCaseContact->find();
2046 while ($otherCaseContact->fetch()) {
2047 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2048 $mainCaseContact->case_id = $mainCaseId;
2049 $mainCaseContact->contact_id = $otherCaseContact->contact_id;
2050 if ($mainCaseContact->contact_id == $otherContactId) {
2051 $mainCaseContact->contact_id = $mainContactId;
2052 }
2053 //avoid duplicate object.
2054 if (!$mainCaseContact->find(TRUE)) {
2055 $mainCaseContact->save();
2056 }
2057 }
2058 }
2059 elseif (!$otherContactId) {
2060 $otherContactId = $mainContactId;
2061 }
2062
2063 if (!$mainCaseId || !$otherCaseId ||
2064 !$mainContactId || !$otherContactId
2065 ) {
2066 continue;
2067 }
2068
2069 // get all activities for other case.
2070 $otherCaseActivities = [];
2071 CRM_Core_DAO::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2072
2073 //for duplicate cases do not process singleton activities.
2074 $otherActivityIds = $singletonActivityIds = [];
2075 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2076 $otherActId = $otherIds['activity_id'] ?? NULL;
2077 if (!$otherActId || in_array($otherActId, $otherActivityIds)) {
2078 continue;
2079 }
2080 $otherActivityIds[] = $otherActId;
2081 }
2082 if ($duplicateCases) {
2083 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2084 $sql = "
2085 SELECT id
2086 FROM civicrm_activity
2087 WHERE activity_type_id = $openCaseType
2088 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2089 $dao = CRM_Core_DAO::executeQuery($sql);
2090 while ($dao->fetch()) {
2091 $singletonActivityIds[] = $dao->id;
2092 }
2093 }
2094 }
2095
2096 // migrate all activities and connect to main contact.
2097 $copiedActivityIds = $activityMappingIds = [];
2098 sort($otherActivityIds);
2099 foreach ($otherActivityIds as $otherActivityId) {
2100
2101 //for duplicate cases -
2102 //do not migrate singleton activities.
2103 if (!$otherActivityId || in_array($otherActivityId, $singletonActivityIds)) {
2104 continue;
2105 }
2106
2107 //migrate activity record.
2108 $otherActivity = new CRM_Activity_DAO_Activity();
2109 $otherActivity->id = $otherActivityId;
2110 if (!$otherActivity->find(TRUE)) {
2111 continue;
2112 }
2113
2114 $mainActVals = [];
2115 $mainActivity = new CRM_Activity_DAO_Activity();
2116 CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
2117 $mainActivity->copyValues($mainActVals);
2118 $mainActivity->id = NULL;
2119 $mainActivity->activity_date_time = $otherActivity->activity_date_time;
2120 $mainActivity->source_record_id = CRM_Utils_Array::value($mainActivity->source_record_id,
2121 $activityMappingIds
2122 );
2123
2124 $mainActivity->original_id = CRM_Utils_Array::value($mainActivity->original_id,
2125 $activityMappingIds
2126 );
2127
2128 $mainActivity->parent_id = CRM_Utils_Array::value($mainActivity->parent_id,
2129 $activityMappingIds
2130 );
2131 $mainActivity->save();
2132 $mainActivityId = $mainActivity->id;
2133 if (!$mainActivityId) {
2134 continue;
2135 }
2136
2137 $activityMappingIds[$otherActivityId] = $mainActivityId;
2138 // insert log of all activities
2139 CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
2140
2141 $copiedActivityIds[] = $otherActivityId;
2142
2143 //create case activity record.
2144 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2145 $mainCaseActivity->case_id = $mainCaseId;
2146 $mainCaseActivity->activity_id = $mainActivityId;
2147 $mainCaseActivity->save();
2148
2149 //migrate source activity.
2150 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2151 $otherSourceActivity->activity_id = $otherActivityId;
2152 $otherSourceActivity->record_type_id = $sourceID;
2153 $otherSourceActivity->find();
2154 while ($otherSourceActivity->fetch()) {
2155 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2156 $mainActivitySource->record_type_id = $sourceID;
2157 $mainActivitySource->activity_id = $mainActivityId;
2158 $mainActivitySource->contact_id = $otherSourceActivity->contact_id;
2159 if ($mainActivitySource->contact_id == $otherContactId) {
2160 $mainActivitySource->contact_id = $mainContactId;
2161 }
2162 //avoid duplicate object.
2163 if (!$mainActivitySource->find(TRUE)) {
2164 $mainActivitySource->save();
2165 }
2166 }
2167
2168 //migrate target activities.
2169 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2170 $otherTargetActivity->activity_id = $otherActivityId;
2171 $otherTargetActivity->record_type_id = $targetID;
2172 $otherTargetActivity->find();
2173 while ($otherTargetActivity->fetch()) {
2174 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2175 $mainActivityTarget->record_type_id = $targetID;
2176 $mainActivityTarget->activity_id = $mainActivityId;
2177 $mainActivityTarget->contact_id = $otherTargetActivity->contact_id;
2178 if ($mainActivityTarget->contact_id == $otherContactId) {
2179 $mainActivityTarget->contact_id = $mainContactId;
2180 }
2181 //avoid duplicate object.
2182 if (!$mainActivityTarget->find(TRUE)) {
2183 $mainActivityTarget->save();
2184 }
2185 }
2186
2187 //migrate assignee activities.
2188 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2189 $otherAssigneeActivity->activity_id = $otherActivityId;
2190 $otherAssigneeActivity->record_type_id = $assigneeID;
2191 $otherAssigneeActivity->find();
2192 while ($otherAssigneeActivity->fetch()) {
2193 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2194 $mainAssigneeActivity->activity_id = $mainActivityId;
2195 $mainAssigneeActivity->record_type_id = $assigneeID;
2196 $mainAssigneeActivity->contact_id = $otherAssigneeActivity->contact_id;
2197 if ($mainAssigneeActivity->contact_id == $otherContactId) {
2198 $mainAssigneeActivity->contact_id = $mainContactId;
2199 }
2200 //avoid duplicate object.
2201 if (!$mainAssigneeActivity->find(TRUE)) {
2202 $mainAssigneeActivity->save();
2203 }
2204 }
2205
2206 // copy custom fields and attachments
2207 $aparams = [
2208 'activityID' => $otherActivityId,
2209 'mainActivityId' => $mainActivityId,
2210 ];
2211 CRM_Activity_BAO_Activity::copyExtendedActivityData($aparams);
2212 }
2213
2214 //copy case relationship.
2215 if ($duplicateContacts) {
2216 //migrate relationship records.
2217 $otherRelationship = new CRM_Contact_DAO_Relationship();
2218 $otherRelationship->case_id = $otherCaseId;
2219 $otherRelationship->find();
2220 $otherRelationshipIds = [];
2221 while ($otherRelationship->fetch()) {
2222 $otherRelVals = [];
2223 $updateOtherRel = FALSE;
2224 CRM_Core_DAO::storeValues($otherRelationship, $otherRelVals);
2225
2226 $mainRelationship = new CRM_Contact_DAO_Relationship();
2227 $mainRelationship->copyValues($otherRelVals);
2228 $mainRelationship->id = NULL;
2229 $mainRelationship->case_id = $mainCaseId;
2230 if ($mainRelationship->contact_id_a == $otherContactId) {
2231 $updateOtherRel = TRUE;
2232 $mainRelationship->contact_id_a = $mainContactId;
2233 }
2234
2235 //case creator change only when we merge user contact.
2236 if ($mainRelationship->contact_id_b == $otherContactId) {
2237 //do not change creator for change client.
2238 if (!$changeClient) {
2239 $updateOtherRel = TRUE;
2240 $mainRelationship->contact_id_b = ($currentUserId) ? $currentUserId : $mainContactId;
2241 }
2242 }
2243 $mainRelationship->end_date = CRM_Utils_Date::isoToMysql($otherRelationship->end_date);
2244 $mainRelationship->start_date = CRM_Utils_Date::isoToMysql($otherRelationship->start_date);
2245
2246 //avoid duplicate object.
2247 if (!$mainRelationship->find(TRUE)) {
2248 $mainRelationship->save();
2249 }
2250
2251 //get the other relationship ids to update end date.
2252 if ($updateOtherRel) {
2253 $otherRelationshipIds[$otherRelationship->id] = $otherRelationship->id;
2254 }
2255 }
2256
2257 //update other relationships end dates
2258 if (!empty($otherRelationshipIds)) {
2259 $sql = 'UPDATE civicrm_relationship
2260 SET end_date = CURDATE()
2261 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2262 CRM_Core_DAO::executeQuery($sql);
2263 }
2264 }
2265
2266 //move other case to trash.
2267 $mergeCase = self::deleteCase($otherCaseId, $moveToTrash);
2268 if (!$mergeCase) {
2269 continue;
2270 }
2271
2272 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2273 if ($changeClient) {
2274 $mainContactDisplayName = CRM_Contact_BAO_Contact::displayName($mainContactId);
2275 $otherContactDisplayName = CRM_Contact_BAO_Contact::displayName($otherContactId);
2276
2277 $mergeActType = array_search('Reassigned Case', $activityTypes);
2278 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2279 [
2280 1 => $otherCaseId,
2281 2 => $otherContactDisplayName,
2282 3 => $mainContactDisplayName,
2283 4 => $mainCaseId,
2284 ]
2285 );
2286 }
2287 elseif ($duplicateContacts) {
2288 $mergeActType = array_search('Merge Case', $activityTypes);
2289 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2290 [
2291 1 => $otherCaseId,
2292 2 => $otherContactId,
2293 3 => $mainContactId,
2294 4 => $mainCaseId,
2295 ]
2296 );
2297 }
2298 else {
2299 $mergeActType = array_search('Merge Case', $activityTypes);
2300 $mergeActSubject = ts("Case %1 merged into case %2", [1 => $otherCaseId, 2 => $mainCaseId]);
2301 if (!empty($copiedActivityIds)) {
2302 $sql = '
2303 SELECT id, subject, activity_date_time, activity_type_id
2304 FROM civicrm_activity
2305 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2306 $dao = CRM_Core_DAO::executeQuery($sql);
2307 while ($dao->fetch()) {
2308 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2309 if ($dao->subject) {
2310 $mergeActSubjectDetails .= " :: {$dao->subject}";
2311 }
2312 $mergeActSubjectDetails .= "<br />";
2313 }
2314 }
2315 }
2316
2317 // Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2318 $activityParams = [
2319 'subject' => $mergeActSubject,
2320 'details' => $mergeActSubjectDetails,
2321 'status_id' => $completedActivityStatus,
2322 'activity_type_id' => $mergeActType,
2323 'source_contact_id' => $currentUserId,
2324 'activity_date_time' => date('YmdHis'),
2325 ];
2326
2327 $mergeActivity = CRM_Activity_BAO_Activity::create($activityParams);
2328 $mergeActivityId = $mergeActivity->id;
2329 if (!$mergeActivityId) {
2330 continue;
2331 }
2332
2333 //connect merge activity to case.
2334 $mergeCaseAct = [
2335 'case_id' => $mainCaseId,
2336 'activity_id' => $mergeActivityId,
2337 ];
2338
2339 self::processCaseActivity($mergeCaseAct);
2340 }
2341
2342 CRM_Utils_Hook::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2343
2344 return $mainCaseIds;
2345 }
2346
2347 /**
2348 * Validate contact permission for
2349 * edit/view on activity record and build links.
2350 *
2351 * @param array $tplParams
2352 * Params to be sent to template for sending email.
2353 * @param array $activityParams
2354 * Info of the activity.
2355 */
2356 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2357 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2358 'activity_type_id', 'id'
2359 );
2360
2361 if (!empty($tplParams['isCaseActivity'])) {
2362 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/case/activity',
2363 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2364 );
2365
2366 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/case/activity/view',
2367 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2368 );
2369
2370 $tplParams['manageCaseURL'] = CRM_Utils_System::url('civicrm/contact/view/case',
2371 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2372 );
2373 }
2374 else {
2375 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2376 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2377 );
2378
2379 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2380 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2381 );
2382 }
2383 }
2384
2385 /**
2386 * Validate contact permission for
2387 * given operation on activity record.
2388 *
2389 * @param int $activityId
2390 * Activity record id.
2391 * @param string $operation
2392 * User operation.
2393 * @param int $actTypeId
2394 * Activity type id.
2395 * @param int $contactId
2396 * Contact id/if not pass consider logged in.
2397 * @param bool $checkComponent
2398 * Do we need to check component enabled.
2399 *
2400 * @return bool
2401 */
2402 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2403 $allow = FALSE;
2404 if (!$actTypeId && $activityId) {
2405 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2406 }
2407
2408 if (!$activityId || !$operation || !$actTypeId) {
2409 return $allow;
2410 }
2411
2412 //do check for civicase component enabled.
2413 if ($checkComponent && !self::enabled()) {
2414 return $allow;
2415 }
2416
2417 //do check for cases.
2418 $caseActOperations = [
2419 'File On Case',
2420 'Link Cases',
2421 'Move To Case',
2422 'Copy To Case',
2423 ];
2424
2425 if (in_array($operation, $caseActOperations)) {
2426 static $caseCount;
2427 if (!isset($caseCount)) {
2428 try {
2429 $caseCount = civicrm_api3('Case', 'getcount', [
2430 'check_permissions' => TRUE,
2431 'status_id' => ['!=' => 'Closed'],
2432 'is_deleted' => 0,
2433 'end_date' => ['IS NULL' => 1],
2434 ]);
2435 }
2436 catch (CiviCRM_API3_Exception $e) {
2437 // Lack of permissions will throw an exception
2438 $caseCount = 0;
2439 }
2440 }
2441 if ($operation == 'File On Case') {
2442 $allow = !empty($caseCount);
2443 }
2444 else {
2445 $allow = ($caseCount > 1);
2446 }
2447 }
2448
2449 $actionOperations = ['view', 'edit', 'delete'];
2450 if (in_array($operation, $actionOperations)) {
2451
2452 //do cache when user has non/supper permission.
2453 static $allowOperations;
2454
2455 if (!is_array($allowOperations) ||
2456 !array_key_exists($operation, $allowOperations)
2457 ) {
2458
2459 if (!$contactId) {
2460 $session = CRM_Core_Session::singleton();
2461 $contactId = $session->get('userID');
2462 }
2463
2464 //check for permissions.
2465 $permissions = [
2466 'view' => [
2467 'access my cases and activities',
2468 'access all cases and activities',
2469 ],
2470 'edit' => [
2471 'access my cases and activities',
2472 'access all cases and activities',
2473 ],
2474 'delete' => ['delete activities'],
2475 ];
2476
2477 //check for core permission.
2478 $hasPermissions = [];
2479 $checkPermissions = $permissions[$operation] ?? NULL;
2480 if (is_array($checkPermissions)) {
2481 foreach ($checkPermissions as $per) {
2482 if (CRM_Core_Permission::check($per)) {
2483 $hasPermissions[$operation][] = $per;
2484 }
2485 }
2486 }
2487
2488 //has permissions.
2489 if (!empty($hasPermissions)) {
2490 //need to check activity object specific.
2491 if (in_array($operation, [
2492 'view',
2493 'edit',
2494 ])
2495 ) {
2496 //do we have supper permission.
2497 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2498 $allowOperations[$operation] = $allow = TRUE;
2499 }
2500 else {
2501 //user has only access to my cases and activity.
2502 //here object specific permmions come in picture.
2503
2504 //edit - contact must be source or assignee
2505 //view - contact must be source/assignee/target
2506 $isTarget = $isAssignee = $isSource = FALSE;
2507 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2508 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2509 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2510 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2511
2512 $target = new CRM_Activity_DAO_ActivityContact();
2513 $target->record_type_id = $targetID;
2514 $target->activity_id = $activityId;
2515 $target->contact_id = $contactId;
2516 if ($target->find(TRUE)) {
2517 $isTarget = TRUE;
2518 }
2519
2520 $assignee = new CRM_Activity_DAO_ActivityContact();
2521 $assignee->activity_id = $activityId;
2522 $assignee->record_type_id = $assigneeID;
2523 $assignee->contact_id = $contactId;
2524 if ($assignee->find(TRUE)) {
2525 $isAssignee = TRUE;
2526 }
2527
2528 $source = new CRM_Activity_DAO_ActivityContact();
2529 $source->activity_id = $activityId;
2530 $source->record_type_id = $sourceID;
2531 $source->contact_id = $contactId;
2532 if ($source->find(TRUE)) {
2533 $isSource = TRUE;
2534 }
2535
2536 if ($operation == 'edit') {
2537 if ($isAssignee || $isSource) {
2538 $allow = TRUE;
2539 }
2540 }
2541 if ($operation == 'view') {
2542 if ($isTarget || $isAssignee || $isSource) {
2543 $allow = TRUE;
2544 }
2545 }
2546 }
2547 }
2548 elseif (is_array($hasPermissions[$operation])) {
2549 $allowOperations[$operation] = $allow = TRUE;
2550 }
2551 }
2552 else {
2553 //contact do not have permission.
2554 $allowOperations[$operation] = FALSE;
2555 }
2556 }
2557 else {
2558 //use cache.
2559 //here contact might have supper/non permission.
2560 $allow = $allowOperations[$operation];
2561 }
2562 }
2563
2564 //do further only when operation is granted.
2565 if ($allow) {
2566 $actTypeName = CRM_Core_PseudoConstant::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $actTypeId);
2567
2568 //do not allow multiple copy / edit action.
2569 $singletonNames = [
2570 'Open Case',
2571 'Reassigned Case',
2572 'Merge Case',
2573 'Link Cases',
2574 'Assign Case Role',
2575 'Email',
2576 'Inbound Email',
2577 ];
2578
2579 //do not allow to delete these activities, CRM-4543
2580 $doNotDeleteNames = ['Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date'];
2581
2582 //allow edit operation.
2583 $allowEditNames = ['Open Case'];
2584
2585 if (CRM_Activity_BAO_Activity::checkEditInboundEmailsPermissions()) {
2586 $allowEditNames[] = 'Inbound Email';
2587 }
2588
2589 // do not allow File on Case
2590 $doNotFileNames = [
2591 'Open Case',
2592 'Change Case Type',
2593 'Change Case Status',
2594 'Change Case Start Date',
2595 'Reassigned Case',
2596 'Merge Case',
2597 'Link Cases',
2598 'Assign Case Role',
2599 ];
2600
2601 if (in_array($actTypeName, $singletonNames)) {
2602 $allow = FALSE;
2603 if ($operation == 'File On Case') {
2604 $allow = !in_array($actTypeName, $doNotFileNames);
2605 }
2606 if (in_array($operation, $actionOperations)) {
2607 $allow = TRUE;
2608 if ($operation == 'edit') {
2609 $allow = in_array($actTypeName, $allowEditNames);
2610 }
2611 elseif ($operation == 'delete') {
2612 $allow = !in_array($actTypeName, $doNotDeleteNames);
2613 }
2614 }
2615 }
2616 if ($allow && ($operation == 'delete') &&
2617 in_array($actTypeName, $doNotDeleteNames)
2618 ) {
2619 $allow = FALSE;
2620 }
2621
2622 if ($allow && ($operation == 'File On Case') &&
2623 in_array($actTypeName, $doNotFileNames)
2624 ) {
2625 $allow = FALSE;
2626 }
2627
2628 //check settings file for masking actions
2629 //on the basis the activity types
2630 //hide Edit link if activity type is NOT editable
2631 //(special case activities).CRM-5871
2632 if ($allow && in_array($operation, $actionOperations)) {
2633 static $actionFilter = [];
2634 if (!array_key_exists($operation, $actionFilter)) {
2635 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2636 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2637 }
2638 if (array_key_exists($operation, $actionFilter[$operation]) &&
2639 in_array($actTypeId, $actionFilter[$operation][$operation])
2640 ) {
2641 $allow = FALSE;
2642 }
2643 }
2644 }
2645
2646 return $allow;
2647 }
2648
2649 /**
2650 * Since we drop 'access CiviCase', allow access
2651 * if user has 'access my cases and activities'
2652 * or 'access all cases and activities'
2653 */
2654 public static function accessCiviCase() {
2655 if (!self::enabled()) {
2656 return FALSE;
2657 }
2658
2659 if (CRM_Core_Permission::check('access my cases and activities') ||
2660 CRM_Core_Permission::check('access all cases and activities')
2661 ) {
2662 return TRUE;
2663 }
2664
2665 return FALSE;
2666 }
2667
2668 /**
2669 * Verify user has permission to access a case.
2670 *
2671 * @param int $caseId
2672 * @param bool $denyClosed
2673 * Set TRUE if one wants closed cases to be treated as inaccessible.
2674 *
2675 * @return bool
2676 */
2677 public static function accessCase($caseId, $denyClosed = TRUE) {
2678 if (!$caseId || !self::enabled()) {
2679 return FALSE;
2680 }
2681
2682 $params = ['id' => $caseId, 'check_permissions' => TRUE];
2683 if ($denyClosed && !CRM_Core_Permission::check('access all cases and activities')) {
2684 $params['status_id'] = ['!=' => 'Closed'];
2685 }
2686 try {
2687 return (bool) civicrm_api3('Case', 'getcount', $params);
2688 }
2689 catch (CiviCRM_API3_Exception $e) {
2690 // Lack of permissions will throw an exception
2691 return FALSE;
2692 }
2693 }
2694
2695 /**
2696 * Check whether activity is a case Activity.
2697 *
2698 * @param int $activityID
2699 * Activity id.
2700 *
2701 * @return bool
2702 */
2703 public static function isCaseActivity($activityID) {
2704 $isCaseActivity = FALSE;
2705 if ($activityID) {
2706 $params = [1 => [$activityID, 'Integer']];
2707 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2708 if (CRM_Core_DAO::singleValueQuery($query, $params)) {
2709 $isCaseActivity = TRUE;
2710 }
2711 }
2712
2713 return $isCaseActivity;
2714 }
2715
2716 /**
2717 * Get all the case type ids currently in use.
2718 *
2719 * @return array
2720 */
2721 public static function getUsedCaseType() {
2722 static $caseTypeIds;
2723
2724 if (!is_array($caseTypeIds)) {
2725 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2726
2727 $dao = CRM_Core_DAO::executeQuery($query);
2728 $caseTypeIds = [];
2729 while ($dao->fetch()) {
2730 $typeId = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2731 $dao->case_type_id
2732 );
2733 $caseTypeIds[] = $typeId[1];
2734 }
2735 }
2736
2737 return $caseTypeIds;
2738 }
2739
2740 /**
2741 * Get all the case status ids currently in use.
2742 *
2743 * @return array
2744 */
2745 public static function getUsedCaseStatuses() {
2746 static $caseStatusIds;
2747
2748 if (!is_array($caseStatusIds)) {
2749 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2750
2751 $dao = CRM_Core_DAO::executeQuery($query);
2752 $caseStatusIds = [];
2753 while ($dao->fetch()) {
2754 $caseStatusIds[] = $dao->status_id;
2755 }
2756 }
2757
2758 return $caseStatusIds;
2759 }
2760
2761 /**
2762 * Get all the encounter medium ids currently in use.
2763 *
2764 * @return array
2765 */
2766 public static function getUsedEncounterMediums() {
2767 static $mediumIds;
2768
2769 if (!is_array($mediumIds)) {
2770 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2771
2772 $dao = CRM_Core_DAO::executeQuery($query);
2773 $mediumIds = [];
2774 while ($dao->fetch()) {
2775 $mediumIds[] = $dao->medium_id;
2776 }
2777 }
2778
2779 return $mediumIds;
2780 }
2781
2782 /**
2783 * Check case configuration.
2784 *
2785 * @param int $contactId
2786 *
2787 * @return array
2788 */
2789 public static function isCaseConfigured($contactId = NULL) {
2790 $configured = array_fill_keys(['configured', 'allowToAddNewCase', 'redirectToCaseAdmin'], FALSE);
2791
2792 //lets check for case configured.
2793 $allCasesCount = CRM_Case_BAO_Case::caseCount(NULL, FALSE);
2794 $configured['configured'] = (bool) $allCasesCount;
2795 if (!$configured['configured']) {
2796 //do check for case type and case status.
2797 $caseTypes = CRM_Case_PseudoConstant::caseType('title', FALSE);
2798 if (!empty($caseTypes)) {
2799 $configured['configured'] = TRUE;
2800 if (!$configured['configured']) {
2801 $caseStatuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
2802 if (!empty($caseStatuses)) {
2803 $configured['configured'] = TRUE;
2804 }
2805 }
2806 }
2807 }
2808 if ($configured['configured']) {
2809 //do check for active case type and case status.
2810 $caseTypes = CRM_Case_PseudoConstant::caseType();
2811 if (!empty($caseTypes)) {
2812 $caseStatuses = CRM_Case_PseudoConstant::caseStatus();
2813 if (!empty($caseStatuses)) {
2814 $configured['allowToAddNewCase'] = TRUE;
2815 }
2816 }
2817
2818 //do we need to redirect user to case admin.
2819 if (!$configured['allowToAddNewCase'] && $contactId) {
2820 //check for current contact case count.
2821 $currentContatCasesCount = CRM_Case_BAO_Case::caseCount($contactId);
2822 //redirect user to case admin page.
2823 if (!$currentContatCasesCount) {
2824 $configured['redirectToCaseAdmin'] = TRUE;
2825 }
2826 }
2827 }
2828
2829 return $configured;
2830 }
2831
2832 /**
2833 * Add/copy relationships, when new client is added for a case
2834 *
2835 * @param int $caseId
2836 * Case id.
2837 * @param int $contactId
2838 * Contact id / new client id.
2839 */
2840 public static function addCaseRelationships($caseId, $contactId) {
2841 // get the case role / relationships for the case
2842 $caseRelationships = new CRM_Contact_DAO_Relationship();
2843 $caseRelationships->case_id = $caseId;
2844 $caseRelationships->find();
2845 $relationshipTypes = [];
2846
2847 // make sure we don't add duplicate relationships of same relationship type.
2848 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id, $relationshipTypes)) {
2849 $values = [];
2850 CRM_Core_DAO::storeValues($caseRelationships, $values);
2851
2852 // add relationship for new client.
2853 $newRelationship = new CRM_Contact_DAO_Relationship();
2854 $newRelationship->copyValues($values);
2855 $newRelationship->id = NULL;
2856 $newRelationship->case_id = $caseId;
2857 $newRelationship->contact_id_a = $contactId;
2858 $newRelationship->end_date = CRM_Utils_Date::isoToMysql($caseRelationships->end_date);
2859 $newRelationship->start_date = CRM_Utils_Date::isoToMysql($caseRelationships->start_date);
2860
2861 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
2862 if (!$newRelationship->find(TRUE)) {
2863 $newRelationship->save();
2864 }
2865
2866 // store relationship type of newly created relationship
2867 $relationshipTypes[] = $caseRelationships->relationship_type_id;
2868 }
2869 }
2870
2871 /**
2872 * Get the list of clients for a case.
2873 *
2874 * @param int $caseId
2875 *
2876 * @return array
2877 * associated array with client ids
2878 */
2879 public static function getCaseClients($caseId) {
2880 $clients = [];
2881 $caseContact = new CRM_Case_DAO_CaseContact();
2882 $caseContact->case_id = $caseId;
2883 $caseContact->orderBy('id');
2884 $caseContact->find();
2885
2886 while ($caseContact->fetch()) {
2887 $clients[] = $caseContact->contact_id;
2888 }
2889
2890 return $clients;
2891 }
2892
2893 /**
2894 * @param int $caseId
2895 * @param string $direction
2896 * @param int $cid
2897 * @param int $relTypeId
2898 *
2899 * @throws \CRM_Core_Exception
2900 * @throws \CiviCRM_API3_Exception
2901 */
2902 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
2903 // Validate inputs
2904 if ($direction !== 'a' && $direction !== 'b') {
2905 throw new CRM_Core_Exception('Invalid relationship direction');
2906 }
2907
2908 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
2909 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
2910 $dao = CRM_Core_DAO::executeQuery($sql, [
2911 1 => [$caseId, 'Positive'],
2912 2 => [$cid, 'Positive'],
2913 3 => [$relTypeId, 'Positive'],
2914 ]);
2915 while ($dao->fetch()) {
2916 civicrm_api3('relationship', 'create', [
2917 'id' => $dao->id,
2918 'is_active' => 0,
2919 'end_date' => 'now',
2920 ]);
2921 }
2922 }
2923
2924 /**
2925 * Get options for a given case field.
2926 *
2927 * @param string $fieldName
2928 * @param string $context
2929 * @param array $props
2930 * Whatever is known about this dao object.
2931 *
2932 * @return array|bool
2933 * @throws \CiviCRM_API3_Exception
2934 *
2935 * @see CRM_Core_DAO::buildOptionsContext
2936 * @see CRM_Core_DAO::buildOptions
2937 *
2938 */
2939 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2940 $className = __CLASS__;
2941 $params = [];
2942 switch ($fieldName) {
2943 // This field is not part of this object but the api supports it
2944 case 'medium_id':
2945 $className = 'CRM_Activity_BAO_Activity';
2946 break;
2947
2948 // Filter status id by case type id
2949 case 'status_id':
2950 if (!empty($props['case_type_id'])) {
2951 $idField = is_numeric($props['case_type_id']) ? 'id' : 'name';
2952 $caseType = civicrm_api3('CaseType', 'getsingle', [$idField => $props['case_type_id'], 'return' => 'definition']);
2953 if (!empty($caseType['definition']['statuses'])) {
2954 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
2955 }
2956 }
2957 break;
2958 }
2959 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
2960 }
2961
2962 /**
2963 * @inheritDoc
2964 */
2965 public function addSelectWhereClause() {
2966 // We always return an array with these keys, even if they are empty,
2967 // because this tells the query builder that we have considered these fields for acls
2968 $clauses = [
2969 'id' => [],
2970 // Only case admins can view deleted cases
2971 'is_deleted' => CRM_Core_Permission::check('administer CiviCase') ? [] : ["= 0"],
2972 ];
2973 // Ensure the user has permission to view the case client
2974 $contactClause = CRM_Utils_SQL::mergeSubquery('Contact');
2975 if ($contactClause) {
2976 $contactClause = implode(' AND contact_id ', $contactClause);
2977 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
2978 }
2979 // The api gatekeeper ensures the user has at least "access my cases and activities"
2980 // so if they do not have permission to see all cases we'll assume they can only access their own
2981 if (!CRM_Core_Permission::check('access all cases and activities')) {
2982 $user = (int) CRM_Core_Session::getLoggedInContactID();
2983 $clauses['id'][] = "IN (
2984 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 (
2985 (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)
2986 )
2987 )";
2988 }
2989 CRM_Utils_Hook::selectWhereClause($this, $clauses);
2990 return $clauses;
2991 }
2992
2993 /**
2994 * CRM-20308: Method to get the contact id to use as from contact for email copy
2995 * 1. Activity Added by Contact's email address
2996 * 2. System Default From Address
2997 * 3. Default Organization Contact email address
2998 * 4. Logged in user
2999 *
3000 * @param int $activityID
3001 *
3002 * @return mixed $emailFromContactId
3003 *
3004 * @throws \CiviCRM_API3_Exception
3005 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3006 */
3007 public static function getReceiptFrom($activityID) {
3008 $name = $address = NULL;
3009
3010 if (!empty($activityID) && (Civi::settings()->get('allow_mail_from_logged_in_contact'))) {
3011 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3012 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3013 // There is always a 'Added by' contact for a activity,
3014 // so we can safely use ActivityContact.Getvalue API
3015 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', [
3016 'activity_id' => $activityID,
3017 'record_type_id' => 'Activity Source',
3018 'return' => 'contact_id',
3019 ]);
3020 list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($sourceContactId);
3021 }
3022
3023 // If 'From' email address not found for Source Activity Contact then
3024 // fetch the email from domain or logged in user.
3025 if (empty($address)) {
3026 list($name, $address) = CRM_Core_BAO_Domain::getDefaultReceiptFrom();
3027 }
3028
3029 return "$name <$address>";
3030 }
3031
3032 /**
3033 * @return array
3034 */
3035 public static function getEntityRefFilters() {
3036 $filters = [
3037 [
3038 'key' => 'case_id.case_type_id',
3039 'value' => ts('Case Type'),
3040 'entity' => 'Case',
3041 ],
3042 [
3043 'key' => 'case_id.status_id',
3044 'value' => ts('Case Status'),
3045 'entity' => 'Case',
3046 ],
3047 ];
3048 foreach (CRM_Contact_BAO_Contact::getEntityRefFilters() as $filter) {
3049 $filter += ['entity' => 'Contact'];
3050 $filter['key'] = 'contact_id.' . $filter['key'];
3051 $filters[] = $filter;
3052 }
3053 return $filters;
3054 }
3055
3056 /**
3057 * Fetch Case Role direction from Case Type
3058 */
3059 public static function getCaseRoleDirection($caseId, $roleTypeId = NULL) {
3060 try {
3061 $case = civicrm_api3('Case', 'getsingle', ['id' => $caseId]);
3062 }
3063 catch (CiviCRM_API3_Exception $e) {
3064 // Lack of permissions will throw an exception
3065 return 0;
3066 }
3067 if (!empty($case['case_type_id'])) {
3068 try {
3069 $caseType = civicrm_api3('CaseType', 'getsingle', ['id' => $case['case_type_id'], 'return' => ['definition']]);
3070 }
3071 catch (CiviCRM_API3_Exception $e) {
3072 // Lack of permissions will throw an exception
3073 return 'no case type found';
3074 }
3075 if (!empty($caseType['definition']['caseRoles'])) {
3076 $caseRoles = [];
3077 foreach ($caseType['definition']['caseRoles'] as $key => $roleDetails) {
3078 // Check if its an a_b label
3079 try {
3080 $relType = civicrm_api3('RelationshipType', 'getsingle', ['label_a_b' => $roleDetails['name']]);
3081 }
3082 catch (CiviCRM_API3_Exception $e) {
3083 }
3084 if (!empty($relType['id'])) {
3085 $roleDetails['id'] = $relType['id'];
3086 $roleDetails['direction'] = 'b_a';
3087 }
3088 // Check if its a b_a label
3089 try {
3090 $relTypeBa = civicrm_api3('RelationshipType', 'getsingle', ['label_b_a' => $roleDetails['name']]);
3091 }
3092 catch (CiviCRM_API3_Exception $e) {
3093 }
3094 if (!empty($relTypeBa['id'])) {
3095 if (!empty($roleDetails['direction'])) {
3096 $roleDetails['direction'] = 'bidrectional';
3097 }
3098 else {
3099 $roleDetails['id'] = $relTypeBa['id'];
3100 $roleDetails['direction'] = 'a_b';
3101 }
3102 }
3103 $caseRoles[$roleDetails['id']] = $roleDetails;
3104 }
3105 }
3106 return $caseRoles;
3107 }
3108 }
3109
3110 }