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