Merge pull request #15790 from civicrm/5.20
[civicrm-core.git] / api / v3 / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This api exposes CiviCRM Case objects.
30 * Developed by woolman.org
31 *
32 * @package CiviCRM_APIv3
33 */
34
35 /**
36 * Open a new case, add client and manager roles, and standard timeline.
37 *
38 * @param array $params
39 *
40 * @code
41 * // REQUIRED for create:
42 * 'case_type_id' => int OR
43 * 'case_type' => str (provide one or the other)
44 * 'contact_id' => int // case client
45 * 'subject' => str
46 * // REQUIRED for update:
47 * 'id' => case Id
48 *
49 * //OPTIONAL
50 * 'medium_id' => int // see civicrm option values for possibilities
51 * 'creator_id' => int // case manager, default to the logged in user
52 * 'status_id' => int // defaults to 1 "ongoing"
53 * 'location' => str
54 * 'start_date' => str datestamp // defaults to: date('YmdHis')
55 * 'duration' => int // in minutes
56 * 'details' => str // html format
57 * @endcode
58 *
59 * @throws API_Exception
60 * @return array
61 * api result array
62 */
63 function civicrm_api3_case_create($params) {
64 _civicrm_api3_case_format_params($params);
65
66 if (empty($params['id'])) {
67 // Creating a new case, so make sure we have the necessary parameters
68 civicrm_api3_verify_mandatory($params, NULL, [
69 'contact_id',
70 'subject',
71 ['case_type', 'case_type_id'],
72 ]);
73 }
74 else {
75 // Update an existing case
76 // FIXME: Some of this logic should move to the BAO object?
77 // FIXME: Should we check if case with ID actually exists?
78
79 if (array_key_exists('creator_id', $params)) {
80 throw new API_Exception('You cannot update creator id');
81 }
82
83 $mergedCaseIds = $origContactIds = [];
84
85 // If a contact ID is specified we need to make sure this is the main contact ID for the case (and update if necessary)
86 if (!empty($params['contact_id'])) {
87 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
88
89 // Get the original contact ID for the case
90 // FIXME: Refactor as separate method to get contactId
91 if (count($origContactIds) > 1) {
92 // Multiple original contact IDs. Need to specify which one to use as a parameter
93 if (empty($params['orig_contact_id'])) {
94 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
95 }
96 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
97 throw new API_Exception('Invalid case contact id (orig_contact_id)');
98 }
99 $origContactId = $params['orig_contact_id'];
100 }
101 else {
102 // Only one original contact ID
103 $origContactId = CRM_Utils_Array::first($origContactIds);
104 }
105
106 // Get the specified main contact ID for the case
107 $mainContactId = CRM_Utils_Array::first($params['contact_id']);
108
109 // If the main contact ID is not in the list of original contact IDs for the case we need to change the main contact ID for the case
110 // This means we'll end up with a new case ID
111 if (!in_array($mainContactId, $origContactIds)) {
112 $mergedCaseIds = CRM_Case_BAO_Case::mergeCases($mainContactId, $params['id'], $origContactId, NULL, TRUE);
113 // If we merged cases then the first element will contain the case ID of the merged case - update that one
114 $params['id'] = CRM_Utils_Array::first($mergedCaseIds);
115 }
116 }
117 }
118
119 // Create/update the case
120 $caseBAO = CRM_Case_BAO_Case::create($params);
121
122 if (!$caseBAO) {
123 throw new API_Exception('Case not created. Please check input params.');
124 }
125
126 if (isset($params['contact_id']) && !isset($params['id'])) {
127 foreach ((array) $params['contact_id'] as $cid) {
128 $contactParams = ['case_id' => $caseBAO->id, 'contact_id' => $cid];
129 CRM_Case_BAO_CaseContact::create($contactParams);
130 }
131 }
132
133 if (!isset($params['id'])) {
134 // As the API was not passed an id we have created a new case.
135 // Only run the xmlProcessor for new cases to get all configuration for the new case.
136 _civicrm_api3_case_create_xmlProcessor($params, $caseBAO);
137 }
138
139 // return case
140 $values = [];
141 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
142
143 return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
144 }
145
146 /**
147 * When creating a new case, run the xmlProcessor to get all necessary params/configuration
148 * for the new case, as cases use an xml file to store their configuration.
149 *
150 * @param $params
151 * @param $caseBAO
152 *
153 * @throws \Exception
154 */
155 function _civicrm_api3_case_create_xmlProcessor($params, $caseBAO) {
156 // Format params for xmlProcessor
157 if (isset($caseBAO->id)) {
158 $params['id'] = $caseBAO->id;
159 }
160
161 // Initialize XML processor with $params
162 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
163 $xmlProcessorParams = [
164 'clientID' => CRM_Utils_Array::value('contact_id', $params),
165 'creatorID' => CRM_Utils_Array::value('creator_id', $params),
166 'standardTimeline' => 1,
167 'activityTypeName' => 'Open Case',
168 'caseID' => CRM_Utils_Array::value('id', $params),
169 'subject' => CRM_Utils_Array::value('subject', $params),
170 'location' => CRM_Utils_Array::value('location', $params),
171 'activity_date_time' => CRM_Utils_Array::value('start_date', $params),
172 'duration' => CRM_Utils_Array::value('duration', $params),
173 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
174 'details' => CRM_Utils_Array::value('details', $params),
175 'custom' => [],
176 'relationship_end_date' => CRM_Utils_Array::value('end_date', $params),
177 ];
178
179 // Do it! :-D
180 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
181 }
182
183 /**
184 * Adjust Metadata for Get Action.
185 *
186 * @param array $params
187 * Parameters determined by getfields.
188 */
189 function _civicrm_api3_case_get_spec(&$params) {
190 $params['contact_id'] = [
191 'api.aliases' => ['client_id'],
192 'title' => 'Case Client',
193 'description' => 'Contact id of one or more clients to retrieve cases for',
194 'type' => CRM_Utils_Type::T_INT,
195 ];
196 $params['activity_id'] = [
197 'title' => 'Case Activity',
198 'description' => 'Id of an activity in the case',
199 'type' => CRM_Utils_Type::T_INT,
200 ];
201 $params['tag_id'] = [
202 'title' => 'Tags',
203 'description' => 'Find cases with specified tags.',
204 'type' => 1,
205 'FKClassName' => 'CRM_Core_DAO_Tag',
206 'FKApiName' => 'Tag',
207 'supports_joins' => TRUE,
208 ];
209 }
210
211 /**
212 * Adjust Metadata for Create Action.
213 *
214 * @param array $params
215 * Array of parameters determined by getfields.
216 */
217 function _civicrm_api3_case_create_spec(&$params) {
218 $params['contact_id'] = [
219 'api.aliases' => ['client_id'],
220 'title' => 'Case Client',
221 'description' => 'Contact id of case client(s)',
222 'api.required' => 1,
223 'type' => CRM_Utils_Type::T_INT,
224 'FKApiName' => 'Contact',
225 ];
226 $params['status_id']['api.default'] = 1;
227 $params['status_id']['api.aliases'] = ['case_status'];
228 $params['creator_id']['api.default'] = 'user_contact_id';
229 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
230 $params['creator_id']['title'] = 'Case Created By';
231 $params['start_date']['api.default'] = 'now';
232 $params['medium_id'] = [
233 'name' => 'medium_id',
234 'title' => 'Activity Medium',
235 'type' => CRM_Utils_Type::T_INT,
236 ];
237 }
238
239 /**
240 * Adjust Metadata for Update action.
241 *
242 * @param array $params
243 * Array of parameters determined by getfields.
244 */
245 function _civicrm_api3_case_update_spec(&$params) {
246 $params['id']['api.required'] = 1;
247 }
248
249 /**
250 * Adjust Metadata for Delete action.
251 *
252 * @param array $params
253 * Array of parameters determined by getfields.
254 */
255 function _civicrm_api3_case_delete_spec(&$params) {
256 $params['id']['api.required'] = 1;
257 }
258
259 /**
260 * Get details of a particular case, or search for cases, depending on params.
261 *
262 * Please provide one (and only one) of the four get/search parameters:
263 *
264 * @param array $params
265 * 'id' => if set, will get all available info about a case, including contacts and activities
266 *
267 * // if no case_id provided, this function will use one of the following search parameters:
268 * 'client_id' => finds all cases with a specific client
269 * 'activity_id' => returns the case containing a specific activity
270 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
271 * $params CRM_Utils_SQL_Select $sql
272 * Other apis wishing to wrap & extend this one can pass in a $sql object with extra clauses
273 *
274 * @throws API_Exception
275 * @return array
276 * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
277 */
278 function civicrm_api3_case_get($params, $sql = NULL) {
279 $options = _civicrm_api3_get_options_from_params($params);
280 if (!is_a($sql, 'CRM_Utils_SQL_Select')) {
281 $sql = CRM_Utils_SQL_Select::fragment();
282 }
283
284 // Add clause to search by client
285 if (!empty($params['contact_id'])) {
286 // Legacy support - this field historically supports a nonstandard format of array(1,2,3) as a synonym for array('IN' => array(1,2,3))
287 if (is_array($params['contact_id'])) {
288 $operator = CRM_Utils_Array::first(array_keys($params['contact_id']));
289 if (!in_array($operator, \CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
290 $params['contact_id'] = ['IN' => $params['contact_id']];
291 }
292 }
293 else {
294 $params['contact_id'] = ['=' => $params['contact_id']];
295 }
296 $clause = CRM_Core_DAO::createSQLFilter('contact_id', $params['contact_id']);
297 $sql->where("a.id IN (SELECT case_id FROM civicrm_case_contact WHERE $clause)");
298 }
299
300 // Order by case contact (primary client)
301 // Ex: "contact_id", "contact_id.display_name", "contact_id.sort_name DESC".
302 if (!empty($options['sort']) && strpos($options['sort'], 'contact_id') !== FALSE) {
303 $sort = explode(', ', $options['sort']);
304 $contactSort = NULL;
305 foreach ($sort as $index => &$sortString) {
306 if (strpos($sortString, 'contact_id') === 0) {
307 $contactSort = $sortString;
308 $sortString = '(1)';
309 // Get sort field and direction
310 list($sortField, $dir) = array_pad(explode(' ', $contactSort), 2, 'ASC');
311 list(, $sortField) = array_pad(explode('.', $sortField), 2, 'id');
312 // Validate inputs
313 if (!array_key_exists($sortField, CRM_Contact_DAO_Contact::fieldKeys()) || ($dir != 'ASC' && $dir != 'DESC')) {
314 throw new API_Exception("Unknown field specified for sort. Cannot order by '$contactSort'");
315 }
316 $sql->orderBy("case_contact.$sortField $dir", NULL, $index);
317 }
318 }
319 // Remove contact sort params so the basic_get function doesn't see them
320 $params['options']['sort'] = implode(', ', $sort);
321 unset($params['option_sort'], $params['option.sort'], $params['sort']);
322 // Add necessary joins to the first case client
323 if ($contactSort) {
324 $sql->join('ccc', 'LEFT JOIN (SELECT * FROM civicrm_case_contact WHERE id IN (SELECT MIN(id) FROM civicrm_case_contact GROUP BY case_id)) AS ccc ON ccc.case_id = a.id');
325 $sql->join('case_contact', 'LEFT JOIN civicrm_contact AS case_contact ON ccc.contact_id = case_contact.id AND case_contact.is_deleted <> 1');
326 }
327 }
328
329 // Add clause to search by activity
330 if (!empty($params['activity_id'])) {
331 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
332 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
333 }
334 $activityId = $params['activity_id'];
335 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
336 if ($originalId) {
337 $activityId .= ',' . $originalId;
338 }
339 $sql
340 ->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
341 ->where("civicrm_case_activity.activity_id IN ($activityId)");
342 }
343
344 // Clause to search by tag
345 if (!empty($params['tag_id'])) {
346 $dummySpec = [];
347 _civicrm_api3_validate_integer($params, 'tag_id', $dummySpec, 'Case');
348 if (!is_array($params['tag_id'])) {
349 $params['tag_id'] = ['=' => $params['tag_id']];
350 }
351 $clause = \CRM_Core_DAO::createSQLFilter('tag_id', $params['tag_id']);
352 if ($clause) {
353 $sql->where('a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_case" AND !clause)', ['!clause' => $clause]);
354 }
355 }
356
357 $cases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), ['sequential' => 0] + $params, TRUE, 'Case', $sql);
358
359 if (empty($options['is_count']) && !empty($cases['values'])) {
360 // For historic reasons we return these by default only when fetching a case by id
361 if (!empty($params['id']) && is_numeric($params['id']) && empty($options['return'])) {
362 $options['return'] = [
363 'contacts' => 1,
364 'activities' => 1,
365 'contact_id' => 1,
366 ];
367 }
368
369 _civicrm_api3_case_read($cases['values'], $options);
370
371 // We disabled sequential to keep the list indexed for case_read(). Now add it back.
372 if (!empty($params['sequential'])) {
373 $cases['values'] = array_values($cases['values']);
374 }
375 }
376
377 return $cases;
378 }
379
380 /**
381 * Deprecated API.
382 *
383 * Use activity API instead.
384 *
385 * @param array $params
386 *
387 * @throws API_Exception
388 * @return array
389 */
390 function civicrm_api3_case_activity_create($params) {
391 require_once "api/v3/Activity.php";
392 return civicrm_api3_activity_create($params) + [
393 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
394 ];
395 }
396
397 /**
398 * Add a timeline to a case.
399 *
400 * @param array $params
401 *
402 * @throws API_Exception
403 * @return array
404 */
405 function civicrm_api3_case_addtimeline($params) {
406 $caseType = CRM_Case_BAO_Case::getCaseType($params['case_id'], 'name');
407 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
408 $xmlProcessorParams = [
409 'clientID' => CRM_Case_BAO_Case::getCaseClients($params['case_id']),
410 'creatorID' => $params['creator_id'],
411 'standardTimeline' => 0,
412 'activity_date_time' => $params['activity_date_time'],
413 'caseID' => $params['case_id'],
414 'caseType' => $caseType,
415 'activitySetName' => $params['timeline'],
416 ];
417 $xmlProcessor->run($caseType, $xmlProcessorParams);
418 return civicrm_api3_create_success();
419 }
420
421 /**
422 * Adjust Metadata for addtimeline action.
423 *
424 * @param array $params
425 * Array of parameters determined by getfields.
426 */
427 function _civicrm_api3_case_addtimeline_spec(&$params) {
428 $params['case_id'] = [
429 'title' => 'Case ID',
430 'description' => 'Id of case to update',
431 'type' => CRM_Utils_Type::T_INT,
432 'api.required' => 1,
433 ];
434 $params['timeline'] = [
435 'title' => 'Timeline',
436 'description' => 'Name of activity set',
437 'type' => CRM_Utils_Type::T_STRING,
438 'api.required' => 1,
439 ];
440 $params['activity_date_time'] = [
441 'api.default' => 'now',
442 'title' => 'Activity date time',
443 'description' => 'Timeline start date',
444 'type' => CRM_Utils_Type::T_DATE,
445 ];
446 $params['creator_id'] = [
447 'api.default' => 'user_contact_id',
448 'title' => 'Activity creator',
449 'description' => 'Contact id of timeline creator',
450 'type' => CRM_Utils_Type::T_INT,
451 ];
452 }
453
454 /**
455 * Merge 2 cases.
456 *
457 * @param array $params
458 *
459 * @throws API_Exception
460 * @return array
461 */
462 function civicrm_api3_case_merge($params) {
463 $clients1 = CRM_Case_BAO_Case::getCaseClients($params['case_id_1']);
464 $clients2 = CRM_Case_BAO_Case::getCaseClients($params['case_id_2']);
465 CRM_Case_BAO_Case::mergeCases($clients1[0], $params['case_id_1'], $clients2[0], $params['case_id_2']);
466 return civicrm_api3_create_success();
467 }
468
469 /**
470 * Adjust Metadata for merge action.
471 *
472 * @param array $params
473 * Array of parameters determined by getfields.
474 */
475 function _civicrm_api3_case_merge_spec(&$params) {
476 $params['case_id_1'] = [
477 'title' => 'Case ID 1',
478 'description' => 'Id of main case',
479 'type' => CRM_Utils_Type::T_INT,
480 'api.required' => 1,
481 ];
482 $params['case_id_2'] = [
483 'title' => 'Case ID 2',
484 'description' => 'Id of second case',
485 'type' => CRM_Utils_Type::T_INT,
486 'api.required' => 1,
487 ];
488 }
489
490 /**
491 * Declare deprecated api functions.
492 *
493 * @deprecated api notice
494 * @return array
495 * Array of deprecated actions
496 */
497 function _civicrm_api3_case_deprecation() {
498 return ['activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.'];
499 }
500
501 /**
502 * @deprecated Update a specified case. Use civicrm_api3_case_create() instead.
503 *
504 * @param array $params
505 * //REQUIRED:
506 * 'case_id' => int
507 *
508 * //OPTIONAL
509 * 'status_id' => int
510 * 'start_date' => str datestamp
511 * 'contact_id' => int // case client
512 *
513 * @throws API_Exception
514 * @return array
515 * api result array
516 */
517 function civicrm_api3_case_update($params) {
518 if (!isset($params['case_id']) && isset($params['id'])) {
519 $params['case_id'] = $params['id'];
520 }
521
522 //check parameters
523 civicrm_api3_verify_mandatory($params, NULL, ['id']);
524
525 // return error if modifying creator id
526 if (array_key_exists('creator_id', $params)) {
527 throw new API_Exception(ts('You cannot update creator id'));
528 }
529
530 $mCaseId = $origContactIds = [];
531
532 // get original contact id and creator id of case
533 if (!empty($params['contact_id'])) {
534 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
535 $origContactId = CRM_Utils_Array::first($origContactIds);
536 }
537
538 if (count($origContactIds) > 1) {
539 // check valid orig contact id
540 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
541 throw new API_Exception('Invalid case contact id (orig_contact_id)');
542 }
543 elseif (empty($params['orig_contact_id'])) {
544 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
545 }
546 $origContactId = $params['orig_contact_id'];
547 }
548
549 // check for same contact id for edit Client
550 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
551 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
552 }
553
554 if (!empty($mCaseId[0])) {
555 $params['id'] = $mCaseId[0];
556 }
557
558 $dao = new CRM_Case_BAO_Case();
559 $dao->id = $params['id'];
560
561 $dao->copyValues($params);
562 $dao->save();
563
564 $case = [];
565 _civicrm_api3_object_to_array($dao, $case);
566
567 return civicrm_api3_create_success([$dao->id => $case], $params, 'Case', 'update', $dao);
568 }
569
570 /**
571 * Delete a specified case.
572 *
573 * @param array $params
574 *
575 * @code
576 * //REQUIRED:
577 * 'id' => int
578 *
579 * //OPTIONAL
580 * 'move_to_trash' => bool (defaults to false)
581 * @endcode
582 *
583 * @throws API_Exception
584 * @return mixed
585 */
586 function civicrm_api3_case_delete($params) {
587 //check parameters
588 civicrm_api3_verify_mandatory($params, NULL, ['id']);
589
590 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
591 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
592 }
593 else {
594 throw new API_Exception('Could not delete case.');
595 }
596 }
597
598 /**
599 * Case.restore API specification
600 *
601 * @param array $spec description of fields supported by this API call
602 * @return void
603 */
604 function _civicrm_api3_case_restore_spec(&$spec) {
605 $result = civicrm_api3('Case', 'getfields', ['api_action' => 'delete']);
606 $spec = ['id' => $result['values']['id']];
607 }
608
609 /**
610 * Restore a specified case from the trash.
611 *
612 * @param array $params
613 * @throws API_Exception
614 * @return mixed
615 */
616 function civicrm_api3_case_restore($params) {
617 if (CRM_Case_BAO_Case::restoreCase($params['id'])) {
618 return civicrm_api3_create_success($params, $params, 'Case', 'restore');
619 }
620 else {
621 throw new API_Exception('Could not restore case.');
622 }
623 }
624
625 /**
626 * Augment case results with extra data.
627 *
628 * @param array $cases
629 * @param array $options
630 */
631 function _civicrm_api3_case_read(&$cases, $options) {
632 foreach ($cases as &$case) {
633 if (empty($options['return']) || !empty($options['return']['contact_id'])) {
634 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
635 // FIXME: Historically we return a 1-based array. Changing that risks breaking API clients that
636 // have been hardcoded to index "1", instead of the first array index (eg. using reset(), foreach etc)
637 $case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id'], NULL, 1);
638 }
639 if (!empty($options['return']['contacts'])) {
640 //get case contacts
641 $contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
642 $relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
643 $case['contacts'] = array_unique(array_merge($contacts, $relations), SORT_REGULAR);
644 }
645 if (!empty($options['return']['activities'])) {
646 // add case activities array - we'll populate them in bulk below
647 $case['activities'] = [];
648 }
649 // Properly render this joined field
650 if (!empty($options['return']['case_type_id.definition'])) {
651 if (!empty($case['case_type_id.definition'])) {
652 list($xml) = CRM_Utils_XML::parseString($case['case_type_id.definition']);
653 }
654 else {
655 $caseTypeId = !empty($case['case_type_id']) ? $case['case_type_id'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $case['id'], 'case_type_id');
656 $caseTypeName = !empty($case['case_type_id.name']) ? $case['case_type_id.name'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name');
657 $xml = CRM_Case_XMLRepository::singleton()->retrieve($caseTypeName);
658 }
659 $case['case_type_id.definition'] = [];
660 if ($xml) {
661 $case['case_type_id.definition'] = CRM_Case_BAO_CaseType::convertXmlToDefinition($xml);
662 }
663 }
664 }
665 // Bulk-load activities
666 if (!empty($options['return']['activities'])) {
667 $query = "SELECT case_id, activity_id FROM civicrm_case_activity WHERE case_id IN (%1)";
668 $params = [1 => [implode(',', array_keys($cases)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]];
669 $dao = CRM_Core_DAO::executeQuery($query, $params);
670 while ($dao->fetch()) {
671 $cases[$dao->case_id]['activities'][] = $dao->activity_id;
672 }
673 }
674 // Bulk-load tags. Supports joins onto the tag entity.
675 $tagGet = ['tag_id', 'entity_id'];
676 foreach (array_keys($options['return']) as $key) {
677 if (strpos($key, 'tag_id.') === 0) {
678 $tagGet[] = $key;
679 $options['return']['tag_id'] = 1;
680 }
681 }
682 if (!empty($options['return']['tag_id'])) {
683 $tags = civicrm_api3('EntityTag', 'get', [
684 'entity_table' => 'civicrm_case',
685 'entity_id' => ['IN' => array_keys($cases)],
686 'return' => $tagGet,
687 'options' => ['limit' => 0],
688 ]);
689 foreach ($tags['values'] as $tag) {
690 $key = (int) $tag['entity_id'];
691 unset($tag['entity_id'], $tag['id']);
692 $cases[$key]['tag_id'][$tag['tag_id']] = $tag;
693 }
694 }
695 }
696
697 /**
698 * Internal function to format create params for processing.
699 *
700 * @param array $params
701 */
702 function _civicrm_api3_case_format_params(&$params) {
703 // Format/include custom params
704 $values = [];
705 _civicrm_api3_custom_format_params($params, $values, 'Case');
706 $params = array_merge($params, $values);
707
708 // A single or multiple contact_id (client_id) can be passed as a value or array.
709 // Convert single value to array here to simplify processing in later functions which expect an array.
710 if (isset($params['contact_id'])) {
711 if (!is_array($params['contact_id'])) {
712 $params['contact_id'] = [$params['contact_id']];
713 }
714 }
715
716 // DEPRECATED: case_id - use id parameter instead.
717 if (!isset($params['id']) && isset($params['case_id'])) {
718 $params['id'] = $params['case_id'];
719 }
720
721 // When creating a new case, either case_type_id or case_type must be specified.
722 if (empty($params['case_type_id']) && empty($params['case_type'])) {
723 // If both case_type_id and case_type are empty we are updating a case so return here.
724 return;
725 }
726
727 // We are creating a new case
728 // figure out case_type_id from case_type and vice-versa
729 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
730 if (empty($params['case_type_id'])) {
731 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
732
733 // DEPRECATED: lookup by label for backward compatibility
734 if (!$params['case_type_id']) {
735 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
736 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
737 $params['case_type'] = $caseTypes[$params['case_type_id']];
738 }
739 }
740 elseif (empty($params['case_type'])) {
741 $params['case_type'] = $caseTypes[$params['case_type_id']];
742 }
743 }
744
745 /**
746 * It actually works a lot better to use the CaseContact api instead of the Case api
747 * for entityRef fields so we can perform the necessary joins,
748 * so we pass off getlist requests to the CaseContact api.
749 *
750 * @param array $params
751 * @return mixed
752 */
753 function civicrm_api3_case_getList($params) {
754 require_once 'api/v3/Generic/Getlist.php';
755 require_once 'api/v3/CaseContact.php';
756 //CRM:19956 - Assign case_id param if both id and case_id is passed to retrieve the case
757 if (!empty($params['id']) && !empty($params['params']) && !empty($params['params']['case_id'])) {
758 $params['params']['case_id'] = ['IN' => $params['id']];
759 unset($params['id']);
760 }
761 $params['id_field'] = 'case_id';
762 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
763 $params['description_field'] = [
764 'case_id',
765 'case_id.case_type_id.title',
766 'case_id.subject',
767 'case_id.status_id',
768 'case_id.start_date',
769 ];
770 $apiRequest = [
771 'version' => 3,
772 'entity' => 'CaseContact',
773 'action' => 'getlist',
774 'params' => $params,
775 ];
776 return civicrm_api3_generic_getList($apiRequest);
777 }
778
779 /**
780 * Needed due to the above override
781 * @param $params
782 * @param $apiRequest
783 */
784 function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
785 require_once 'api/v3/Generic/Getlist.php';
786 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
787 }