ebecf786662f13c320b693ccddfd0dc28c8ca612
[civicrm-core.git] / api / v3 / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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:
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
56 * @endcode
57 *
58 * @throws API_Exception
59 * @return array
60 * api result array
61 */
62 function civicrm_api3_case_create($params) {
63
64 if (!empty($params['id'])) {
65 return civicrm_api3_case_update($params);
66 }
67
68 civicrm_api3_verify_mandatory($params, NULL, array(
69 'contact_id',
70 'subject',
71 array('case_type', 'case_type_id'))
72 );
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'])) {
77 throw new API_Exception('Invalid case_type. No such case type exists.');
78 }
79 if (empty($params['case_type'])) {
80 throw new API_Exception('Invalid case_type_id. No such case type exists.');
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) {
96 throw new API_Exception('Case not created. Please check input params.');
97 }
98
99 foreach ((array) $params['contact_id'] as $cid) {
100 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
101 CRM_Case_BAO_CaseContact::create($contactParams);
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
128 return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
129 }
130
131 /**
132 * Adjust Metadata for Get Action.
133 *
134 * @param array $params
135 * Parameters determined by getfields.
136 */
137 function _civicrm_api3_case_get_spec(&$params) {
138 $params['contact_id'] = array(
139 'api.aliases' => array('client_id'),
140 'title' => 'Case Client',
141 'description' => 'Contact id of one or more clients to retrieve cases for',
142 'type' => CRM_Utils_Type::T_INT,
143 );
144 $params['activity_id'] = array(
145 'title' => 'Case Activity',
146 'description' => 'Id of an activity in the case',
147 'type' => CRM_Utils_Type::T_INT,
148 );
149 }
150
151 /**
152 * Adjust Metadata for Create Action.
153 *
154 * @param array $params
155 * Array of parameters determined by getfields.
156 */
157 function _civicrm_api3_case_create_spec(&$params) {
158 $params['contact_id'] = array(
159 'api.aliases' => array('client_id'),
160 'title' => 'Case Client',
161 'description' => 'Contact id of case client(s)',
162 'api.required' => 1,
163 'type' => CRM_Utils_Type::T_INT,
164 );
165 $params['status_id']['api.default'] = 1;
166 $params['status_id']['api.aliases'] = array('case_status');
167 $params['creator_id']['api.default'] = 'user_contact_id';
168 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
169 $params['creator_id']['title'] = 'Case Created By';
170 $params['start_date']['api.default'] = 'now';
171 $params['medium_id'] = array(
172 'name' => 'medium_id',
173 'title' => 'Activity Medium',
174 'type' => CRM_Utils_Type::T_INT,
175 );
176 }
177
178 /**
179 * Adjust Metadata for Update action.
180 *
181 * @param array $params
182 * Array of parameters determined by getfields.
183 */
184 function _civicrm_api3_case_update_spec(&$params) {
185 $params['id']['api.required'] = 1;
186 }
187
188 /**
189 * Adjust Metadata for Delete action.
190 *
191 * @param array $params
192 * Array of parameters determined by getfields.
193 */
194 function _civicrm_api3_case_delete_spec(&$params) {
195 $params['id']['api.required'] = 1;
196 }
197
198 /**
199 * Get details of a particular case, or search for cases, depending on params.
200 *
201 * Please provide one (and only one) of the four get/search parameters:
202 *
203 * @param array $params
204 * 'id' => if set, will get all available info about a case, including contacts and activities
205 *
206 * // if no case_id provided, this function will use one of the following search parameters:
207 * 'client_id' => finds all cases with a specific client
208 * 'activity_id' => returns the case containing a specific activity
209 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
210 *
211 * @throws API_Exception
212 * @return array
213 * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
214 */
215 function civicrm_api3_case_get($params) {
216 $options = _civicrm_api3_get_options_from_params($params);
217 $sql = CRM_Utils_SQL_Select::fragment();
218
219 // Add clause to search by client
220 if (!empty($params['contact_id'])) {
221 // Legacy support - this field historically supports a nonstandard format of array(1,2,3) as a synonym for array('IN' => array(1,2,3))
222 if (is_array($params['contact_id'])) {
223 $operator = CRM_Utils_Array::first(array_keys($params['contact_id']));
224 if (!in_array($operator, \CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
225 $params['contact_id'] = array('IN' => $params['contact_id']);
226 }
227 }
228 else {
229 $params['contact_id'] = array('=' => $params['contact_id']);
230 }
231 $clause = CRM_Core_DAO::createSQLFilter('contact_id', $params['contact_id']);
232 $sql->where("a.id IN (SELECT case_id FROM civicrm_case_contact WHERE $clause)");
233 }
234
235 // Add clause to search by activity
236 if (!empty($params['activity_id'])) {
237 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
238 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
239 }
240 $activityId = $params['activity_id'];
241 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
242 if ($originalId) {
243 $activityId .= ',' . $originalId;
244 }
245 $sql
246 ->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
247 ->where("civicrm_case_activity.activity_id IN ($activityId)");
248 }
249
250 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case', $sql);
251
252 if (empty($options['is_count'])) {
253 // For historic reasons we return these by default only when fetching a case by id
254 if (!empty($params['id']) && empty($options['return'])) {
255 $options['return'] = array(
256 'contacts' => 1,
257 'activities' => 1,
258 'contact_id' => 1,
259 );
260 }
261
262 foreach ($foundcases['values'] as &$case) {
263 _civicrm_api3_case_read($case, $options);
264 }
265 }
266
267 return $foundcases;
268 }
269
270 /**
271 * Deprecated API.
272 *
273 * Use activity API instead.
274 *
275 * @param array $params
276 *
277 * @throws API_Exception
278 * @return array
279 */
280 function civicrm_api3_case_activity_create($params) {
281 require_once "api/v3/Activity.php";
282 return civicrm_api3_activity_create($params) + array(
283 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
284 );
285 }
286
287 /**
288 * Declare deprecated api functions.
289 *
290 * @deprecated api notice
291 * @return array
292 * Array of deprecated actions
293 */
294 function _civicrm_api3_case_deprecation() {
295 return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
296 }
297
298 /**
299 * Update a specified case.
300 *
301 * @param array $params
302 * //REQUIRED:
303 * 'case_id' => int
304 *
305 * //OPTIONAL
306 * 'status_id' => int
307 * 'start_date' => str datestamp
308 * 'contact_id' => int // case client
309 *
310 * @throws API_Exception
311 * @return array
312 * api result array
313 */
314 function civicrm_api3_case_update($params) {
315 if (!isset($params['case_id']) && isset($params['id'])) {
316 $params['case_id'] = $params['id'];
317 }
318
319 //check parameters
320 civicrm_api3_verify_mandatory($params, NULL, array('id'));
321
322 // return error if modifying creator id
323 if (array_key_exists('creator_id', $params)) {
324 throw new API_Exception(ts('You cannot update creator id'));
325 }
326
327 $mCaseId = $origContactIds = array();
328
329 // get original contact id and creator id of case
330 if (!empty($params['contact_id'])) {
331 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
332 $origContactId = $origContactIds[1];
333 }
334
335 if (count($origContactIds) > 1) {
336 // check valid orig contact id
337 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
338 throw new API_Exception('Invalid case contact id (orig_contact_id)');
339 }
340 elseif (empty($params['orig_contact_id'])) {
341 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
342 }
343 $origContactId = $params['orig_contact_id'];
344 }
345
346 // check for same contact id for edit Client
347 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
348 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
349 }
350
351 if (!empty($mCaseId[0])) {
352 $params['id'] = $mCaseId[0];
353 }
354
355 $dao = new CRM_Case_BAO_Case();
356 $dao->id = $params['id'];
357
358 $dao->copyValues($params);
359 $dao->save();
360
361 $case = array();
362 _civicrm_api3_object_to_array($dao, $case);
363
364 return civicrm_api3_create_success(array($dao->id => $case), $params, 'Case', 'update', $dao);
365 }
366
367 /**
368 * Delete a specified case.
369 *
370 * @param array $params
371 *
372 * @code
373 * //REQUIRED:
374 * 'id' => int
375 *
376 * //OPTIONAL
377 * 'move_to_trash' => bool (defaults to false)
378 * @endcode
379 *
380 * @throws API_Exception
381 * @return bool
382 * true if success, else false
383 */
384 function civicrm_api3_case_delete($params) {
385 //check parameters
386 civicrm_api3_verify_mandatory($params, NULL, array('id'));
387
388 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
389 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
390 }
391 else {
392 throw new API_Exception('Could not delete case.');
393 }
394 }
395
396 /**
397 * Augment a case with extra data.
398 *
399 * @param array $case
400 * @param array $options
401 */
402 function _civicrm_api3_case_read(&$case, $options) {
403 if (empty($options['return']) || !empty($options['return']['contact_id'])) {
404 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
405 $case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id']);
406 }
407 if (!empty($options['return']['contacts'])) {
408 //get case contacts
409 $contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
410 $relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
411 $case['contacts'] = array_merge($contacts, $relations);
412 }
413 if (!empty($options['return']['activities'])) {
414 //get case activities
415 $case['activities'] = array();
416 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = %1";
417 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($case['id'], 'Integer')));
418 while ($dao->fetch()) {
419 $case['activities'][] = $dao->activity_id;
420 }
421 }
422 // Properly render this joined field
423 if (!empty($options['return']['case_type_id.definition'])) {
424 if (!empty($case['case_type_id.definition'])) {
425 list($xml) = CRM_Utils_XML::parseString($case['case_type_id.definition']);
426 }
427 else {
428 $caseTypeId = !empty($case['case_type_id']) ? $case['case_type_id'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $case['id'], 'case_type_id');
429 $caseTypeName = !empty($case['case_type_id.name']) ? $case['case_type_id.name'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name');
430 $xml = CRM_Case_XMLRepository::singleton()->retrieve($caseTypeName);
431 }
432 $case['case_type_id.definition'] = array();
433 if ($xml) {
434 $case['case_type_id.definition'] = CRM_Case_BAO_CaseType::convertXmlToDefinition($xml);
435 }
436 }
437 }
438
439 /**
440 * Internal function to format create params for processing.
441 *
442 * @param array $params
443 */
444 function _civicrm_api3_case_format_params(&$params) {
445 // figure out case type id from case type and vice-versa
446 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
447 if (empty($params['case_type_id'])) {
448 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
449
450 // DEPRECATED: lookup by label for backward compatibility
451 if (!$params['case_type_id']) {
452 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
453 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
454 $params['case_type'] = $caseTypes[$params['case_type_id']];
455 }
456 }
457 elseif (empty($params['case_type'])) {
458 $params['case_type'] = $caseTypes[$params['case_type_id']];
459 }
460 }
461
462 /**
463 * It actually works a lot better to use the CaseContact api instead of the Case api
464 * for entityRef fields so we can perform the necessary joins,
465 * so we pass off getlist requests to the CaseContact api.
466 *
467 * @param array $params
468 * @return mixed
469 */
470 function civicrm_api3_case_getList($params) {
471 require_once 'api/v3/Generic/Getlist.php';
472 require_once 'api/v3/CaseContact.php';
473 //CRM:19956 - Assign case_id param if both id and case_id is passed to retrieve the case
474 if (!empty($params['id']) && !empty($params['params']) && !empty($params['params']['case_id'])) {
475 $params['params']['case_id'] = array('IN' => $params['id']);
476 unset($params['id']);
477 }
478 $params['id_field'] = 'case_id';
479 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
480 $params['description_field'] = array(
481 'case_id',
482 'case_id.case_type_id.title',
483 'case_id.subject',
484 'case_id.status_id',
485 'case_id.start_date',
486 );
487 $apiRequest = array(
488 'version' => 3,
489 'entity' => 'CaseContact',
490 'action' => 'getlist',
491 'params' => $params,
492 );
493 return civicrm_api3_generic_getList($apiRequest);
494 }
495
496 /**
497 * Needed due to the above override
498 * @param $params
499 * @param $apiRequest
500 */
501 function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
502 require_once 'api/v3/Generic/Getlist.php';
503 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
504 }