CRM-14449 api custom data behaviour - preliminary tidy up
[civicrm-core.git] / api / v3 / Case.php
CommitLineData
6a488035 1<?php
6a488035
TO
2
3/*
4 +--------------------------------------------------------------------+
731a0992 5 | CiviCRM version 4.5 |
6a488035 6 +--------------------------------------------------------------------+
731a0992 7 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
731a0992 35 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
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 * @return sucessfully opened case
60 *
61 * @access public
62 * {@getfields case_create}
63 */
64function civicrm_api3_case_create($params) {
65
66 if (!empty($params['id'])) {
67 return civicrm_api3_case_update($params);
68 }
69
70 civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'subject', array('case_type', 'case_type_id')));
71 _civicrm_api3_case_format_params($params);
72
73 // If format_params didn't find what it was looking for, return error
74 if (empty($params['case_type_id'])) {
75 return civicrm_api3_create_error('Invalid case_type. No such case type exists.');
76 }
77 if (empty($params['case_type'])) {
78 return civicrm_api3_create_error('Invalid case_type_id. No such case type exists.');
79 }
80
81 // Fixme: can we safely pass raw params to the BAO?
82 $newParams = array(
83 'case_type_id' => $params['case_type_id'],
84 'creator_id' => $params['creator_id'],
85 'status_id' => $params['status_id'],
86 'start_date' => $params['start_date'],
87 'end_date' => CRM_Utils_Array::value('end_date', $params),
88 'subject' => $params['subject'],
89 );
90
91 $caseBAO = CRM_Case_BAO_Case::create($newParams);
92
93 if (!$caseBAO) {
94 return civicrm_api3_create_error('Case not created. Please check input params.');
95 }
96
97 foreach ((array) $params['contact_id'] as $cid) {
98 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
99 CRM_Case_BAO_Case::addCaseToContact($contactParams);
100 }
101
102 // Initialize XML processor with $params
103 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
104 $xmlProcessorParams = array(
105 'clientID' => $params['contact_id'],
106 'creatorID' => $params['creator_id'],
107 'standardTimeline' => 1,
108 'activityTypeName' => 'Open Case',
109 'caseID' => $caseBAO->id,
110 'subject' => $params['subject'],
111 'location' => CRM_Utils_Array::value('location', $params),
112 'activity_date_time' => $params['start_date'],
113 'duration' => CRM_Utils_Array::value('duration', $params),
114 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
115 'details' => CRM_Utils_Array::value('details', $params),
116 'custom' => array(),
117 );
118
119 // Do it! :-D
120 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
121
122 // return case
123 $values = array();
124 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
125
126 return civicrm_api3_create_success($values, $params, 'case', 'create', $caseBAO);
127}
128
11e09c59 129/**
6a488035
TO
130 * Adjust Metadata for Get Action
131 *
132 * @param array $params array or parameters determined by getfields
133 */
134function _civicrm_api3_case_get_spec(&$params) {
135 $params['contact_id']['api.aliases'] = array('client_id');
136 $params['contact_id']['title'] = 'Case Client';
9af2925b 137 $params['creator_id']['api.default'] = 'user_contact_id';
6a488035
TO
138}
139
11e09c59 140/**
6a488035
TO
141 * Adjust Metadata for Create Action
142 *
143 * @param array $params array or parameters determined by getfields
144 */
145function _civicrm_api3_case_create_spec(&$params) {
146 $params['contact_id']['api.aliases'] = array('client_id');
147 $params['contact_id']['title'] = 'Case Client';
148 $params['contact_id']['api.required'] = 1;
149 $params['status_id']['api.default'] = 1;
16c0ec8d
CW
150 $params['medium_id'] = array(
151 'name' => 'medium_id',
152 'title' => 'Activity Medium',
153 );
6a488035
TO
154}
155
11e09c59 156/**
6a488035
TO
157 * Adjust Metadata for Update action
158 *
159 * @param array $params array or parameters determined by getfields
160 */
161function _civicrm_api3_case_update_spec(&$params) {
162 $params['id']['api.required'] = 1;
163}
164
11e09c59 165/**
6a488035
TO
166 * Adjust Metadata for Delete action
167 *
168 * @param array $params array or parameters determined by getfields
169 */
170function _civicrm_api3_case_delete_spec(&$params) {
171 $params['id']['api.required'] = 1;
172}
173
6a488035
TO
174/**
175 * Get details of a particular case, or search for cases, depending on params
176 *
177 * Please provide one (and only one) of the four get/search parameters:
178 *
179 * @param array(
180 'id' => if set, will get all available info about a case, including contacts and activities
181 *
182 * // if no case_id provided, this function will use one of the following search parameters:
183 * 'client_id' => finds all cases with a specific client
184 * 'activity_id' => returns the case containing a specific activity
185 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
186 *
187 * {@getfields case_get}
188 *
189 * @return (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
190 * @access public
191 * @todo Erik Hommel 16 dec 2010 check if all DB fields are returned
192 */
193function civicrm_api3_case_get($params) {
194 $options = _civicrm_api3_get_options_from_params($params);
195
6a488035
TO
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 return civicrm_api3_create_error('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 return civicrm_api3_create_error('Invalid parameter: contact_id. Must provide a numeric value.');
230 }
231
232 $sql = "
233SELECT 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";
9af2925b 238 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
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 }
f21557af 246
e01eccc0
RB
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
f21557af 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');
6a488035
TO
262}
263
264/**
265 * Deprecated. Use activity API instead
266 */
267function 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 * @return Updated case
284 *
285 * @access public
286 *
287 */
288function civicrm_api3_case_update($params) {
289 //check parameters
290 civicrm_api3_verify_mandatory($params, NULL, array('id'));
291
292 // return error if modifing creator id
293 if (array_key_exists('creator_id', $params)) {
294 return civicrm_api3_create_error(ts('You cannot update creator id'));
295 }
296
297 $mCaseId = array();
298 $origContactIds = array();
299
300 // get original contact id and creator id of case
301 if (!empty($params['contact_id'])) {
c2e81506 302 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
6a488035
TO
303 $origContactId = $origContactIds[1];
304 }
305
306 if (count($origContactIds) > 1) {
307 // check valid orig contact id
308 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
309 return civicrm_api3_create_error('Invalid case contact id (orig_contact_id)');
310 }
311 elseif (empty($params['orig_contact_id'])) {
312 return civicrm_api3_create_error('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
313 }
314 $origContactId = $params['orig_contact_id'];
315 }
316
317 // check for same contact id for edit Client
318 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
319 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
320 }
321
322 if (!empty($mCaseId[0])) {
c2e81506 323 $params['id'] = $mCaseId[0];
6a488035
TO
324 }
325
326 $dao = new CRM_Case_BAO_Case();
327 $dao->id = $params['id'];
328
329 $dao->copyValues($params);
330 $dao->save();
331
332 $case = array();
333
334 _civicrm_api3_object_to_array($dao, $case);
335
336 return civicrm_api3_create_success($case, $params, 'case', 'update', $dao);
337}
338
339/**
340 * Delete a specified case.
341 *
342 * @param array(
343 //REQUIRED:
344 * 'id' => int
345 *
346 * //OPTIONAL
347 * 'move_to_trash' => bool (defaults to false)
348 *
349 * @return boolean: true if success, else false
350 * {@getfields case_delete}
351 * @access public
352 */
353function civicrm_api3_case_delete($params) {
354 //check parameters
355 civicrm_api3_verify_mandatory($params, NULL, array('id'));
356
357 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
358 return civicrm_api3_create_success($params, $params, 'case', 'delete');
359 }
360 else {
361 return civicrm_api3_create_error('Could not delete case.');
362 }
363}
364
365/***********************************/
366/* */
367/* INTERNAL FUNCTIONS */
368/* */
369/***********************************/
370
371/**
372 * Internal function to retrieve a case.
373 *
374 * @param int $caseId
375 *
9af2925b
EM
376 * @param $params
377 *
378 * @internal param $options
6a488035 379 *
9af2925b 380 * @return array (reference) case object
6a488035
TO
381 */
382function _civicrm_api3_case_read($caseId, $options) {
383 $return = CRM_Utils_Array::value('return', $options, array());
384 $dao = new CRM_Case_BAO_Case();
385 $dao->id = $caseId;
386 if ($dao->find(TRUE)) {
387 $case = array();
388 _civicrm_api3_object_to_array($dao, $case);
389 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
390 $case['client_id'] = $case['contact_id'] = $dao->retrieveContactIdsByCaseId($caseId);
391
392 //handle multi-value case type
393 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
394 $case['case_type_id'] = trim(str_replace($sep, ',', $case['case_type_id']), ',');
395
396 if (!empty($return['contacts'])) {
397 //get case contacts
398 $contacts = CRM_Case_BAO_Case::getcontactNames($caseId);
399 $relations = CRM_Case_BAO_Case::getRelatedContacts($caseId);
400 $case['contacts'] = array_merge($contacts, $relations);
401 }
402 if (!empty($return['activities'])) {
403 //get case activities
404 $case['activities'] = array();
405 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = $caseId";
406 $dao = CRM_Core_DAO::executeQuery($query);
407 while ($dao->fetch()) {
408 $case['activities'][] = $dao->activity_id;
409 }
410 }
411 return $case;
412 }
413}
414
415/**
416 * Internal function to format create params for processing
417 */
418function _civicrm_api3_case_format_params(&$params) {
6a488035
TO
419 // figure out case type id from case type and vice-versa
420 $caseTypes = CRM_Case_PseudoConstant::caseType('label', FALSE);
421 if (empty($params['case_type_id'])) {
422 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
423 }
424 elseif (empty($params['case_type'])) {
425 $params['case_type'] = $caseTypes[$params['case_type_id']];
426 }
427 // format input with value separators
428 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
429 $params['case_type_id'] = $sep . implode($sep, (array) $params['case_type_id']) . $sep;
430}