Fixed API test failures due to correct check on error message.
[civicrm-core.git] / api / v3 / Case.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
784e85a1 42 * //REQUIRED:
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
47 *
48 * //OPTIONAL
49 * 'medium_id' => int // see civicrm option values for possibilities
50 * 'creator_id' => int // case manager, default to the logged in user
51 * 'status_id' => int // defaults to 1 "ongoing"
52 * 'location' => str
53 * 'start_date' => str datestamp // defaults to: date('YmdHis')
54 * 'duration' => int // in minutes
55 * 'details' => str // html format
b081365f 56 * @endcode
6a488035 57 *
784e85a1 58 * @throws API_Exception
a6c01b45 59 * @return array
72b3a70c 60 * api result array
6a488035
TO
61 */
62function civicrm_api3_case_create($params) {
63
64 if (!empty($params['id'])) {
65 return civicrm_api3_case_update($params);
66 }
67
211e2fca
EM
68 civicrm_api3_verify_mandatory($params, NULL, array(
69 'contact_id',
70 'subject',
71 array('case_type', 'case_type_id'))
72 );
6a488035
TO
73 _civicrm_api3_case_format_params($params);
74
75 // If format_params didn't find what it was looking for, return error
76 if (empty($params['case_type_id'])) {
784e85a1 77 throw new API_Exception('Invalid case_type. No such case type exists.');
6a488035
TO
78 }
79 if (empty($params['case_type'])) {
784e85a1 80 throw new API_Exception('Invalid case_type_id. No such case type exists.');
6a488035
TO
81 }
82
83 // Fixme: can we safely pass raw params to the BAO?
84 $newParams = array(
85 'case_type_id' => $params['case_type_id'],
86 'creator_id' => $params['creator_id'],
87 'status_id' => $params['status_id'],
88 'start_date' => $params['start_date'],
89 'end_date' => CRM_Utils_Array::value('end_date', $params),
90 'subject' => $params['subject'],
91 );
92
93 $caseBAO = CRM_Case_BAO_Case::create($newParams);
94
95 if (!$caseBAO) {
784e85a1 96 throw new API_Exception('Case not created. Please check input params.');
6a488035
TO
97 }
98
99 foreach ((array) $params['contact_id'] as $cid) {
100 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
b53bcc5d 101 CRM_Case_BAO_CaseContact::create($contactParams);
6a488035
TO
102 }
103
104 // Initialize XML processor with $params
105 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
106 $xmlProcessorParams = array(
107 'clientID' => $params['contact_id'],
108 'creatorID' => $params['creator_id'],
109 'standardTimeline' => 1,
110 'activityTypeName' => 'Open Case',
111 'caseID' => $caseBAO->id,
112 'subject' => $params['subject'],
113 'location' => CRM_Utils_Array::value('location', $params),
114 'activity_date_time' => $params['start_date'],
115 'duration' => CRM_Utils_Array::value('duration', $params),
116 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
117 'details' => CRM_Utils_Array::value('details', $params),
118 'custom' => array(),
119 );
120
121 // Do it! :-D
122 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
123
124 // return case
125 $values = array();
126 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
127
244bbdd8 128 return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
6a488035
TO
129}
130
11e09c59 131/**
2fb1dd66 132 * Adjust Metadata for Get Action.
6a488035 133 *
cf470720 134 * @param array $params
2fb1dd66 135 * Parameters determined by getfields.
6a488035
TO
136 */
137function _civicrm_api3_case_get_spec(&$params) {
d142432b
EM
138 $params['contact_id'] = array(
139 'api.aliases' => array('client_id'),
140 'title' => 'Case Client',
48bdb3cd 141 'description' => 'Contact id of one or more clients to retrieve cases for',
d142432b 142 'type' => CRM_Utils_Type::T_INT,
48bdb3cd
CW
143 'FKApiName' => 'Contact',
144 );
145 $params['activity_id'] = array(
146 'title' => 'Case Activity',
147 'description' => 'Id of an activity in the case',
148 'type' => CRM_Utils_Type::T_INT,
149 'FKApiName' => 'Activity',
d142432b 150 );
6a488035
TO
151}
152
11e09c59 153/**
2fb1dd66 154 * Adjust Metadata for Create Action.
6a488035 155 *
cf470720 156 * @param array $params
b081365f 157 * Array of parameters determined by getfields.
6a488035
TO
158 */
159function _civicrm_api3_case_create_spec(&$params) {
d142432b
EM
160 $params['contact_id'] = array(
161 'api.aliases' => array('client_id'),
162 'title' => 'Case Client',
48bdb3cd 163 'description' => 'Contact id of case client(s)',
d142432b
EM
164 'api.required' => 1,
165 'type' => CRM_Utils_Type::T_INT,
48bdb3cd 166 'FKApiName' => 'Contact',
d142432b 167 );
6a488035 168 $params['status_id']['api.default'] = 1;
8ae90f85 169 $params['status_id']['api.aliases'] = array('case_status');
941feb14
EM
170 $params['creator_id']['api.default'] = 'user_contact_id';
171 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
b05e6d0d 172 $params['creator_id']['title'] = 'Case Created By';
ca11b9da 173 $params['start_date']['api.default'] = 'now';
16c0ec8d
CW
174 $params['medium_id'] = array(
175 'name' => 'medium_id',
176 'title' => 'Activity Medium',
d142432b 177 'type' => CRM_Utils_Type::T_INT,
16c0ec8d 178 );
6a488035
TO
179}
180
11e09c59 181/**
2fb1dd66 182 * Adjust Metadata for Update action.
6a488035 183 *
cf470720 184 * @param array $params
b081365f 185 * Array of parameters determined by getfields.
6a488035
TO
186 */
187function _civicrm_api3_case_update_spec(&$params) {
188 $params['id']['api.required'] = 1;
189}
190
11e09c59 191/**
c1a920f1 192 * Adjust Metadata for Delete action.
6a488035 193 *
cf470720 194 * @param array $params
b081365f 195 * Array of parameters determined by getfields.
6a488035
TO
196 */
197function _civicrm_api3_case_delete_spec(&$params) {
198 $params['id']['api.required'] = 1;
199}
200
6a488035 201/**
211e2fca 202 * Get details of a particular case, or search for cases, depending on params.
6a488035
TO
203 *
204 * Please provide one (and only one) of the four get/search parameters:
205 *
6c552737
TO
206 * @param array $params
207 * 'id' => if set, will get all available info about a case, including contacts and activities
6a488035 208 *
6c552737
TO
209 * // if no case_id provided, this function will use one of the following search parameters:
210 * 'client_id' => finds all cases with a specific client
211 * 'activity_id' => returns the case containing a specific activity
212 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
6a488035 213 *
77b97be7 214 * @throws API_Exception
a6c01b45 215 * @return array
72b3a70c 216 * (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
TO
217 */
218function civicrm_api3_case_get($params) {
219 $options = _civicrm_api3_get_options_from_params($params);
48bdb3cd
CW
220 $sql = CRM_Utils_SQL_Select::fragment();
221
222 // Add clause to search by client
6a488035 223 if (!empty($params['contact_id'])) {
48bdb3cd
CW
224 $contacts = array();
225 foreach ((array) $params['contact_id'] as $c) {
226 if (!CRM_Utils_Rule::positiveInteger($c)) {
227 throw new API_Exception('Invalid parameter: contact_id. Must provide numeric value(s).');
6a488035 228 }
48bdb3cd 229 $contacts[] = $c;
6a488035 230 }
48bdb3cd
CW
231 $sql
232 ->join('civicrm_case_contact', 'INNER JOIN civicrm_case_contact ON civicrm_case_contact.case_id = a.id')
233 ->where('civicrm_case_contact.contact_id IN (' . implode(',', $contacts) . ')');
6a488035
TO
234 }
235
48bdb3cd 236 // Add clause to search by activity
6a488035 237 if (!empty($params['activity_id'])) {
48bdb3cd 238 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
784e85a1 239 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
6a488035 240 }
48bdb3cd
CW
241 $activityId = $params['activity_id'];
242 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
243 if ($originalId) {
244 $activityId .= ',' . $originalId;
6a488035 245 }
48bdb3cd
CW
246 $sql
247 ->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
248 ->where("civicrm_case_activity.activity_id IN ($activityId)");
6a488035 249 }
f21557af 250
a54ac083
CW
251 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case', $sql);
252
abd06efc
CW
253 if (empty($options['is_count'])) {
254 // For historic reasons we return these by default only when fetching a case by id
255 if (!empty($params['id']) && empty($options['return'])) {
256 $options['return'] = array(
257 'contacts' => 1,
258 'activities' => 1,
259 'contact_id' => 1,
260 );
261 }
e01eccc0 262
abd06efc
CW
263 foreach ($foundcases['values'] as &$case) {
264 _civicrm_api3_case_read($case, $options);
265 }
35671d00 266 }
f21557af 267
a54ac083 268 return $foundcases;
6a488035
TO
269}
270
271/**
35823763
EM
272 * Deprecated API.
273 *
274 * Use activity API instead.
9657ccf2
EM
275 *
276 * @param array $params
277 *
278 * @throws API_Exception
279 * @return array
6a488035
TO
280 */
281function civicrm_api3_case_activity_create($params) {
a14e9d08
CW
282 require_once "api/v3/Activity.php";
283 return civicrm_api3_activity_create($params) + array(
284 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
285 );
286}
287
288/**
35823763
EM
289 * Declare deprecated api functions.
290 *
a14e9d08 291 * @deprecated api notice
a6c01b45 292 * @return array
16b10e64 293 * Array of deprecated actions
a14e9d08
CW
294 */
295function _civicrm_api3_case_deprecation() {
296 return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
6a488035
TO
297}
298
299/**
300 * Update a specified case.
301 *
6c552737
TO
302 * @param array $params
303 * //REQUIRED:
304 * 'case_id' => int
6a488035 305 *
6c552737
TO
306 * //OPTIONAL
307 * 'status_id' => int
308 * 'start_date' => str datestamp
309 * 'contact_id' => int // case client
6a488035 310 *
784e85a1 311 * @throws API_Exception
a6c01b45 312 * @return array
72b3a70c 313 * api result array
6a488035
TO
314 */
315function civicrm_api3_case_update($params) {
316 //check parameters
317 civicrm_api3_verify_mandatory($params, NULL, array('id'));
318
784e85a1 319 // return error if modifying creator id
6a488035 320 if (array_key_exists('creator_id', $params)) {
784e85a1 321 throw new API_Exception(ts('You cannot update creator id'));
6a488035
TO
322 }
323
784e85a1 324 $mCaseId = $origContactIds = array();
6a488035
TO
325
326 // get original contact id and creator id of case
327 if (!empty($params['contact_id'])) {
c2e81506 328 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
6a488035
TO
329 $origContactId = $origContactIds[1];
330 }
331
332 if (count($origContactIds) > 1) {
333 // check valid orig contact id
334 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
784e85a1 335 throw new API_Exception('Invalid case contact id (orig_contact_id)');
6a488035
TO
336 }
337 elseif (empty($params['orig_contact_id'])) {
784e85a1 338 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
339 }
340 $origContactId = $params['orig_contact_id'];
341 }
342
343 // check for same contact id for edit Client
344 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
345 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
346 }
347
348 if (!empty($mCaseId[0])) {
c2e81506 349 $params['id'] = $mCaseId[0];
6a488035
TO
350 }
351
352 $dao = new CRM_Case_BAO_Case();
353 $dao->id = $params['id'];
354
355 $dao->copyValues($params);
356 $dao->save();
357
358 $case = array();
6a488035
TO
359 _civicrm_api3_object_to_array($dao, $case);
360
a54ac083 361 return civicrm_api3_create_success(array($dao->id => $case), $params, 'Case', 'update', $dao);
6a488035
TO
362}
363
364/**
365 * Delete a specified case.
366 *
6c552737 367 * @param array $params
37b8953e 368 *
244bbdd8 369 * @code
6c552737
TO
370 * //REQUIRED:
371 * 'id' => int
6a488035 372 *
6c552737
TO
373 * //OPTIONAL
374 * 'move_to_trash' => bool (defaults to false)
244bbdd8 375 * @endcode
6a488035 376 *
77b97be7 377 * @throws API_Exception
5c766a0b 378 * @return bool
72b3a70c 379 * true if success, else false
6a488035
TO
380 */
381function civicrm_api3_case_delete($params) {
382 //check parameters
383 civicrm_api3_verify_mandatory($params, NULL, array('id'));
384
385 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
244bbdd8 386 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
6a488035
TO
387 }
388 else {
784e85a1 389 throw new API_Exception('Could not delete case.');
6a488035
TO
390 }
391}
392
6a488035 393/**
a54ac083 394 * Augment a case with extra data.
6a488035 395 *
a54ac083 396 * @param array $case
e9ff5391 397 * @param array $options
6a488035 398 */
a54ac083
CW
399function _civicrm_api3_case_read(&$case, $options) {
400 if (empty($options['return']) || !empty($options['return']['contact_id'])) {
6a488035 401 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
a54ac083
CW
402 $case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id']);
403 }
404 if (!empty($options['return']['contacts'])) {
405 //get case contacts
406 $contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
407 $relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
408 $case['contacts'] = array_merge($contacts, $relations);
409 }
410 if (!empty($options['return']['activities'])) {
411 //get case activities
412 $case['activities'] = array();
413 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = %1";
414 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($case['id'], 'Integer')));
415 while ($dao->fetch()) {
416 $case['activities'][] = $dao->activity_id;
6a488035 417 }
6a488035
TO
418 }
419}
420
421/**
61fe4988 422 * Internal function to format create params for processing.
9657ccf2
EM
423 *
424 * @param array $params
6a488035
TO
425 */
426function _civicrm_api3_case_format_params(&$params) {
6a488035 427 // figure out case type id from case type and vice-versa
1be6caec 428 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
6a488035
TO
429 if (empty($params['case_type_id'])) {
430 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
3f25e694
TO
431
432 // DEPRECATED: lookup by label for backward compatibility
433 if (!$params['case_type_id']) {
434 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
435 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
61fe4988 436 $params['case_type'] = $caseTypes[$params['case_type_id']];
3f25e694 437 }
6a488035
TO
438 }
439 elseif (empty($params['case_type'])) {
440 $params['case_type'] = $caseTypes[$params['case_type_id']];
441 }
6a488035 442}
ff9340a4
CW
443
444/**
445 * It actually works a lot better to use the CaseContact api instead of the Case api
446 * for entityRef fields so we can perform the necessary joins,
447 * so we pass off getlist requests to the CaseContact api.
448 *
449 * @param array $params
450 * @return mixed
451 */
452function civicrm_api3_case_getList($params) {
453 require_once 'api/v3/Generic/Getlist.php';
454 require_once 'api/v3/CaseContact.php';
455 $params['id_field'] = 'case_id';
456 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
457 $params['description_field'] = array(
458 'case_id',
459 'case_id.case_type_id.title',
460 'case_id.subject',
461 'case_id.status_id',
462 'case_id.start_date',
463 );
464 $apiRequest = array(
465 'entity' => 'CaseContact',
466 'action' => 'getlist',
467 'params' => $params,
468 );
469 return civicrm_api3_generic_getList($apiRequest);
470}
471
472/**
473 * Needed due to the above override
474 * @param $params
475 * @param $apiRequest
476 */
477function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
478 require_once 'api/v3/Generic/Getlist.php';
479 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
480}