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