Merge branch 4.5 into master
[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 /**
40 * Open a new case, add client and manager roles, and add standard timeline
41 *
42 * @param array $params
43 * //REQUIRED:
44 * 'case_type_id' => int OR
45 * 'case_type' => str (provide one or the other)
46 * 'contact_id' => int // case client
47 * 'subject' => str
48 *
49 * //OPTIONAL
50 * 'medium_id' => int // see civicrm option values for possibilities
51 * 'creator_id' => int // case manager, default to the logged in user
52 * 'status_id' => int // defaults to 1 "ongoing"
53 * 'location' => str
54 * 'start_date' => str datestamp // defaults to: date('YmdHis')
55 * 'duration' => int // in minutes
56 * 'details' => str // html format
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('contact_id', 'subject', array('case_type', 'case_type_id')));
69 _civicrm_api3_case_format_params($params);
70
71 // If format_params didn't find what it was looking for, return error
72 if (empty($params['case_type_id'])) {
73 throw new API_Exception('Invalid case_type. No such case type exists.');
74 }
75 if (empty($params['case_type'])) {
76 throw new API_Exception('Invalid case_type_id. No such case type exists.');
77 }
78
79 // Fixme: can we safely pass raw params to the BAO?
80 $newParams = array(
81 'case_type_id' => $params['case_type_id'],
82 'creator_id' => $params['creator_id'],
83 'status_id' => $params['status_id'],
84 'start_date' => $params['start_date'],
85 'end_date' => CRM_Utils_Array::value('end_date', $params),
86 'subject' => $params['subject'],
87 );
88
89 $caseBAO = CRM_Case_BAO_Case::create($newParams);
90
91 if (!$caseBAO) {
92 throw new API_Exception('Case not created. Please check input params.');
93 }
94
95 foreach ((array) $params['contact_id'] as $cid) {
96 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
97 CRM_Case_BAO_Case::addCaseToContact($contactParams);
98 }
99
100 // Initialize XML processor with $params
101 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
102 $xmlProcessorParams = array(
103 'clientID' => $params['contact_id'],
104 'creatorID' => $params['creator_id'],
105 'standardTimeline' => 1,
106 'activityTypeName' => 'Open Case',
107 'caseID' => $caseBAO->id,
108 'subject' => $params['subject'],
109 'location' => CRM_Utils_Array::value('location', $params),
110 'activity_date_time' => $params['start_date'],
111 'duration' => CRM_Utils_Array::value('duration', $params),
112 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
113 'details' => CRM_Utils_Array::value('details', $params),
114 'custom' => array(),
115 );
116
117 // Do it! :-D
118 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
119
120 // return case
121 $values = array();
122 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
123
124 return civicrm_api3_create_success($values, $params, 'case', 'create', $caseBAO);
125 }
126
127 /**
128 * Adjust Metadata for Get Action
129 *
130 * @param array $params
131 * Array or parameters determined by getfields.
132 */
133 function _civicrm_api3_case_get_spec(&$params) {
134 $params['contact_id']['api.aliases'] = array('client_id');
135 $params['contact_id']['title'] = 'Case Client';
136 }
137
138 /**
139 * Adjust Metadata for Create Action
140 *
141 * @param array $params
142 * Array or parameters determined by getfields.
143 */
144 function _civicrm_api3_case_create_spec(&$params) {
145 $params['contact_id']['api.aliases'] = array('client_id');
146 $params['contact_id']['title'] = 'Case Client';
147 $params['contact_id']['api.required'] = 1;
148 $params['status_id']['api.default'] = 1;
149 $params['status_id']['api.aliases'] = array('case_status');
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
164 * 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
174 * Array or parameters determined by getfields.
175 */
176 function _civicrm_api3_case_delete_spec(&$params) {
177 $params['id']['api.required'] = 1;
178 }
179
180 /**
181 * Get details of a particular case, or search for cases, depending on params
182 *
183 * Please provide one (and only one) of the four get/search parameters:
184 *
185 * @param array $params
186 * 'id' => if set, will get all available info about a case, including contacts and activities
187 *
188 * // if no case_id provided, this function will use one of the following search parameters:
189 * 'client_id' => finds all cases with a specific client
190 * 'activity_id' => returns the case containing a specific activity
191 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
192 *
193 * @throws API_Exception
194 * @return array
195 * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
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)) != FALSE) {
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 require_once "api/v3/Activity.php";
277 return civicrm_api3_activity_create($params) + array(
278 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
279 );
280 }
281
282 /**
283 * @deprecated api notice
284 * @return array
285 * 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 $params
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
305 * api result array
306 *
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 $params
363 * //REQUIRED:
364 * 'id' => int
365 *
366 * //OPTIONAL
367 * 'move_to_trash' => bool (defaults to false)
368 *
369 * @throws API_Exception
370 * @return bool
371 * true if success, else false
372 */
373 function civicrm_api3_case_delete($params) {
374 //check parameters
375 civicrm_api3_verify_mandatory($params, NULL, array('id'));
376
377 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
378 return civicrm_api3_create_success($params, $params, 'case', 'delete');
379 }
380 else {
381 throw new API_Exception('Could not delete case.');
382 }
383 }
384
385 /***********************************/
386 /* */
387 /* INTERNAL FUNCTIONS */
388 /* */
389 /***********************************/
390
391 /**
392 * Internal function to retrieve a case.
393 *
394 * @param int $caseId
395 *
396 * @param $options
397 *
398 * @return array
399 * 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 }