Merge pull request #5010 from eileenmcnaughton/rebase2
[civicrm-core.git] / api / v3 / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 * File for the CiviCRM APIv3 Case functions
30 * Developed by woolman.org
31 *
32 * @package CiviCRM_APIv3
33 * @subpackage API_Case
34 * @copyright CiviCRM LLC (c) 2004-2014
35 */
36
37
38 /**
39 * Open a new case, add client and manager roles, and add standard timeline.
40 *
41 * @param array $params
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 *
57 * @throws API_Exception
58 * @return array
59 * api result array
60 */
61 function civicrm_api3_case_create($params) {
62
63 if (!empty($params['id'])) {
64 return civicrm_api3_case_update($params);
65 }
66
67 civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'subject', array('case_type', 'case_type_id')));
68 _civicrm_api3_case_format_params($params);
69
70 // If format_params didn't find what it was looking for, return error
71 if (empty($params['case_type_id'])) {
72 throw new API_Exception('Invalid case_type. No such case type exists.');
73 }
74 if (empty($params['case_type'])) {
75 throw new API_Exception('Invalid case_type_id. No such case type exists.');
76 }
77
78 // Fixme: can we safely pass raw params to the BAO?
79 $newParams = array(
80 'case_type_id' => $params['case_type_id'],
81 'creator_id' => $params['creator_id'],
82 'status_id' => $params['status_id'],
83 'start_date' => $params['start_date'],
84 'end_date' => CRM_Utils_Array::value('end_date', $params),
85 'subject' => $params['subject'],
86 );
87
88 $caseBAO = CRM_Case_BAO_Case::create($newParams);
89
90 if (!$caseBAO) {
91 throw new API_Exception('Case not created. Please check input params.');
92 }
93
94 foreach ((array) $params['contact_id'] as $cid) {
95 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
96 CRM_Case_BAO_Case::addCaseToContact($contactParams);
97 }
98
99 // Initialize XML processor with $params
100 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
101 $xmlProcessorParams = array(
102 'clientID' => $params['contact_id'],
103 'creatorID' => $params['creator_id'],
104 'standardTimeline' => 1,
105 'activityTypeName' => 'Open Case',
106 'caseID' => $caseBAO->id,
107 'subject' => $params['subject'],
108 'location' => CRM_Utils_Array::value('location', $params),
109 'activity_date_time' => $params['start_date'],
110 'duration' => CRM_Utils_Array::value('duration', $params),
111 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
112 'details' => CRM_Utils_Array::value('details', $params),
113 'custom' => array(),
114 );
115
116 // Do it! :-D
117 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
118
119 // return case
120 $values = array();
121 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
122
123 return civicrm_api3_create_success($values, $params, 'case', 'create', $caseBAO);
124 }
125
126 /**
127 * Adjust Metadata for Get Action.
128 *
129 * @param array $params
130 * Parameters determined by getfields.
131 */
132 function _civicrm_api3_case_get_spec(&$params) {
133 $params['contact_id']['api.aliases'] = array('client_id');
134 $params['contact_id']['title'] = 'Case Client';
135 }
136
137 /**
138 * Adjust Metadata for Create Action.
139 *
140 * @param array $params
141 * Array or parameters determined by getfields.
142 */
143 function _civicrm_api3_case_create_spec(&$params) {
144 $params['contact_id']['api.aliases'] = array('client_id');
145 $params['contact_id']['title'] = 'Case Client';
146 $params['contact_id']['api.required'] = 1;
147 $params['status_id']['api.default'] = 1;
148 $params['status_id']['api.aliases'] = array('case_status');
149 $params['creator_id']['api.default'] = 'user_contact_id';
150 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
151 $params['creator_id']['title'] = 'Case Created By';
152 $params['start_date']['api.default'] = 'now';
153 $params['medium_id'] = array(
154 'name' => 'medium_id',
155 'title' => 'Activity Medium',
156 );
157 }
158
159 /**
160 * Adjust Metadata for Update action.
161 *
162 * @param array $params
163 * 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
173 * 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 $params
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 * @throws API_Exception
193 * @return array
194 * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
195 */
196 function civicrm_api3_case_get($params) {
197 $options = _civicrm_api3_get_options_from_params($params);
198 //search by client
199 if (!empty($params['contact_id'])) {
200 $ids = array();
201 foreach ((array) $params['contact_id'] as $cid) {
202 if (is_numeric($cid)) {
203 $ids = array_merge($ids, CRM_Case_BAO_Case::retrieveCaseIdsByContactId($cid, TRUE));
204 }
205 }
206 $cases = array();
207 foreach ($ids as $id) {
208 if ($case = _civicrm_api3_case_read($id, $options)) {
209 $cases[$id] = $case;
210 }
211 }
212 return civicrm_api3_create_success($cases, $params, 'case', 'get');
213 }
214
215 //search by activity
216 if (!empty($params['activity_id'])) {
217 if (!is_numeric($params['activity_id'])) {
218 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
219 }
220 $caseId = CRM_Case_BAO_Case::getCaseIdByActivityId($params['activity_id']);
221 if (!$caseId) {
222 return civicrm_api3_create_success(array(), $params, 'case', 'get');
223 }
224 $case = array($caseId => _civicrm_api3_case_read($caseId, $options));
225 return civicrm_api3_create_success($case, $params, 'case', 'get');
226 }
227
228 //search by contacts
229 if (($contact = CRM_Utils_Array::value('contact_id', $params)) != FALSE) {
230 if (!is_numeric($contact)) {
231 throw new API_Exception('Invalid parameter: contact_id. Must provide a numeric value.');
232 }
233
234 $sql = "
235 SELECT DISTINCT case_id
236 FROM civicrm_relationship
237 WHERE (contact_id_a = $contact
238 OR contact_id_b = $contact)
239 AND case_id IS NOT NULL";
240 $dao = CRM_Core_DAO::executeQuery($sql);
241
242 $cases = array();
243 while ($dao->fetch()) {
244 $cases[$dao->case_id] = _civicrm_api3_case_read($dao->case_id, $options);
245 }
246 return civicrm_api3_create_success($cases, $params, 'case', 'get');
247 }
248
249 // For historic reasons we always return these when an id is provided
250 $caseId = CRM_Utils_Array::value('id', $params);
251 if ($caseId) {
252 $options['return'] = array('contacts' => 1, 'activities' => 1);
253 }
254
255 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case');
256 $cases = array();
257 foreach ($foundcases['values'] as $foundcase) {
258 if ($case = _civicrm_api3_case_read($foundcase['id'], $options)) {
259 $cases[$foundcase['id']] = $case;
260 }
261 }
262
263 return civicrm_api3_create_success($cases, $params, 'case', 'get');
264 }
265
266 /**
267 * Deprecated. Use activity API instead
268 *
269 * @param array $params
270 *
271 * @throws API_Exception
272 * @return array
273 */
274 function civicrm_api3_case_activity_create($params) {
275 require_once "api/v3/Activity.php";
276 return civicrm_api3_activity_create($params) + array(
277 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
278 );
279 }
280
281 /**
282 * @deprecated api notice
283 * @return array
284 * Array of deprecated actions
285 */
286 function _civicrm_api3_case_deprecation() {
287 return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
288 }
289
290 /**
291 * Update a specified case.
292 *
293 * @param array $params
294 * //REQUIRED:
295 * 'case_id' => int
296 *
297 * //OPTIONAL
298 * 'status_id' => int
299 * 'start_date' => str datestamp
300 * 'contact_id' => int // case client
301 *
302 * @throws API_Exception
303 * @return array
304 * api result array
305 *
306 */
307 function civicrm_api3_case_update($params) {
308 //check parameters
309 civicrm_api3_verify_mandatory($params, NULL, array('id'));
310
311 // return error if modifying creator id
312 if (array_key_exists('creator_id', $params)) {
313 throw new API_Exception(ts('You cannot update creator id'));
314 }
315
316 $mCaseId = $origContactIds = array();
317
318 // get original contact id and creator id of case
319 if (!empty($params['contact_id'])) {
320 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
321 $origContactId = $origContactIds[1];
322 }
323
324 if (count($origContactIds) > 1) {
325 // check valid orig contact id
326 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
327 throw new API_Exception('Invalid case contact id (orig_contact_id)');
328 }
329 elseif (empty($params['orig_contact_id'])) {
330 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
331 }
332 $origContactId = $params['orig_contact_id'];
333 }
334
335 // check for same contact id for edit Client
336 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
337 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
338 }
339
340 if (!empty($mCaseId[0])) {
341 $params['id'] = $mCaseId[0];
342 }
343
344 $dao = new CRM_Case_BAO_Case();
345 $dao->id = $params['id'];
346
347 $dao->copyValues($params);
348 $dao->save();
349
350 $case = array();
351
352 _civicrm_api3_object_to_array($dao, $case);
353 $values[$dao->id] = $case;
354
355 return civicrm_api3_create_success($values, $params, 'case', 'update', $dao);
356 }
357
358 /**
359 * Delete a specified case.
360 *
361 * @param array $params
362 * //REQUIRED:
363 * 'id' => int
364 *
365 * //OPTIONAL
366 * 'move_to_trash' => bool (defaults to false)
367 *
368 * @throws API_Exception
369 * @return bool
370 * true if success, else false
371 */
372 function civicrm_api3_case_delete($params) {
373 //check parameters
374 civicrm_api3_verify_mandatory($params, NULL, array('id'));
375
376 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
377 return civicrm_api3_create_success($params, $params, 'case', 'delete');
378 }
379 else {
380 throw new API_Exception('Could not delete case.');
381 }
382 }
383
384 /***********************************/
385 /* */
386 /* INTERNAL FUNCTIONS */
387 /* */
388 /***********************************/
389
390 /**
391 * Internal function to retrieve a case.
392 *
393 * @param int $caseId
394 *
395 * @param $options
396 *
397 * @return array
398 * case object
399 */
400 function _civicrm_api3_case_read($caseId, $options) {
401 $return = CRM_Utils_Array::value('return', $options, array());
402 $dao = new CRM_Case_BAO_Case();
403 $dao->id = $caseId;
404 if ($dao->find(TRUE)) {
405 $case = array();
406 _civicrm_api3_object_to_array($dao, $case);
407 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
408 $case['client_id'] = $case['contact_id'] = $dao->retrieveContactIdsByCaseId($caseId);
409
410 if (!empty($return['contacts'])) {
411 //get case contacts
412 $contacts = CRM_Case_BAO_Case::getcontactNames($caseId);
413 $relations = CRM_Case_BAO_Case::getRelatedContacts($caseId);
414 $case['contacts'] = array_merge($contacts, $relations);
415 }
416 if (!empty($return['activities'])) {
417 //get case activities
418 $case['activities'] = array();
419 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = $caseId";
420 $dao = CRM_Core_DAO::executeQuery($query);
421 while ($dao->fetch()) {
422 $case['activities'][] = $dao->activity_id;
423 }
424 }
425 return $case;
426 }
427 }
428
429 /**
430 * Internal function to format create params for processing
431 *
432 * @param array $params
433 */
434 function _civicrm_api3_case_format_params(&$params) {
435 // figure out case type id from case type and vice-versa
436 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
437 if (empty($params['case_type_id'])) {
438 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
439
440 // DEPRECATED: lookup by label for backward compatibility
441 if (!$params['case_type_id']) {
442 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
443 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
444 $params['case_type'] = $caseTypes[$params['case_type_id']]; // label => name
445 }
446 }
447 elseif (empty($params['case_type'])) {
448 $params['case_type'] = $caseTypes[$params['case_type_id']];
449 }
450 }