Merge pull request #9521 from seamuslee001/drupal8-url-fix
[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 $contacts = array();
222 foreach ((array) $params['contact_id'] as $c) {
223 if (!CRM_Utils_Rule::positiveInteger($c)) {
224 throw new API_Exception('Invalid parameter: contact_id. Must provide numeric value(s).');
225 }
226 $contacts[] = $c;
227 }
228 $sql
229 ->join('civicrm_case_contact', 'INNER JOIN civicrm_case_contact ON civicrm_case_contact.case_id = a.id')
230 ->where('civicrm_case_contact.contact_id IN (' . implode(',', $contacts) . ')');
231 }
232
233 // Add clause to search by activity
234 if (!empty($params['activity_id'])) {
235 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
236 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
237 }
238 $activityId = $params['activity_id'];
239 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
240 if ($originalId) {
241 $activityId .= ',' . $originalId;
242 }
243 $sql
244 ->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
245 ->where("civicrm_case_activity.activity_id IN ($activityId)");
246 }
247
248 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case', $sql);
249
250 if (empty($options['is_count'])) {
251 // For historic reasons we return these by default only when fetching a case by id
252 if (!empty($params['id']) && empty($options['return'])) {
253 $options['return'] = array(
254 'contacts' => 1,
255 'activities' => 1,
256 'contact_id' => 1,
257 );
258 }
259
260 foreach ($foundcases['values'] as &$case) {
261 _civicrm_api3_case_read($case, $options);
262 }
263 }
264
265 return $foundcases;
266 }
267
268 /**
269 * Deprecated API.
270 *
271 * Use activity API instead.
272 *
273 * @param array $params
274 *
275 * @throws API_Exception
276 * @return array
277 */
278 function civicrm_api3_case_activity_create($params) {
279 require_once "api/v3/Activity.php";
280 return civicrm_api3_activity_create($params) + array(
281 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
282 );
283 }
284
285 /**
286 * Declare deprecated api functions.
287 *
288 * @deprecated api notice
289 * @return array
290 * Array of deprecated actions
291 */
292 function _civicrm_api3_case_deprecation() {
293 return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
294 }
295
296 /**
297 * Update a specified case.
298 *
299 * @param array $params
300 * //REQUIRED:
301 * 'case_id' => int
302 *
303 * //OPTIONAL
304 * 'status_id' => int
305 * 'start_date' => str datestamp
306 * 'contact_id' => int // case client
307 *
308 * @throws API_Exception
309 * @return array
310 * api result array
311 */
312 function civicrm_api3_case_update($params) {
313 if (!isset($params['case_id']) && isset($params['id'])) {
314 $params['case_id'] = $params['id'];
315 }
316
317 //check parameters
318 civicrm_api3_verify_mandatory($params, NULL, array('id'));
319
320 // return error if modifying creator id
321 if (array_key_exists('creator_id', $params)) {
322 throw new API_Exception(ts('You cannot update creator id'));
323 }
324
325 $mCaseId = $origContactIds = array();
326
327 // get original contact id and creator id of case
328 if (!empty($params['contact_id'])) {
329 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
330 $origContactId = $origContactIds[1];
331 }
332
333 if (count($origContactIds) > 1) {
334 // check valid orig contact id
335 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
336 throw new API_Exception('Invalid case contact id (orig_contact_id)');
337 }
338 elseif (empty($params['orig_contact_id'])) {
339 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
340 }
341 $origContactId = $params['orig_contact_id'];
342 }
343
344 // check for same contact id for edit Client
345 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
346 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
347 }
348
349 if (!empty($mCaseId[0])) {
350 $params['id'] = $mCaseId[0];
351 }
352
353 $dao = new CRM_Case_BAO_Case();
354 $dao->id = $params['id'];
355
356 $dao->copyValues($params);
357 $dao->save();
358
359 $case = array();
360 _civicrm_api3_object_to_array($dao, $case);
361
362 return civicrm_api3_create_success(array($dao->id => $case), $params, 'Case', 'update', $dao);
363 }
364
365 /**
366 * Delete a specified case.
367 *
368 * @param array $params
369 *
370 * @code
371 * //REQUIRED:
372 * 'id' => int
373 *
374 * //OPTIONAL
375 * 'move_to_trash' => bool (defaults to false)
376 * @endcode
377 *
378 * @throws API_Exception
379 * @return bool
380 * true if success, else false
381 */
382 function civicrm_api3_case_delete($params) {
383 //check parameters
384 civicrm_api3_verify_mandatory($params, NULL, array('id'));
385
386 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
387 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
388 }
389 else {
390 throw new API_Exception('Could not delete case.');
391 }
392 }
393
394 /**
395 * Augment a case with extra data.
396 *
397 * @param array $case
398 * @param array $options
399 */
400 function _civicrm_api3_case_read(&$case, $options) {
401 if (empty($options['return']) || !empty($options['return']['contact_id'])) {
402 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
403 $case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id']);
404 }
405 if (!empty($options['return']['contacts'])) {
406 //get case contacts
407 $contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
408 $relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
409 $case['contacts'] = array_merge($contacts, $relations);
410 }
411 if (!empty($options['return']['activities'])) {
412 //get case activities
413 $case['activities'] = array();
414 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = %1";
415 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($case['id'], 'Integer')));
416 while ($dao->fetch()) {
417 $case['activities'][] = $dao->activity_id;
418 }
419 }
420 }
421
422 /**
423 * Internal function to format create params for processing.
424 *
425 * @param array $params
426 */
427 function _civicrm_api3_case_format_params(&$params) {
428 // figure out case type id from case type and vice-versa
429 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
430 if (empty($params['case_type_id'])) {
431 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
432
433 // DEPRECATED: lookup by label for backward compatibility
434 if (!$params['case_type_id']) {
435 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
436 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
437 $params['case_type'] = $caseTypes[$params['case_type_id']];
438 }
439 }
440 elseif (empty($params['case_type'])) {
441 $params['case_type'] = $caseTypes[$params['case_type_id']];
442 }
443 }
444
445 /**
446 * It actually works a lot better to use the CaseContact api instead of the Case api
447 * for entityRef fields so we can perform the necessary joins,
448 * so we pass off getlist requests to the CaseContact api.
449 *
450 * @param array $params
451 * @return mixed
452 */
453 function civicrm_api3_case_getList($params) {
454 require_once 'api/v3/Generic/Getlist.php';
455 require_once 'api/v3/CaseContact.php';
456 //CRM:19956 - Assign case_id param if both id and case_id is passed to retrieve the case
457 if (!empty($params['id']) && !empty($params['params']) && !empty($params['params']['case_id'])) {
458 $params['params']['case_id'] = array('IN' => $params['id']);
459 unset($params['id']);
460 }
461 $params['id_field'] = 'case_id';
462 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
463 $params['description_field'] = array(
464 'case_id',
465 'case_id.case_type_id.title',
466 'case_id.subject',
467 'case_id.status_id',
468 'case_id.start_date',
469 );
470 $apiRequest = array(
471 'version' => 3,
472 'entity' => 'CaseContact',
473 'action' => 'getlist',
474 'params' => $params,
475 );
476 return civicrm_api3_generic_getList($apiRequest);
477 }
478
479 /**
480 * Needed due to the above override
481 * @param $params
482 * @param $apiRequest
483 */
484 function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
485 require_once 'api/v3/Generic/Getlist.php';
486 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
487 }