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