CRM-14449 case api code tidy up
[civicrm-core.git] / api / v3 / Case.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 * File for the CiviCRM APIv3 Case functions
31 * Developed by woolman.org
32 *
33 * @package CiviCRM_APIv3
34 * @subpackage API_Case
35 * @copyright CiviCRM LLC (c) 2004-2014
36 *
37 */
38
39
40 /**
41 * Open a new case, add client and manager roles, and add standard timeline
42 *
43 * @param array (
44 * //REQUIRED:
45 * 'case_type_id' => int OR
46 * 'case_type' => str (provide one or the other)
47 * 'contact_id' => int // case client
48 * 'subject' => str
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
58 *
59 * @throws API_Exception
60 * @return array api result array
61 *
62 * @access public
63 * {@getfields case_create}
64 */
65 function civicrm_api3_case_create($params) {
66
67 if (!empty($params['id'])) {
68 return civicrm_api3_case_update($params);
69 }
70
71 civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'subject', array('case_type', 'case_type_id')));
72 _civicrm_api3_case_format_params($params);
73
74 // If format_params didn't find what it was looking for, return error
75 if (empty($params['case_type_id'])) {
76 throw new API_Exception('Invalid case_type. No such case type exists.');
77 }
78 if (empty($params['case_type'])) {
79 throw new API_Exception('Invalid case_type_id. No such case type exists.');
80 }
81
82 // Fixme: can we safely pass raw params to the BAO?
83 $newParams = array(
84 'case_type_id' => $params['case_type_id'],
85 'creator_id' => $params['creator_id'],
86 'status_id' => $params['status_id'],
87 'start_date' => $params['start_date'],
88 'end_date' => CRM_Utils_Array::value('end_date', $params),
89 'subject' => $params['subject'],
90 );
91
92 $caseBAO = CRM_Case_BAO_Case::create($newParams);
93
94 if (!$caseBAO) {
95 throw new API_Exception('Case not created. Please check input params.');
96 }
97
98 foreach ((array) $params['contact_id'] as $cid) {
99 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
100 CRM_Case_BAO_Case::addCaseToContact($contactParams);
101 }
102
103 // Initialize XML processor with $params
104 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
105 $xmlProcessorParams = array(
106 'clientID' => $params['contact_id'],
107 'creatorID' => $params['creator_id'],
108 'standardTimeline' => 1,
109 'activityTypeName' => 'Open Case',
110 'caseID' => $caseBAO->id,
111 'subject' => $params['subject'],
112 'location' => CRM_Utils_Array::value('location', $params),
113 'activity_date_time' => $params['start_date'],
114 'duration' => CRM_Utils_Array::value('duration', $params),
115 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
116 'details' => CRM_Utils_Array::value('details', $params),
117 'custom' => array(),
118 );
119
120 // Do it! :-D
121 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
122
123 // return case
124 $values = array();
125 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
126
127 return civicrm_api3_create_success($values, $params, 'case', 'create', $caseBAO);
128 }
129
130 /**
131 * Adjust Metadata for Get Action
132 *
133 * @param array $params array or parameters determined by getfields
134 */
135 function _civicrm_api3_case_get_spec(&$params) {
136 $params['contact_id']['api.aliases'] = array('client_id');
137 $params['contact_id']['title'] = 'Case Client';
138 $params['creator_id']['api.default'] = 'user_contact_id';
139 }
140
141 /**
142 * Adjust Metadata for Create Action
143 *
144 * @param array $params array or parameters determined by getfields
145 */
146 function _civicrm_api3_case_create_spec(&$params) {
147 $params['contact_id']['api.aliases'] = array('client_id');
148 $params['contact_id']['title'] = 'Case Client';
149 $params['contact_id']['api.required'] = 1;
150 $params['status_id']['api.default'] = 1;
151 $params['medium_id'] = array(
152 'name' => 'medium_id',
153 'title' => 'Activity Medium',
154 );
155 }
156
157 /**
158 * Adjust Metadata for Update action
159 *
160 * @param array $params array or parameters determined by getfields
161 */
162 function _civicrm_api3_case_update_spec(&$params) {
163 $params['id']['api.required'] = 1;
164 }
165
166 /**
167 * Adjust Metadata for Delete action
168 *
169 * @param array $params array or parameters determined by getfields
170 */
171 function _civicrm_api3_case_delete_spec(&$params) {
172 $params['id']['api.required'] = 1;
173 }
174
175 /**
176 * Get details of a particular case, or search for cases, depending on params
177 *
178 * Please provide one (and only one) of the four get/search parameters:
179 *
180 * @param array (
181 * 'id' => if set, will get all available info about a case, including contacts and activities
182 *
183 * // if no case_id provided, this function will use one of the following search parameters:
184 * 'client_id' => finds all cases with a specific client
185 * 'activity_id' => returns the case containing a specific activity
186 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
187 *
188 * {@getfields case_get}
189 *
190 * @return array (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found@access public
191 * @todo Erik Hommel 16 dec 2010 check if all DB fields are returned
192 */
193 function civicrm_api3_case_get($params) {
194 $options = _civicrm_api3_get_options_from_params($params);
195
196 //search by client
197 if (!empty($params['contact_id'])) {
198 $ids = array();
199 foreach ((array) $params['contact_id'] as $cid) {
200 if (is_numeric($cid)) {
201 $ids = array_merge($ids, CRM_Case_BAO_Case::retrieveCaseIdsByContactId($cid, TRUE));
202 }
203 }
204 $cases = array();
205 foreach ($ids as $id) {
206 if ($case = _civicrm_api3_case_read($id, $options)) {
207 $cases[$id] = $case;
208 }
209 }
210 return civicrm_api3_create_success($cases, $params, 'case', 'get');
211 }
212
213 //search by activity
214 if (!empty($params['activity_id'])) {
215 if (!is_numeric($params['activity_id'])) {
216 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
217 }
218 $caseId = CRM_Case_BAO_Case::getCaseIdByActivityId($params['activity_id']);
219 if (!$caseId) {
220 return civicrm_api3_create_success(array(), $params, 'case', 'get');
221 }
222 $case = array($caseId => _civicrm_api3_case_read($caseId, $options));
223 return civicrm_api3_create_success($case, $params, 'case', 'get');
224 }
225
226 //search by contacts
227 if ($contact = CRM_Utils_Array::value('contact_id', $params)) {
228 if (!is_numeric($contact)) {
229 throw new API_Exception('Invalid parameter: contact_id. Must provide a numeric value.');
230 }
231
232 $sql = "
233 SELECT DISTINCT case_id
234 FROM civicrm_relationship
235 WHERE (contact_id_a = $contact
236 OR contact_id_b = $contact)
237 AND case_id IS NOT NULL";
238 $dao = CRM_Core_DAO::executeQuery($sql);
239
240 $cases = array();
241 while ($dao->fetch()) {
242 $cases[$dao->case_id] = _civicrm_api3_case_read($dao->case_id, $options);
243 }
244 return civicrm_api3_create_success($cases, $params, 'case', 'get');
245 }
246
247 // For historic reasons we always return these when an id is provided
248 $caseId = CRM_Utils_Array::value('id', $params);
249 if ($caseId) {
250 $options['return'] = array('contacts' => 1, 'activities' => 1);
251 }
252
253 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case');
254 $cases = array();
255 foreach ($foundcases['values'] as $foundcase) {
256 if ($case = _civicrm_api3_case_read($foundcase['id'], $options)) {
257 $cases[$foundcase['id']] = $case;
258 }
259 }
260
261 return civicrm_api3_create_success($cases, $params, 'case', 'get');
262 }
263
264 /**
265 * Deprecated. Use activity API instead
266 */
267 function civicrm_api3_case_activity_create($params) {
268 return civicrm_api3_activity_create($params);
269 }
270
271 /**
272 * Update a specified case.
273 *
274 * @param array (
275 * //REQUIRED:
276 * 'case_id' => int
277 *
278 * //OPTIONAL
279 * 'status_id' => int
280 * 'start_date' => str datestamp
281 * 'contact_id' => int // case client
282 *
283 * @throws API_Exception
284 * @return array api result array
285 *
286 * @access public
287 */
288 function civicrm_api3_case_update($params) {
289 //check parameters
290 civicrm_api3_verify_mandatory($params, NULL, array('id'));
291
292 // return error if modifying creator id
293 if (array_key_exists('creator_id', $params)) {
294 throw new API_Exception(ts('You cannot update creator id'));
295 }
296
297 $mCaseId = $origContactIds = array();
298
299 // get original contact id and creator id of case
300 if (!empty($params['contact_id'])) {
301 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
302 $origContactId = $origContactIds[1];
303 }
304
305 if (count($origContactIds) > 1) {
306 // check valid orig contact id
307 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
308 throw new API_Exception('Invalid case contact id (orig_contact_id)');
309 }
310 elseif (empty($params['orig_contact_id'])) {
311 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
312 }
313 $origContactId = $params['orig_contact_id'];
314 }
315
316 // check for same contact id for edit Client
317 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
318 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
319 }
320
321 if (!empty($mCaseId[0])) {
322 $params['id'] = $mCaseId[0];
323 }
324
325 $dao = new CRM_Case_BAO_Case();
326 $dao->id = $params['id'];
327
328 $dao->copyValues($params);
329 $dao->save();
330
331 $case = array();
332
333 _civicrm_api3_object_to_array($dao, $case);
334
335 return civicrm_api3_create_success($case, $params, 'case', 'update', $dao);
336 }
337
338 /**
339 * Delete a specified case.
340 *
341 * @param array(
342 //REQUIRED:
343 * 'id' => int
344 *
345 * //OPTIONAL
346 * 'move_to_trash' => bool (defaults to false)
347 *
348 * @return boolean: true if success, else false
349 * {@getfields case_delete}
350 * @access public
351 */
352 function civicrm_api3_case_delete($params) {
353 //check parameters
354 civicrm_api3_verify_mandatory($params, NULL, array('id'));
355
356 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
357 return civicrm_api3_create_success($params, $params, 'case', 'delete');
358 }
359 else {
360 throw new API_Exception('Could not delete case.');
361 }
362 }
363
364 /***********************************/
365 /* */
366 /* INTERNAL FUNCTIONS */
367 /* */
368 /***********************************/
369
370 /**
371 * Internal function to retrieve a case.
372 *
373 * @param int $caseId
374 *
375 * @param $options
376 *
377 * @internal param $params
378 *
379 * @internal param $options
380 *
381 * @return array (reference) case object
382 */
383 function _civicrm_api3_case_read($caseId, $options) {
384 $return = CRM_Utils_Array::value('return', $options, array());
385 $dao = new CRM_Case_BAO_Case();
386 $dao->id = $caseId;
387 if ($dao->find(TRUE)) {
388 $case = array();
389 _civicrm_api3_object_to_array($dao, $case);
390 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
391 $case['client_id'] = $case['contact_id'] = $dao->retrieveContactIdsByCaseId($caseId);
392
393 //handle multi-value case type
394 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
395 $case['case_type_id'] = trim(str_replace($sep, ',', $case['case_type_id']), ',');
396
397 if (!empty($return['contacts'])) {
398 //get case contacts
399 $contacts = CRM_Case_BAO_Case::getcontactNames($caseId);
400 $relations = CRM_Case_BAO_Case::getRelatedContacts($caseId);
401 $case['contacts'] = array_merge($contacts, $relations);
402 }
403 if (!empty($return['activities'])) {
404 //get case activities
405 $case['activities'] = array();
406 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = $caseId";
407 $dao = CRM_Core_DAO::executeQuery($query);
408 while ($dao->fetch()) {
409 $case['activities'][] = $dao->activity_id;
410 }
411 }
412 return $case;
413 }
414 }
415
416 /**
417 * Internal function to format create params for processing
418 */
419 function _civicrm_api3_case_format_params(&$params) {
420 // figure out case type id from case type and vice-versa
421 $caseTypes = CRM_Case_PseudoConstant::caseType('label', FALSE);
422 if (empty($params['case_type_id'])) {
423 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
424 }
425 elseif (empty($params['case_type'])) {
426 $params['case_type'] = $caseTypes[$params['case_type_id']];
427 }
428 // format input with value separators
429 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
430 $params['case_type_id'] = $sep . implode($sep, (array) $params['case_type_id']) . $sep;
431 }