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