Merge pull request #18316 from civicrm/5.29
[civicrm-core.git] / CRM / Case / XMLProcessor / Process.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 class CRM_Case_XMLProcessor_Process extends CRM_Case_XMLProcessor {
18 protected $defaultAssigneeOptionsValues = [];
19
20 /**
21 * Run.
22 *
23 * @param string $caseType
24 * @param array $params
25 *
26 * @throws CRM_Core_Exception
27 */
28 public function run($caseType, &$params) {
29 $xml = $this->retrieve($caseType);
30
31 if ($xml === FALSE) {
32 $docLink = CRM_Utils_System::docURL2("user/case-management/set-up");
33 throw new CRM_Core_Exception(ts("Configuration file could not be retrieved for case type = '%1' %2.",
34 [1 => $caseType, 2 => $docLink]
35 ));
36 }
37
38 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
39 $this->_isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
40
41 $this->process($xml, $params);
42 }
43
44 /**
45 * @param $caseType
46 * @param $fieldSet
47 * @param bool $isLabel
48 * @param bool $maskAction
49 *
50 * @return array|bool|mixed
51 * @throws Exception
52 */
53 public function get($caseType, $fieldSet, $isLabel = FALSE, $maskAction = FALSE) {
54 $xml = $this->retrieve($caseType);
55 if ($xml === FALSE) {
56 $docLink = CRM_Utils_System::docURL2("user/case-management/set-up");
57 throw new CRM_Core_Exception(ts("Unable to load configuration file for the referenced case type: '%1' %2.",
58 [1 => $caseType, 2 => $docLink]
59 ));
60 }
61
62 switch ($fieldSet) {
63 case 'CaseRoles':
64 return $this->caseRoles($xml->CaseRoles);
65
66 case 'ActivitySets':
67 return $this->activitySets($xml->ActivitySets);
68
69 case 'ActivityTypes':
70 return $this->activityTypes($xml->ActivityTypes, FALSE, $isLabel, $maskAction);
71 }
72 }
73
74 /**
75 * @param $xml
76 * @param array $params
77 *
78 * @throws Exception
79 */
80 public function process($xml, &$params) {
81 $standardTimeline = $params['standardTimeline'] ?? NULL;
82 $activitySetName = $params['activitySetName'] ?? NULL;
83
84 if ('Open Case' == CRM_Utils_Array::value('activityTypeName', $params)) {
85 // create relationships for the ones that are required
86 foreach ($xml->CaseRoles as $caseRoleXML) {
87 foreach ($caseRoleXML->RelationshipType as $relationshipTypeXML) {
88 // simplexml treats node values differently than you'd expect,
89 // e.g. as an array
90 // Just using `if ($relationshipTypeXML->creator)` ends up always
91 // being true, so you have to cast to int or somehow force evaluation
92 // of the actual value. And casting to (bool) seems to behave
93 // differently on these objects than casting to (int).
94 if (!empty($relationshipTypeXML->creator)) {
95 if (!$this->createRelationships($relationshipTypeXML,
96 $params
97 )
98 ) {
99 throw new CRM_Core_Exception('Unable to create case relationships');
100 }
101 }
102 }
103 }
104 }
105
106 if ('Change Case Start Date' == CRM_Utils_Array::value('activityTypeName', $params)) {
107 // delete all existing activities which are non-empty
108 $this->deleteEmptyActivity($params);
109 }
110
111 foreach ($xml->ActivitySets as $activitySetsXML) {
112 foreach ($activitySetsXML->ActivitySet as $activitySetXML) {
113 if ($standardTimeline) {
114 if (!empty($activitySetXML->timeline)) {
115 return $this->processStandardTimeline($activitySetXML, $params);
116 }
117 }
118 elseif ($activitySetName) {
119 $name = (string) $activitySetXML->name;
120 if ($name == $activitySetName) {
121 return $this->processActivitySet($activitySetXML, $params);
122 }
123 }
124 }
125 }
126 }
127
128 /**
129 * @param $activitySetXML
130 * @param array $params
131 */
132 public function processStandardTimeline($activitySetXML, &$params) {
133 if ('Change Case Type' == CRM_Utils_Array::value('activityTypeName', $params)
134 && CRM_Utils_Array::value('resetTimeline', $params, TRUE)
135 ) {
136 // delete all existing activities which are non-empty
137 $this->deleteEmptyActivity($params);
138 }
139
140 foreach ($activitySetXML->ActivityTypes as $activityTypesXML) {
141 foreach ($activityTypesXML as $activityTypeXML) {
142 $this->createActivity($activityTypeXML, $params);
143 }
144 }
145 }
146
147 /**
148 * @param $activitySetXML
149 * @param array $params
150 */
151 public function processActivitySet($activitySetXML, &$params) {
152 foreach ($activitySetXML->ActivityTypes as $activityTypesXML) {
153 foreach ($activityTypesXML as $activityTypeXML) {
154 $this->createActivity($activityTypeXML, $params);
155 }
156 }
157 }
158
159 /**
160 * @param $caseRolesXML
161 * @param bool $isCaseManager
162 *
163 * @return array|mixed
164 */
165 public function &caseRoles($caseRolesXML, $isCaseManager = FALSE) {
166 // Look up relationship types according to the XML convention (described
167 // from perspective of non-client) but return the labels according to the UI
168 // convention (described from perspective of client)
169 $relationshipTypesToReturn = &$this->allRelationshipTypes(FALSE);
170
171 $result = [];
172 foreach ($caseRolesXML as $caseRoleXML) {
173 foreach ($caseRoleXML->RelationshipType as $relationshipTypeXML) {
174 list($relationshipTypeID,) = $this->locateNameOrLabel($relationshipTypeXML);
175 if ($relationshipTypeID === FALSE) {
176 continue;
177 }
178
179 if (!$isCaseManager) {
180 $result[$relationshipTypeID] = $relationshipTypesToReturn[$relationshipTypeID];
181 }
182 elseif ($relationshipTypeXML->manager == 1) {
183 return $relationshipTypeID;
184 }
185 }
186 }
187 return $result;
188 }
189
190 /**
191 * @param SimpleXMLElement $relationshipTypeXML
192 * @param array $params
193 *
194 * @return bool
195 * @throws CRM_Core_Exception
196 */
197 public function createRelationships($relationshipTypeXML, &$params) {
198
199 // get the relationship
200 list($relationshipType, $relationshipTypeName) = $this->locateNameOrLabel($relationshipTypeXML);
201 if ($relationshipType === FALSE) {
202 $docLink = CRM_Utils_System::docURL2("user/case-management/set-up");
203 throw new CRM_Core_Exception(ts('Relationship type %1, found in case configuration file, is not present in the database %2',
204 [1 => $relationshipTypeName, 2 => $docLink]
205 ));
206 }
207
208 $client = $params['clientID'];
209 if (!is_array($client)) {
210 $client = [$client];
211 }
212
213 foreach ($client as $key => $clientId) {
214 $relationshipParams = [
215 'relationship_type_id' => substr($relationshipType, 0, -4),
216 'is_active' => 1,
217 'case_id' => $params['caseID'],
218 'start_date' => date("Ymd"),
219 'end_date' => $params['relationship_end_date'] ?? NULL,
220 ];
221
222 if (substr($relationshipType, -4) == '_b_a') {
223 $relationshipParams['contact_id_b'] = $clientId;
224 $relationshipParams['contact_id_a'] = $params['creatorID'];
225 }
226 if (substr($relationshipType, -4) == '_a_b') {
227 $relationshipParams['contact_id_a'] = $clientId;
228 $relationshipParams['contact_id_b'] = $params['creatorID'];
229 }
230
231 if (!$this->createRelationship($relationshipParams)) {
232 throw new CRM_Core_Exception('Unable to create case relationship');
233 }
234 }
235 return TRUE;
236 }
237
238 /**
239 * @param array $params
240 *
241 * @return bool
242 */
243 public function createRelationship(&$params) {
244 $dao = new CRM_Contact_DAO_Relationship();
245 $dao->copyValues($params);
246 // only create a relationship if it does not exist
247 if (!$dao->find(TRUE)) {
248 $dao->save();
249 }
250 return TRUE;
251 }
252
253 /**
254 * @param $activityTypesXML
255 * @param bool $maxInst
256 * @param bool $isLabel
257 * @param bool $maskAction
258 *
259 * @return array
260 */
261 public function activityTypes($activityTypesXML, $maxInst = FALSE, $isLabel = FALSE, $maskAction = FALSE) {
262 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(TRUE, TRUE);
263 $result = [];
264 foreach ($activityTypesXML as $activityTypeXML) {
265 foreach ($activityTypeXML as $recordXML) {
266 $activityTypeName = (string) $recordXML->name;
267 $maxInstances = (string) $recordXML->max_instances;
268 $activityTypeInfo = $activityTypes[$activityTypeName] ?? NULL;
269
270 if ($activityTypeInfo['id']) {
271 if ($maskAction) {
272 if ($maskAction == 'edit' && '0' === (string) $recordXML->editable) {
273 $result[$maskAction][] = $activityTypeInfo['id'];
274 }
275 }
276 else {
277 if (!$maxInst) {
278 //if we want,labels of activities should be returned.
279 if ($isLabel) {
280 $result[$activityTypeInfo['id']] = $activityTypeInfo['label'];
281 }
282 else {
283 $result[$activityTypeInfo['id']] = $activityTypeName;
284 }
285 }
286 else {
287 if ($maxInstances) {
288 $result[$activityTypeName] = $maxInstances;
289 }
290 }
291 }
292 }
293 }
294 }
295
296 // call option value hook
297 CRM_Utils_Hook::optionValues($result, 'case_activity_type');
298
299 return $result;
300 }
301
302 /**
303 * @param SimpleXMLElement $caseTypeXML
304 *
305 * @return array<string> symbolic activity-type names
306 */
307 public function getDeclaredActivityTypes($caseTypeXML) {
308 $result = [];
309
310 if (!empty($caseTypeXML->ActivityTypes) && $caseTypeXML->ActivityTypes->ActivityType) {
311 foreach ($caseTypeXML->ActivityTypes->ActivityType as $activityTypeXML) {
312 $result[] = (string) $activityTypeXML->name;
313 }
314 }
315
316 if (!empty($caseTypeXML->ActivitySets) && $caseTypeXML->ActivitySets->ActivitySet) {
317 foreach ($caseTypeXML->ActivitySets->ActivitySet as $activitySetXML) {
318 if ($activitySetXML->ActivityTypes && $activitySetXML->ActivityTypes->ActivityType) {
319 foreach ($activitySetXML->ActivityTypes->ActivityType as $activityTypeXML) {
320 $result[] = (string) $activityTypeXML->name;
321 }
322 }
323 }
324 }
325
326 $result = array_unique($result);
327 sort($result);
328 return $result;
329 }
330
331 /**
332 * Relationships are straight from XML, described from perspective of non-client
333 *
334 * @param SimpleXMLElement $caseTypeXML
335 *
336 * @return array<string> symbolic relationship-type names
337 */
338 public function getDeclaredRelationshipTypes($caseTypeXML) {
339 $result = [];
340
341 if (!empty($caseTypeXML->CaseRoles) && $caseTypeXML->CaseRoles->RelationshipType) {
342 foreach ($caseTypeXML->CaseRoles->RelationshipType as $relTypeXML) {
343 list(, $relationshipTypeMachineName) = $this->locateNameOrLabel($relTypeXML);
344 $result[] = $relationshipTypeMachineName;
345 }
346 }
347
348 $result = array_unique($result);
349 sort($result);
350 return $result;
351 }
352
353 /**
354 * @param array $params
355 */
356 public function deleteEmptyActivity(&$params) {
357 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
358 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
359
360 $query = "
361 DELETE a
362 FROM civicrm_activity a
363 INNER JOIN civicrm_activity_contact t ON t.activity_id = a.id
364 INNER JOIN civicrm_case_activity ca on ca.activity_id = a.id
365 WHERE t.contact_id = %1
366 AND t.record_type_id = $targetID
367 AND a.is_auto = 1
368 AND a.is_current_revision = 1
369 AND ca.case_id = %2
370 ";
371 $sqlParams = [1 => [$params['clientID'], 'Integer'], 2 => [$params['caseID'], 'Integer']];
372 CRM_Core_DAO::executeQuery($query, $sqlParams);
373 }
374
375 /**
376 * @param array $params
377 *
378 * @return bool
379 */
380 public function isActivityPresent(&$params) {
381 $query = "
382 SELECT count(a.id)
383 FROM civicrm_activity a
384 INNER JOIN civicrm_case_activity ca on ca.activity_id = a.id
385 WHERE a.activity_type_id = %1
386 AND ca.case_id = %2
387 AND a.is_deleted = 0
388 ";
389
390 $sqlParams = [
391 1 => [$params['activityTypeID'], 'Integer'],
392 2 => [$params['caseID'], 'Integer'],
393 ];
394 $count = CRM_Core_DAO::singleValueQuery($query, $sqlParams);
395
396 // check for max instance
397 $caseType = CRM_Case_BAO_Case::getCaseType($params['caseID'], 'name');
398 $maxInstance = self::getMaxInstance($caseType, $params['activityTypeName']);
399
400 return $maxInstance ? ($count < $maxInstance ? FALSE : TRUE) : FALSE;
401 }
402
403 /**
404 * @param $activityTypeXML
405 * @param array $params
406 *
407 * @return bool
408 * @throws CRM_Core_Exception
409 * @throws Exception
410 */
411 public function createActivity($activityTypeXML, &$params) {
412 $activityTypeName = (string) $activityTypeXML->name;
413 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(TRUE, TRUE);
414 $activityTypeInfo = $activityTypes[$activityTypeName] ?? NULL;
415
416 if (!$activityTypeInfo) {
417 $docLink = CRM_Utils_System::docURL2("user/case-management/set-up");
418 throw new CRM_Core_Exception(ts('Activity type %1, found in case configuration file, is not present in the database %2',
419 [1 => $activityTypeName, 2 => $docLink]
420 ));
421 }
422
423 $activityTypeID = $activityTypeInfo['id'];
424
425 if (isset($activityTypeXML->status)) {
426 $statusName = (string) $activityTypeXML->status;
427 }
428 else {
429 $statusName = 'Scheduled';
430 }
431
432 $client = (array) $params['clientID'];
433
434 //set order
435 $orderVal = '';
436 if (isset($activityTypeXML->order)) {
437 $orderVal = (string) $activityTypeXML->order;
438 }
439
440 if ($activityTypeName == 'Open Case') {
441 $activityParams = [
442 'activity_type_id' => $activityTypeID,
443 'source_contact_id' => $params['creatorID'],
444 'is_auto' => FALSE,
445 'is_current_revision' => 1,
446 'subject' => !empty($params['subject']) ? $params['subject'] : $activityTypeName,
447 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $statusName),
448 'target_contact_id' => $client,
449 'medium_id' => $params['medium_id'] ?? NULL,
450 'location' => $params['location'] ?? NULL,
451 'details' => $params['details'] ?? NULL,
452 'duration' => $params['duration'] ?? NULL,
453 'weight' => $orderVal,
454 ];
455 }
456 else {
457 $activityParams = [
458 'activity_type_id' => $activityTypeID,
459 'source_contact_id' => $params['creatorID'],
460 'is_auto' => TRUE,
461 'is_current_revision' => 1,
462 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $statusName),
463 'target_contact_id' => $client,
464 'weight' => $orderVal,
465 ];
466 }
467
468 $activityParams['assignee_contact_id'] = $this->getDefaultAssigneeForActivity($activityParams, $activityTypeXML, $params['caseID']);
469
470 //parsing date to default preference format
471 $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time']);
472
473 if ($activityTypeName == 'Open Case') {
474 // we don't set activity_date_time for auto generated
475 // activities, but we want it to be set for open case.
476 $activityParams['activity_date_time'] = $params['activity_date_time'];
477 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
478 $activityParams['custom'] = $params['custom'];
479 }
480
481 // Add parameters for attachments
482
483 $numAttachments = Civi::settings()->get('max_attachments');
484 for ($i = 1; $i <= $numAttachments; $i++) {
485 $attachName = "attachFile_$i";
486 if (isset($params[$attachName]) && !empty($params[$attachName])) {
487 $activityParams[$attachName] = $params[$attachName];
488 }
489 }
490 }
491 else {
492 $activityDate = NULL;
493 //get date of reference activity if set.
494 if ($referenceActivityName = (string) $activityTypeXML->reference_activity) {
495
496 //we skip open case as reference activity.CRM-4374.
497 if (!empty($params['resetTimeline']) && $referenceActivityName == 'Open Case') {
498 $activityDate = $params['activity_date_time'];
499 }
500 else {
501 $referenceActivityInfo = $activityTypes[$referenceActivityName] ?? NULL;
502 if ($referenceActivityInfo['id']) {
503 $caseActivityParams = ['activity_type_id' => $referenceActivityInfo['id']];
504
505 //if reference_select is set take according activity.
506 if ($referenceSelect = (string) $activityTypeXML->reference_select) {
507 $caseActivityParams[$referenceSelect] = 1;
508 }
509
510 $referenceActivity = CRM_Case_BAO_Case::getCaseActivityDates($params['caseID'], $caseActivityParams, TRUE);
511
512 if (is_array($referenceActivity)) {
513 foreach ($referenceActivity as $aId => $details) {
514 $activityDate = $details['activity_date'] ?? NULL;
515 break;
516 }
517 }
518 }
519 }
520 }
521 if (!$activityDate) {
522 $activityDate = $params['activity_date_time'];
523 }
524 list($activity_date, $activity_time) = CRM_Utils_Date::setDateDefaults($activityDate);
525 $activityDateTime = CRM_Utils_Date::processDate($activity_date, $activity_time);
526 //add reference offset to date.
527 if ((int) $activityTypeXML->reference_offset) {
528 $activityDateTime = CRM_Utils_Date::intervalAdd('day', (int) $activityTypeXML->reference_offset,
529 $activityDateTime
530 );
531 }
532
533 $activityParams['activity_date_time'] = CRM_Utils_Date::format($activityDateTime);
534 }
535
536 // if same activity is already there, skip and dont touch
537 $params['activityTypeID'] = $activityTypeID;
538 $params['activityTypeName'] = $activityTypeName;
539 if ($this->isActivityPresent($params)) {
540 return TRUE;
541 }
542 $activityParams['case_id'] = $params['caseID'];
543 if (!empty($activityParams['is_auto'])) {
544 $activityParams['skipRecentView'] = TRUE;
545 }
546
547 // @todo - switch to using api & remove the parameter pre-wrangling above.
548 $activity = CRM_Activity_BAO_Activity::create($activityParams);
549
550 if (!$activity) {
551 throw new CRM_Core_Exception('Unable to create Activity');
552 }
553
554 // create case activity record
555 $caseParams = [
556 'activity_id' => $activity->id,
557 'case_id' => $params['caseID'],
558 ];
559 CRM_Case_BAO_Case::processCaseActivity($caseParams);
560 return TRUE;
561 }
562
563 /**
564 * Return the default assignee contact for the activity.
565 *
566 * @param array $activityParams
567 * @param object $activityTypeXML
568 * @param int $caseId
569 *
570 * @return int|null the ID of the default assignee contact or null if none.
571 */
572 protected function getDefaultAssigneeForActivity($activityParams, $activityTypeXML, $caseId) {
573 if (!isset($activityTypeXML->default_assignee_type)) {
574 return NULL;
575 }
576
577 $defaultAssigneeOptionsValues = $this->getDefaultAssigneeOptionValues();
578
579 switch ($activityTypeXML->default_assignee_type) {
580 case $defaultAssigneeOptionsValues['BY_RELATIONSHIP']:
581 return $this->getDefaultAssigneeByRelationship($activityParams, $activityTypeXML, $caseId);
582
583 break;
584 case $defaultAssigneeOptionsValues['SPECIFIC_CONTACT']:
585 return $this->getDefaultAssigneeBySpecificContact($activityTypeXML);
586
587 break;
588 case $defaultAssigneeOptionsValues['USER_CREATING_THE_CASE']:
589 return $activityParams['source_contact_id'];
590
591 break;
592 case $defaultAssigneeOptionsValues['NONE']:
593 default:
594 return NULL;
595 }
596 }
597
598 /**
599 * Fetches and caches the activity's default assignee options.
600 *
601 * @return array
602 */
603 protected function getDefaultAssigneeOptionValues() {
604 if (!empty($this->defaultAssigneeOptionsValues)) {
605 return $this->defaultAssigneeOptionsValues;
606 }
607
608 $defaultAssigneeOptions = civicrm_api3('OptionValue', 'get', [
609 'option_group_id' => 'activity_default_assignee',
610 'options' => ['limit' => 0],
611 ]);
612
613 foreach ($defaultAssigneeOptions['values'] as $option) {
614 $this->defaultAssigneeOptionsValues[$option['name']] = $option['value'];
615 }
616
617 return $this->defaultAssigneeOptionsValues;
618 }
619
620 /**
621 * Returns the default assignee for the activity by searching for the target's
622 * contact relationship type defined in the activity's details.
623 *
624 * @param array $activityParams
625 * @param object $activityTypeXML
626 * @param int $caseId
627 *
628 * @return int|null the ID of the default assignee contact or null if none.
629 */
630 protected function getDefaultAssigneeByRelationship($activityParams, $activityTypeXML, $caseId) {
631 $isDefaultRelationshipDefined = isset($activityTypeXML->default_assignee_relationship)
632 && preg_match('/\d+_[ab]_[ab]/', $activityTypeXML->default_assignee_relationship);
633
634 if (!$isDefaultRelationshipDefined) {
635 return NULL;
636 }
637
638 $targetContactId = is_array($activityParams['target_contact_id'])
639 ? CRM_Utils_Array::first($activityParams['target_contact_id'])
640 : $activityParams['target_contact_id'];
641 list($relTypeId, $a, $b) = explode('_', $activityTypeXML->default_assignee_relationship);
642
643 $params = [
644 'relationship_type_id' => $relTypeId,
645 "contact_id_$b" => $targetContactId,
646 'is_active' => 1,
647 'case_id' => $caseId,
648 'options' => ['limit' => 1],
649 ];
650
651 if ($this->isBidirectionalRelationshipType($relTypeId)) {
652 $params["contact_id_$a"] = $targetContactId;
653 $params['options']['or'] = [['contact_id_a', 'contact_id_b']];
654 }
655
656 $relationships = civicrm_api3('Relationship', 'get', $params);
657 if (empty($relationships['count'])) {
658 $params['case_id'] = ['IS NULL' => 1];
659 $relationships = civicrm_api3('Relationship', 'get', $params);
660 }
661
662 if ($relationships['count']) {
663 $relationship = CRM_Utils_Array::first($relationships['values']);
664
665 // returns the contact id on the other side of the relationship:
666 return (int) $relationship['contact_id_a'] === (int) $targetContactId
667 ? $relationship['contact_id_b']
668 : $relationship['contact_id_a'];
669 }
670 else {
671 return NULL;
672 }
673 }
674
675 /**
676 * Determines if the given relationship type is bidirectional or not by
677 * comparing their labels.
678 *
679 * @return bool
680 */
681 protected function isBidirectionalRelationshipType($relationshipTypeId) {
682 $relationshipTypeResult = civicrm_api3('RelationshipType', 'get', [
683 'id' => $relationshipTypeId,
684 'options' => ['limit' => 1],
685 ]);
686
687 if ($relationshipTypeResult['count'] === 0) {
688 return FALSE;
689 }
690
691 $relationshipType = CRM_Utils_Array::first($relationshipTypeResult['values']);
692
693 return $relationshipType['label_b_a'] === $relationshipType['label_a_b'];
694 }
695
696 /**
697 * Returns the activity's default assignee for a specific contact if the contact exists,
698 * otherwise returns null.
699 *
700 * @param object $activityTypeXML
701 *
702 * @return int|null
703 */
704 protected function getDefaultAssigneeBySpecificContact($activityTypeXML) {
705 if (!$activityTypeXML->default_assignee_contact) {
706 return NULL;
707 }
708
709 $contact = civicrm_api3('Contact', 'get', [
710 'id' => $activityTypeXML->default_assignee_contact,
711 ]);
712
713 if ($contact['count'] == 1) {
714 return $activityTypeXML->default_assignee_contact;
715 }
716
717 return NULL;
718 }
719
720 /**
721 * @param $activitySetsXML
722 *
723 * @return array
724 */
725 public static function activitySets($activitySetsXML) {
726 $result = [];
727 foreach ($activitySetsXML as $activitySetXML) {
728 foreach ($activitySetXML as $recordXML) {
729 $activitySetName = (string) $recordXML->name;
730 $activitySetLabel = (string) $recordXML->label;
731 $result[$activitySetName] = $activitySetLabel;
732 }
733 }
734
735 return $result;
736 }
737
738 /**
739 * @param $caseType
740 * @param string|null $activityTypeName
741 *
742 * @return array|bool|mixed
743 * @throws CRM_Core_Exception
744 */
745 public function getMaxInstance($caseType, $activityTypeName = NULL) {
746 $xml = $this->retrieve($caseType);
747
748 if ($xml === FALSE) {
749 throw new CRM_Core_Exception('Unable to locate xml definition for case type ' . $caseType);
750 }
751
752 $activityInstances = $this->activityTypes($xml->ActivityTypes, TRUE);
753 return $activityTypeName ? CRM_Utils_Array::value($activityTypeName, $activityInstances) : $activityInstances;
754 }
755
756 /**
757 * @param $caseType
758 *
759 * @return array|mixed
760 */
761 public function getCaseManagerRoleId($caseType) {
762 $xml = $this->retrieve($caseType);
763 return $this->caseRoles($xml->CaseRoles, TRUE);
764 }
765
766 /**
767 * @param string $caseType
768 *
769 * @return array<\Civi\CCase\CaseChangeListener>
770 */
771 public function getListeners($caseType) {
772 $xml = $this->retrieve($caseType);
773 $listeners = [];
774 if ($xml->Listeners && $xml->Listeners->Listener) {
775 foreach ($xml->Listeners->Listener as $listenerXML) {
776 $class = (string) $listenerXML;
777 $listeners[] = new $class();
778 }
779 }
780 return $listeners;
781 }
782
783 /**
784 * @return int
785 */
786 public function getRedactActivityEmail() {
787 return $this->getBoolSetting('civicaseRedactActivityEmail', 'RedactActivityEmail');
788 }
789
790 /**
791 * Retrieves AllowMultipleCaseClients setting.
792 *
793 * @return string
794 * 1 if allowed, 0 if not
795 */
796 public function getAllowMultipleCaseClients() {
797 return $this->getBoolSetting('civicaseAllowMultipleClients', 'AllowMultipleCaseClients');
798 }
799
800 /**
801 * Retrieves NaturalActivityTypeSort setting.
802 *
803 * @return string
804 * 1 if natural, 0 if alphabetic
805 */
806 public function getNaturalActivityTypeSort() {
807 return $this->getBoolSetting('civicaseNaturalActivityTypeSort', 'NaturalActivityTypeSort');
808 }
809
810 /**
811 * @param string $settingKey
812 * @param string $xmlTag
813 * @param mixed $default
814 *
815 * @return int
816 */
817 private function getBoolSetting($settingKey, $xmlTag, $default = 0) {
818 $setting = Civi::settings()->get($settingKey);
819 if ($setting !== 'default') {
820 return (int) $setting;
821 }
822 if ($xml = $this->retrieve("Settings")) {
823 return (string) $xml->{$xmlTag} ? 1 : 0;
824 }
825 return $default;
826 }
827
828 /**
829 * At some point name and label got mixed up for case roles.
830 * Check against known machine name values, and then if no match check
831 * against labels.
832 * This is subject to some edge cases, but we catch those with a system
833 * status check.
834 * We do this to avoid requiring people to update their xml files which can
835 * be stored in external files we can't/don't want to edit.
836 *
837 * @param SimpleXMLElement $xml
838 *
839 * @return array[bool|string,string]
840 */
841 public function locateNameOrLabel($xml) {
842 $lookupString = (string) $xml->name;
843
844 // Don't use pseudoconstant because we need everything both name and
845 // label and disabled types.
846 $relationshipTypes = civicrm_api3('RelationshipType', 'get', [
847 'options' => ['limit' => 0],
848 ])['values'];
849
850 // First look and see if it matches a machine name in the system.
851 // There are some edge cases here where we've actually been passed in a
852 // display label and it happens to match the machine name for a different
853 // db entry, but we have a system status check.
854 // But, we do want to check against the a_b version first, because of the
855 // way direction matters and that for bidirectional only one is present in
856 // the list where this eventually gets used, so return that first.
857 $relationshipTypeMachineNames = array_column($relationshipTypes, 'id', 'name_a_b');
858 if (isset($relationshipTypeMachineNames[$lookupString])) {
859 return ["{$relationshipTypeMachineNames[$lookupString]}_b_a", $lookupString];
860 }
861 $relationshipTypeMachineNames = array_column($relationshipTypes, 'id', 'name_b_a');
862 if (isset($relationshipTypeMachineNames[$lookupString])) {
863 return ["{$relationshipTypeMachineNames[$lookupString]}_a_b", $lookupString];
864 }
865
866 // Now at this point assume we've been passed a display label, so find
867 // what it matches and return the associated machine name. This is a bit
868 // trickier because suppose somebody has changed the display labels so
869 // that they are now the same, but the machine names are different. We
870 // don't know which to return and so while it's the right relationship type
871 // it might be the backwards direction. We have to pick one to try first.
872
873 $relationshipTypeDisplayLabels = array_column($relationshipTypes, 'id', 'label_a_b');
874 if (isset($relationshipTypeDisplayLabels[$lookupString])) {
875 return [
876 "{$relationshipTypeDisplayLabels[$lookupString]}_b_a",
877 $relationshipTypes[$relationshipTypeDisplayLabels[$lookupString]]['name_a_b'],
878 ];
879 }
880 $relationshipTypeDisplayLabels = array_column($relationshipTypes, 'id', 'label_b_a');
881 if (isset($relationshipTypeDisplayLabels[$lookupString])) {
882 return [
883 "{$relationshipTypeDisplayLabels[$lookupString]}_a_b",
884 $relationshipTypes[$relationshipTypeDisplayLabels[$lookupString]]['name_b_a'],
885 ];
886 }
887
888 // Just go with what we were passed in, even though it doesn't seem
889 // to match *anything*. This was what it did before.
890 return [FALSE, $lookupString];
891 }
892
893 }