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