(NFC) Bring up API folder to style of future coder checker
[civicrm-core.git] / api / v3 / Case.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
b081365f 29 * This api exposes CiviCRM Case objects.
6a488035
TO
30 * Developed by woolman.org
31 *
32 * @package CiviCRM_APIv3
6a488035
TO
33 */
34
6a488035 35/**
244bbdd8 36 * Open a new case, add client and manager roles, and standard timeline.
6a488035 37 *
6c552737 38 * @param array $params
37b8953e 39 *
b081365f 40 * @code
ea2aa8ff 41 * // REQUIRED for create:
6a488035
TO
42 * 'case_type_id' => int OR
43 * 'case_type' => str (provide one or the other)
44 * 'contact_id' => int // case client
45 * 'subject' => str
ea2aa8ff 46 * // REQUIRED for update:
791a8dc4 47 * 'id' => case Id
6a488035
TO
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
b081365f 57 * @endcode
6a488035 58 *
784e85a1 59 * @throws API_Exception
a6c01b45 60 * @return array
72b3a70c 61 * api result array
6a488035
TO
62 */
63function civicrm_api3_case_create($params) {
6a488035
TO
64 _civicrm_api3_case_format_params($params);
65
da4d8910
MW
66 if (empty($params['id'])) {
67 // Creating a new case, so make sure we have the necessary parameters
cf8f0fff 68 civicrm_api3_verify_mandatory($params, NULL, [
7c31ae57
SL
69 'contact_id',
70 'subject',
71 ['case_type', 'case_type_id'],
72 ]);
6a488035 73 }
da4d8910
MW
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?
6a488035 78
da4d8910 79 if (array_key_exists('creator_id', $params)) {
ef76301b 80 throw new API_Exception('You cannot update creator id');
da4d8910
MW
81 }
82
cf8f0fff 83 $mergedCaseIds = $origContactIds = [];
da4d8910 84
ea2aa8ff 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)
da4d8910
MW
86 if (!empty($params['contact_id'])) {
87 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
da4d8910 88
ea2aa8ff
MW
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'];
2a3c0d28 100 }
ea2aa8ff
MW
101 else {
102 // Only one original contact ID
103 $origContactId = CRM_Utils_Array::first($origContactIds);
da4d8910 104 }
6a488035 105
ea2aa8ff
MW
106 // Get the specified main contact ID for the case
107 $mainContactId = CRM_Utils_Array::first($params['contact_id']);
da4d8910 108
ea2aa8ff
MW
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 }
da4d8910
MW
116 }
117 }
118
119 // Create/update the case
120 $caseBAO = CRM_Case_BAO_Case::create($params);
6a488035
TO
121
122 if (!$caseBAO) {
784e85a1 123 throw new API_Exception('Case not created. Please check input params.');
6a488035
TO
124 }
125
6e36c320 126 if (isset($params['contact_id']) && !isset($params['id'])) {
791a8dc4 127 foreach ((array) $params['contact_id'] as $cid) {
cf8f0fff 128 $contactParams = ['case_id' => $caseBAO->id, 'contact_id' => $cid];
791a8dc4
MW
129 CRM_Case_BAO_CaseContact::create($contactParams);
130 }
6a488035
TO
131 }
132
da4d8910 133 if (!isset($params['id'])) {
2a3c0d28
MW
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.
da4d8910
MW
136 _civicrm_api3_case_create_xmlProcessor($params, $caseBAO);
137 }
138
139 // return case
cf8f0fff 140 $values = [];
da4d8910
MW
141 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
142
da4d8910
MW
143 return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
144}
145
2a3c0d28
MW
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.
ea2aa8ff 149 *
2a3c0d28
MW
150 * @param $params
151 * @param $caseBAO
ea2aa8ff
MW
152 *
153 * @throws \Exception
2a3c0d28 154 */
da4d8910
MW
155function _civicrm_api3_case_create_xmlProcessor($params, $caseBAO) {
156 // Format params for xmlProcessor
ebf4aeaa
MW
157 if (isset($caseBAO->id)) {
158 $params['id'] = $caseBAO->id;
159 }
da4d8910 160
6a488035
TO
161 // Initialize XML processor with $params
162 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
cf8f0fff 163 $xmlProcessorParams = [
2a3c0d28
MW
164 'clientID' => CRM_Utils_Array::value('contact_id', $params),
165 'creatorID' => CRM_Utils_Array::value('creator_id', $params),
6a488035
TO
166 'standardTimeline' => 1,
167 'activityTypeName' => 'Open Case',
2a3c0d28
MW
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),
cf8f0fff 175 'custom' => [],
3717c347 176 'relationship_end_date' => CRM_Utils_Array::value('end_date', $params),
cf8f0fff 177 ];
6a488035
TO
178
179 // Do it! :-D
180 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
6a488035
TO
181}
182
11e09c59 183/**
2fb1dd66 184 * Adjust Metadata for Get Action.
6a488035 185 *
cf470720 186 * @param array $params
2fb1dd66 187 * Parameters determined by getfields.
6a488035
TO
188 */
189function _civicrm_api3_case_get_spec(&$params) {
cf8f0fff
CW
190 $params['contact_id'] = [
191 'api.aliases' => ['client_id'],
d142432b 192 'title' => 'Case Client',
48bdb3cd 193 'description' => 'Contact id of one or more clients to retrieve cases for',
d142432b 194 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
195 ];
196 $params['activity_id'] = [
48bdb3cd
CW
197 'title' => 'Case Activity',
198 'description' => 'Id of an activity in the case',
199 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
200 ];
201 $params['tag_id'] = [
9ef16723 202 'title' => 'Tags',
cde84d6f 203 'description' => 'Find cases with specified tags.',
9ef16723
CW
204 'type' => 1,
205 'FKClassName' => 'CRM_Core_DAO_Tag',
206 'FKApiName' => 'Tag',
207 'supports_joins' => TRUE,
cf8f0fff 208 ];
6a488035
TO
209}
210
11e09c59 211/**
2fb1dd66 212 * Adjust Metadata for Create Action.
6a488035 213 *
cf470720 214 * @param array $params
b081365f 215 * Array of parameters determined by getfields.
6a488035
TO
216 */
217function _civicrm_api3_case_create_spec(&$params) {
cf8f0fff
CW
218 $params['contact_id'] = [
219 'api.aliases' => ['client_id'],
d142432b 220 'title' => 'Case Client',
48bdb3cd 221 'description' => 'Contact id of case client(s)',
d142432b
EM
222 'api.required' => 1,
223 'type' => CRM_Utils_Type::T_INT,
6e36c320 224 'FKApiName' => 'Contact',
cf8f0fff 225 ];
6a488035 226 $params['status_id']['api.default'] = 1;
cf8f0fff 227 $params['status_id']['api.aliases'] = ['case_status'];
941feb14
EM
228 $params['creator_id']['api.default'] = 'user_contact_id';
229 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
b05e6d0d 230 $params['creator_id']['title'] = 'Case Created By';
ca11b9da 231 $params['start_date']['api.default'] = 'now';
cf8f0fff 232 $params['medium_id'] = [
16c0ec8d
CW
233 'name' => 'medium_id',
234 'title' => 'Activity Medium',
d142432b 235 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 236 ];
6a488035
TO
237}
238
11e09c59 239/**
2fb1dd66 240 * Adjust Metadata for Update action.
6a488035 241 *
cf470720 242 * @param array $params
b081365f 243 * Array of parameters determined by getfields.
6a488035
TO
244 */
245function _civicrm_api3_case_update_spec(&$params) {
246 $params['id']['api.required'] = 1;
247}
248
11e09c59 249/**
c1a920f1 250 * Adjust Metadata for Delete action.
6a488035 251 *
cf470720 252 * @param array $params
b081365f 253 * Array of parameters determined by getfields.
6a488035
TO
254 */
255function _civicrm_api3_case_delete_spec(&$params) {
256 $params['id']['api.required'] = 1;
257}
258
6a488035 259/**
211e2fca 260 * Get details of a particular case, or search for cases, depending on params.
6a488035
TO
261 *
262 * Please provide one (and only one) of the four get/search parameters:
263 *
6c552737
TO
264 * @param array $params
265 * 'id' => if set, will get all available info about a case, including contacts and activities
6a488035 266 *
6c552737
TO
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)
09f6c512
CW
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
6a488035 273 *
77b97be7 274 * @throws API_Exception
a6c01b45 275 * @return array
72b3a70c 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
6a488035 277 */
09f6c512 278function civicrm_api3_case_get($params, $sql = NULL) {
6a488035 279 $options = _civicrm_api3_get_options_from_params($params);
09f6c512
CW
280 if (!is_a($sql, 'CRM_Utils_SQL_Select')) {
281 $sql = CRM_Utils_SQL_Select::fragment();
282 }
48bdb3cd
CW
283
284 // Add clause to search by client
6a488035 285 if (!empty($params['contact_id'])) {
9808e205
CW
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)) {
cf8f0fff 290 $params['contact_id'] = ['IN' => $params['contact_id']];
6a488035
TO
291 }
292 }
9808e205 293 else {
cf8f0fff 294 $params['contact_id'] = ['=' => $params['contact_id']];
9808e205
CW
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)");
6a488035
TO
298 }
299
242220e2
CW
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;
4c6cc364 305 foreach ($sort as $index => &$sortString) {
242220e2
CW
306 if (strpos($sortString, 'contact_id') === 0) {
307 $contactSort = $sortString;
4c6cc364 308 $sortString = '(1)';
242220e2
CW
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 }
4c6cc364 316 $sql->orderBy("case_contact.$sortField $dir", NULL, $index);
242220e2
CW
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');
7a51786d 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');
242220e2
CW
326 }
327 }
328
48bdb3cd 329 // Add clause to search by activity
6a488035 330 if (!empty($params['activity_id'])) {
48bdb3cd 331 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
784e85a1 332 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
6a488035 333 }
48bdb3cd
CW
334 $activityId = $params['activity_id'];
335 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
336 if ($originalId) {
337 $activityId .= ',' . $originalId;
6a488035 338 }
48bdb3cd
CW
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)");
6a488035 342 }
f21557af 343
9ef16723
CW
344 // Clause to search by tag
345 if (!empty($params['tag_id'])) {
cf8f0fff 346 $dummySpec = [];
9ef16723
CW
347 _civicrm_api3_validate_integer($params, 'tag_id', $dummySpec, 'Case');
348 if (!is_array($params['tag_id'])) {
cf8f0fff 349 $params['tag_id'] = ['=' => $params['tag_id']];
9ef16723
CW
350 }
351 $clause = \CRM_Core_DAO::createSQLFilter('tag_id', $params['tag_id']);
352 if ($clause) {
cf8f0fff 353 $sql->where('a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_case" AND !clause)', ['!clause' => $clause]);
9ef16723
CW
354 }
355 }
356
cf8f0fff 357 $cases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), ['sequential' => 0] + $params, TRUE, 'Case', $sql);
a54ac083 358
9ef16723 359 if (empty($options['is_count']) && !empty($cases['values'])) {
abd06efc 360 // For historic reasons we return these by default only when fetching a case by id
10befc1f 361 if (!empty($params['id']) && is_numeric($params['id']) && empty($options['return'])) {
cf8f0fff 362 $options['return'] = [
abd06efc
CW
363 'contacts' => 1,
364 'activities' => 1,
365 'contact_id' => 1,
cf8f0fff 366 ];
abd06efc 367 }
e01eccc0 368
9ef16723
CW
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']);
abd06efc 374 }
35671d00 375 }
f21557af 376
9ef16723 377 return $cases;
6a488035
TO
378}
379
380/**
35823763
EM
381 * Deprecated API.
382 *
383 * Use activity API instead.
9657ccf2
EM
384 *
385 * @param array $params
386 *
387 * @throws API_Exception
388 * @return array
6a488035
TO
389 */
390function civicrm_api3_case_activity_create($params) {
a14e9d08 391 require_once "api/v3/Activity.php";
cf8f0fff 392 return civicrm_api3_activity_create($params) + [
a14e9d08 393 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
cf8f0fff 394 ];
ae76ce5e
CW
395}
396
397/**
398 * Add a timeline to a case.
399 *
400 * @param array $params
401 *
402 * @throws API_Exception
403 * @return array
404 */
405function civicrm_api3_case_addtimeline($params) {
406 $caseType = CRM_Case_BAO_Case::getCaseType($params['case_id'], 'name');
407 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
cf8f0fff 408 $xmlProcessorParams = [
ae76ce5e
CW
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'],
cf8f0fff 416 ];
ae76ce5e
CW
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 */
427function _civicrm_api3_case_addtimeline_spec(&$params) {
cf8f0fff 428 $params['case_id'] = [
ae76ce5e
CW
429 'title' => 'Case ID',
430 'description' => 'Id of case to update',
431 'type' => CRM_Utils_Type::T_INT,
432 'api.required' => 1,
cf8f0fff
CW
433 ];
434 $params['timeline'] = [
ae76ce5e
CW
435 'title' => 'Timeline',
436 'description' => 'Name of activity set',
437 'type' => CRM_Utils_Type::T_STRING,
438 'api.required' => 1,
cf8f0fff
CW
439 ];
440 $params['activity_date_time'] = [
ae76ce5e
CW
441 'api.default' => 'now',
442 'title' => 'Activity date time',
443 'description' => 'Timeline start date',
444 'type' => CRM_Utils_Type::T_DATE,
cf8f0fff
CW
445 ];
446 $params['creator_id'] = [
ae76ce5e
CW
447 'api.default' => 'user_contact_id',
448 'title' => 'Activity creator',
449 'description' => 'Contact id of timeline creator',
450 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 451 ];
a14e9d08
CW
452}
453
a6bc7218
CW
454/**
455 * Merge 2 cases.
456 *
457 * @param array $params
458 *
459 * @throws API_Exception
460 * @return array
461 */
462function 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 */
475function _civicrm_api3_case_merge_spec(&$params) {
cf8f0fff 476 $params['case_id_1'] = [
a6bc7218
CW
477 'title' => 'Case ID 1',
478 'description' => 'Id of main case',
479 'type' => CRM_Utils_Type::T_INT,
480 'api.required' => 1,
cf8f0fff
CW
481 ];
482 $params['case_id_2'] = [
a6bc7218
CW
483 'title' => 'Case ID 2',
484 'description' => 'Id of second case',
485 'type' => CRM_Utils_Type::T_INT,
486 'api.required' => 1,
cf8f0fff 487 ];
a6bc7218
CW
488}
489
a14e9d08 490/**
35823763
EM
491 * Declare deprecated api functions.
492 *
a14e9d08 493 * @deprecated api notice
a6c01b45 494 * @return array
16b10e64 495 * Array of deprecated actions
a14e9d08
CW
496 */
497function _civicrm_api3_case_deprecation() {
cf8f0fff 498 return ['activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.'];
6a488035
TO
499}
500
501/**
3755d879 502 * @deprecated Update a specified case. Use civicrm_api3_case_create() instead.
6a488035 503 *
6c552737
TO
504 * @param array $params
505 * //REQUIRED:
506 * 'case_id' => int
6a488035 507 *
6c552737
TO
508 * //OPTIONAL
509 * 'status_id' => int
510 * 'start_date' => str datestamp
511 * 'contact_id' => int // case client
6a488035 512 *
784e85a1 513 * @throws API_Exception
a6c01b45 514 * @return array
72b3a70c 515 * api result array
6a488035
TO
516 */
517function civicrm_api3_case_update($params) {
e720ce6e
CB
518 if (!isset($params['case_id']) && isset($params['id'])) {
519 $params['case_id'] = $params['id'];
520 }
521
6a488035 522 //check parameters
cf8f0fff 523 civicrm_api3_verify_mandatory($params, NULL, ['id']);
6a488035 524
784e85a1 525 // return error if modifying creator id
6a488035 526 if (array_key_exists('creator_id', $params)) {
784e85a1 527 throw new API_Exception(ts('You cannot update creator id'));
6a488035
TO
528 }
529
cf8f0fff 530 $mCaseId = $origContactIds = [];
6a488035
TO
531
532 // get original contact id and creator id of case
533 if (!empty($params['contact_id'])) {
c2e81506 534 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
f37c1b47 535 $origContactId = CRM_Utils_Array::first($origContactIds);
6a488035
TO
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)) {
784e85a1 541 throw new API_Exception('Invalid case contact id (orig_contact_id)');
6a488035
TO
542 }
543 elseif (empty($params['orig_contact_id'])) {
784e85a1 544 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
6a488035
TO
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])) {
c2e81506 555 $params['id'] = $mCaseId[0];
6a488035
TO
556 }
557
558 $dao = new CRM_Case_BAO_Case();
559 $dao->id = $params['id'];
560
561 $dao->copyValues($params);
562 $dao->save();
563
cf8f0fff 564 $case = [];
6a488035
TO
565 _civicrm_api3_object_to_array($dao, $case);
566
cf8f0fff 567 return civicrm_api3_create_success([$dao->id => $case], $params, 'Case', 'update', $dao);
6a488035
TO
568}
569
570/**
571 * Delete a specified case.
572 *
6c552737 573 * @param array $params
37b8953e 574 *
244bbdd8 575 * @code
6c552737
TO
576 * //REQUIRED:
577 * 'id' => int
6a488035 578 *
6c552737
TO
579 * //OPTIONAL
580 * 'move_to_trash' => bool (defaults to false)
244bbdd8 581 * @endcode
6a488035 582 *
77b97be7 583 * @throws API_Exception
8572e6de 584 * @return mixed
6a488035
TO
585 */
586function civicrm_api3_case_delete($params) {
587 //check parameters
cf8f0fff 588 civicrm_api3_verify_mandatory($params, NULL, ['id']);
6a488035
TO
589
590 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
244bbdd8 591 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
6a488035
TO
592 }
593 else {
784e85a1 594 throw new API_Exception('Could not delete case.');
6a488035
TO
595 }
596}
597
8572e6de
CW
598/**
599 * Case.restore API specification
600 *
601 * @param array $spec description of fields supported by this API call
602 * @return void
603 */
604function _civicrm_api3_case_restore_spec(&$spec) {
cf8f0fff
CW
605 $result = civicrm_api3('Case', 'getfields', ['api_action' => 'delete']);
606 $spec = ['id' => $result['values']['id']];
8572e6de
CW
607}
608
609/**
610 * Restore a specified case from the trash.
611 *
612 * @param array $params
613 * @throws API_Exception
614 * @return mixed
615 */
616function 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
6a488035 625/**
9ef16723 626 * Augment case results with extra data.
6a488035 627 *
9ef16723 628 * @param array $cases
e9ff5391 629 * @param array $options
6a488035 630 */
9ef16723
CW
631function _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'
ea2aa8ff
MW
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);
9ef16723
CW
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
cf8f0fff 647 $case['activities'] = [];
9ef16723
CW
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 }
cf8f0fff 659 $case['case_type_id.definition'] = [];
9ef16723
CW
660 if ($xml) {
661 $case['case_type_id.definition'] = CRM_Case_BAO_CaseType::convertXmlToDefinition($xml);
662 }
663 }
a54ac083 664 }
9ef16723 665 // Bulk-load activities
a54ac083 666 if (!empty($options['return']['activities'])) {
9ef16723 667 $query = "SELECT case_id, activity_id FROM civicrm_case_activity WHERE case_id IN (%1)";
cf8f0fff 668 $params = [1 => [implode(',', array_keys($cases)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES]];
9ef16723 669 $dao = CRM_Core_DAO::executeQuery($query, $params);
a54ac083 670 while ($dao->fetch()) {
9ef16723 671 $cases[$dao->case_id]['activities'][] = $dao->activity_id;
6a488035 672 }
6a488035 673 }
9ef16723 674 // Bulk-load tags. Supports joins onto the tag entity.
cf8f0fff 675 $tagGet = ['tag_id', 'entity_id'];
9ef16723
CW
676 foreach (array_keys($options['return']) as $key) {
677 if (strpos($key, 'tag_id.') === 0) {
678 $tagGet[] = $key;
679 $options['return']['tag_id'] = 1;
69f9c562 680 }
9ef16723
CW
681 }
682 if (!empty($options['return']['tag_id'])) {
cf8f0fff 683 $tags = civicrm_api3('EntityTag', 'get', [
9ef16723 684 'entity_table' => 'civicrm_case',
cf8f0fff 685 'entity_id' => ['IN' => array_keys($cases)],
9ef16723 686 'return' => $tagGet,
cf8f0fff
CW
687 'options' => ['limit' => 0],
688 ]);
9ef16723
CW
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;
69f9c562
CW
693 }
694 }
6a488035
TO
695}
696
697/**
61fe4988 698 * Internal function to format create params for processing.
9657ccf2
EM
699 *
700 * @param array $params
6a488035
TO
701 */
702function _civicrm_api3_case_format_params(&$params) {
2a3c0d28 703 // Format/include custom params
cf8f0fff 704 $values = [];
2a3c0d28
MW
705 _civicrm_api3_custom_format_params($params, $values, 'Case');
706 $params = array_merge($params, $values);
ebf4aeaa 707
ea2aa8ff
MW
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'])) {
cf8f0fff 712 $params['contact_id'] = [$params['contact_id']];
ea2aa8ff
MW
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.
2a3c0d28 722 if (empty($params['case_type_id']) && empty($params['case_type'])) {
ea2aa8ff 723 // If both case_type_id and case_type are empty we are updating a case so return here.
2a3c0d28
MW
724 return;
725 }
726
ea2aa8ff 727 // We are creating a new case
2a3c0d28
MW
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);
61fe4988 737 $params['case_type'] = $caseTypes[$params['case_type_id']];
3f25e694 738 }
6a488035 739 }
2a3c0d28
MW
740 elseif (empty($params['case_type'])) {
741 $params['case_type'] = $caseTypes[$params['case_type_id']];
742 }
6a488035 743}
ff9340a4
CW
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 */
753function civicrm_api3_case_getList($params) {
754 require_once 'api/v3/Generic/Getlist.php';
755 require_once 'api/v3/CaseContact.php';
09d55aa3 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'])) {
cf8f0fff 758 $params['params']['case_id'] = ['IN' => $params['id']];
09d55aa3 759 unset($params['id']);
760 }
ff9340a4
CW
761 $params['id_field'] = 'case_id';
762 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
cf8f0fff 763 $params['description_field'] = [
ff9340a4
CW
764 'case_id',
765 'case_id.case_type_id.title',
766 'case_id.subject',
767 'case_id.status_id',
768 'case_id.start_date',
cf8f0fff
CW
769 ];
770 $apiRequest = [
09d55aa3 771 'version' => 3,
ff9340a4
CW
772 'entity' => 'CaseContact',
773 'action' => 'getlist',
774 'params' => $params,
cf8f0fff 775 ];
ff9340a4
CW
776 return civicrm_api3_generic_getList($apiRequest);
777}
778
779/**
780 * Needed due to the above override
781 * @param $params
782 * @param $apiRequest
783 */
784function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
785 require_once 'api/v3/Generic/Getlist.php';
786 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
787}