Merge remote-tracking branch 'upstream/4.4' into 4.4-4.5-2014-10-01-19-08-00
[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 }
139
140 /**
141 * Adjust Metadata for Create Action
142 *
143 * @param array $params array or parameters determined by getfields
144 */
145 function _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;
150 $params['creator_id']['api.default'] = 'user_contact_id';
151 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
152 $params['creator_id']['title'] = 'Case Created By';
153 $params['start_date']['api.default'] = 'now';
154 $params['medium_id'] = array(
155 'name' => 'medium_id',
156 'title' => 'Activity Medium',
157 );
158 }
159
160 /**
161 * Adjust Metadata for Update action
162 *
163 * @param array $params array or parameters determined by getfields
164 */
165 function _civicrm_api3_case_update_spec(&$params) {
166 $params['id']['api.required'] = 1;
167 }
168
169 /**
170 * Adjust Metadata for Delete action
171 *
172 * @param array $params array or parameters determined by getfields
173 */
174 function _civicrm_api3_case_delete_spec(&$params) {
175 $params['id']['api.required'] = 1;
176 }
177
178 /**
179 * Get details of a particular case, or search for cases, depending on params
180 *
181 * Please provide one (and only one) of the four get/search parameters:
182 *
183 * @param array (
184 * 'id' => if set, will get all available info about a case, including contacts and activities
185 *
186 * // if no case_id provided, this function will use one of the following search parameters:
187 * 'client_id' => finds all cases with a specific client
188 * 'activity_id' => returns the case containing a specific activity
189 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
190 *
191 * {@getfields case_get}
192 *
193 * @throws API_Exception
194 * @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
195 * @todo Erik Hommel 16 dec 2010 check if all DB fields are returned
196 */
197 function civicrm_api3_case_get($params) {
198 $options = _civicrm_api3_get_options_from_params($params);
199 //search by client
200 if (!empty($params['contact_id'])) {
201 $ids = array();
202 foreach ((array) $params['contact_id'] as $cid) {
203 if (is_numeric($cid)) {
204 $ids = array_merge($ids, CRM_Case_BAO_Case::retrieveCaseIdsByContactId($cid, TRUE));
205 }
206 }
207 $cases = array();
208 foreach ($ids as $id) {
209 if ($case = _civicrm_api3_case_read($id, $options)) {
210 $cases[$id] = $case;
211 }
212 }
213 return civicrm_api3_create_success($cases, $params, 'case', 'get');
214 }
215
216 //search by activity
217 if (!empty($params['activity_id'])) {
218 if (!is_numeric($params['activity_id'])) {
219 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
220 }
221 $caseId = CRM_Case_BAO_Case::getCaseIdByActivityId($params['activity_id']);
222 if (!$caseId) {
223 return civicrm_api3_create_success(array(), $params, 'case', 'get');
224 }
225 $case = array($caseId => _civicrm_api3_case_read($caseId, $options));
226 return civicrm_api3_create_success($case, $params, 'case', 'get');
227 }
228
229 //search by contacts
230 if ($contact = CRM_Utils_Array::value('contact_id', $params)) {
231 if (!is_numeric($contact)) {
232 throw new API_Exception('Invalid parameter: contact_id. Must provide a numeric value.');
233 }
234
235 $sql = "
236 SELECT DISTINCT case_id
237 FROM civicrm_relationship
238 WHERE (contact_id_a = $contact
239 OR contact_id_b = $contact)
240 AND case_id IS NOT NULL";
241 $dao = CRM_Core_DAO::executeQuery($sql);
242
243 $cases = array();
244 while ($dao->fetch()) {
245 $cases[$dao->case_id] = _civicrm_api3_case_read($dao->case_id, $options);
246 }
247 return civicrm_api3_create_success($cases, $params, 'case', 'get');
248 }
249
250 // For historic reasons we always return these when an id is provided
251 $caseId = CRM_Utils_Array::value('id', $params);
252 if ($caseId) {
253 $options['return'] = array('contacts' => 1, 'activities' => 1);
254 }
255
256 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case');
257 $cases = array();
258 foreach ($foundcases['values'] as $foundcase) {
259 if ($case = _civicrm_api3_case_read($foundcase['id'], $options)) {
260 $cases[$foundcase['id']] = $case;
261 }
262 }
263
264 return civicrm_api3_create_success($cases, $params, 'case', 'get');
265 }
266
267 /**
268 * Deprecated. Use activity API instead
269 *
270 * @param array $params
271 *
272 * @throws API_Exception
273 * @return array
274 */
275 function civicrm_api3_case_activity_create($params) {
276 return civicrm_api3_activity_create($params);
277 }
278
279 /**
280 * Update a specified case.
281 *
282 * @param array (
283 * //REQUIRED:
284 * 'case_id' => int
285 *
286 * //OPTIONAL
287 * 'status_id' => int
288 * 'start_date' => str datestamp
289 * 'contact_id' => int // case client
290 *
291 * @throws API_Exception
292 * @return array api result array
293 *
294 * @access public
295 */
296 function civicrm_api3_case_update($params) {
297 //check parameters
298 civicrm_api3_verify_mandatory($params, NULL, array('id'));
299
300 // return error if modifying creator id
301 if (array_key_exists('creator_id', $params)) {
302 throw new API_Exception(ts('You cannot update creator id'));
303 }
304
305 $mCaseId = $origContactIds = array();
306
307 // get original contact id and creator id of case
308 if (!empty($params['contact_id'])) {
309 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
310 $origContactId = $origContactIds[1];
311 }
312
313 if (count($origContactIds) > 1) {
314 // check valid orig contact id
315 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
316 throw new API_Exception('Invalid case contact id (orig_contact_id)');
317 }
318 elseif (empty($params['orig_contact_id'])) {
319 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
320 }
321 $origContactId = $params['orig_contact_id'];
322 }
323
324 // check for same contact id for edit Client
325 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
326 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
327 }
328
329 if (!empty($mCaseId[0])) {
330 $params['id'] = $mCaseId[0];
331 }
332
333 $dao = new CRM_Case_BAO_Case();
334 $dao->id = $params['id'];
335
336 $dao->copyValues($params);
337 $dao->save();
338
339 $case = array();
340
341 _civicrm_api3_object_to_array($dao, $case);
342 $values[$dao->id] = $case;
343
344 return civicrm_api3_create_success($values, $params, 'case', 'update', $dao);
345 }
346
347 /**
348 * Delete a specified case.
349 *
350 * @param array (
351 * //REQUIRED:
352 * 'id' => int
353 *
354 * //OPTIONAL
355 * 'move_to_trash' => bool (defaults to false)
356 *
357 * @throws API_Exception
358 * @return boolean: true if success, else false
359 * {@getfields case_delete}
360 * @access public
361 */
362 function civicrm_api3_case_delete($params) {
363 //check parameters
364 civicrm_api3_verify_mandatory($params, NULL, array('id'));
365
366 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
367 return civicrm_api3_create_success($params, $params, 'case', 'delete');
368 }
369 else {
370 throw new API_Exception('Could not delete case.');
371 }
372 }
373
374 /***********************************/
375 /* */
376 /* INTERNAL FUNCTIONS */
377 /* */
378 /***********************************/
379
380 /**
381 * Internal function to retrieve a case.
382 *
383 * @param int $caseId
384 *
385 * @param $options
386 *
387 * @internal param $params
388 *
389 * @internal param $options
390 *
391 * @return array (reference) case object
392 */
393 function _civicrm_api3_case_read($caseId, $options) {
394 $return = CRM_Utils_Array::value('return', $options, array());
395 $dao = new CRM_Case_BAO_Case();
396 $dao->id = $caseId;
397 if ($dao->find(TRUE)) {
398 $case = array();
399 _civicrm_api3_object_to_array($dao, $case);
400 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
401 $case['client_id'] = $case['contact_id'] = $dao->retrieveContactIdsByCaseId($caseId);
402
403 if (!empty($return['contacts'])) {
404 //get case contacts
405 $contacts = CRM_Case_BAO_Case::getcontactNames($caseId);
406 $relations = CRM_Case_BAO_Case::getRelatedContacts($caseId);
407 $case['contacts'] = array_merge($contacts, $relations);
408 }
409 if (!empty($return['activities'])) {
410 //get case activities
411 $case['activities'] = array();
412 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = $caseId";
413 $dao = CRM_Core_DAO::executeQuery($query);
414 while ($dao->fetch()) {
415 $case['activities'][] = $dao->activity_id;
416 }
417 }
418 return $case;
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']]; // label => name
438 }
439 }
440 elseif (empty($params['case_type'])) {
441 $params['case_type'] = $caseTypes[$params['case_type_id']];
442 }
443 }