CRM-19816 - Improve activity search filters
[civicrm-core.git] / api / v3 / Case.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6a488035
TO
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
b081365f 29 * This api exposes CiviCRM Case objects.
6a488035
TO
30 * Developed by woolman.org
31 *
32 * @package CiviCRM_APIv3
6a488035
TO
33 */
34
35
36/**
244bbdd8 37 * Open a new case, add client and manager roles, and standard timeline.
6a488035 38 *
6c552737 39 * @param array $params
37b8953e 40 *
b081365f 41 * @code
784e85a1 42 * //REQUIRED:
6a488035
TO
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
b081365f 56 * @endcode
6a488035 57 *
784e85a1 58 * @throws API_Exception
a6c01b45 59 * @return array
72b3a70c 60 * api result array
6a488035
TO
61 */
62function civicrm_api3_case_create($params) {
63
64 if (!empty($params['id'])) {
65 return civicrm_api3_case_update($params);
66 }
67
211e2fca
EM
68 civicrm_api3_verify_mandatory($params, NULL, array(
69 'contact_id',
70 'subject',
71 array('case_type', 'case_type_id'))
72 );
6a488035
TO
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'])) {
784e85a1 77 throw new API_Exception('Invalid case_type. No such case type exists.');
6a488035
TO
78 }
79 if (empty($params['case_type'])) {
784e85a1 80 throw new API_Exception('Invalid case_type_id. No such case type exists.');
6a488035
TO
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) {
784e85a1 96 throw new API_Exception('Case not created. Please check input params.');
6a488035
TO
97 }
98
99 foreach ((array) $params['contact_id'] as $cid) {
100 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
b53bcc5d 101 CRM_Case_BAO_CaseContact::create($contactParams);
6a488035
TO
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
244bbdd8 128 return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
6a488035
TO
129}
130
11e09c59 131/**
2fb1dd66 132 * Adjust Metadata for Get Action.
6a488035 133 *
cf470720 134 * @param array $params
2fb1dd66 135 * Parameters determined by getfields.
6a488035
TO
136 */
137function _civicrm_api3_case_get_spec(&$params) {
d142432b
EM
138 $params['contact_id'] = array(
139 'api.aliases' => array('client_id'),
140 'title' => 'Case Client',
48bdb3cd 141 'description' => 'Contact id of one or more clients to retrieve cases for',
d142432b 142 'type' => CRM_Utils_Type::T_INT,
48bdb3cd
CW
143 );
144 $params['activity_id'] = array(
145 'title' => 'Case Activity',
146 'description' => 'Id of an activity in the case',
147 'type' => CRM_Utils_Type::T_INT,
d142432b 148 );
6a488035
TO
149}
150
11e09c59 151/**
2fb1dd66 152 * Adjust Metadata for Create Action.
6a488035 153 *
cf470720 154 * @param array $params
b081365f 155 * Array of parameters determined by getfields.
6a488035
TO
156 */
157function _civicrm_api3_case_create_spec(&$params) {
d142432b
EM
158 $params['contact_id'] = array(
159 'api.aliases' => array('client_id'),
160 'title' => 'Case Client',
48bdb3cd 161 'description' => 'Contact id of case client(s)',
d142432b
EM
162 'api.required' => 1,
163 'type' => CRM_Utils_Type::T_INT,
164 );
6a488035 165 $params['status_id']['api.default'] = 1;
8ae90f85 166 $params['status_id']['api.aliases'] = array('case_status');
941feb14
EM
167 $params['creator_id']['api.default'] = 'user_contact_id';
168 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
b05e6d0d 169 $params['creator_id']['title'] = 'Case Created By';
ca11b9da 170 $params['start_date']['api.default'] = 'now';
16c0ec8d
CW
171 $params['medium_id'] = array(
172 'name' => 'medium_id',
173 'title' => 'Activity Medium',
d142432b 174 'type' => CRM_Utils_Type::T_INT,
16c0ec8d 175 );
6a488035
TO
176}
177
11e09c59 178/**
2fb1dd66 179 * Adjust Metadata for Update action.
6a488035 180 *
cf470720 181 * @param array $params
b081365f 182 * Array of parameters determined by getfields.
6a488035
TO
183 */
184function _civicrm_api3_case_update_spec(&$params) {
185 $params['id']['api.required'] = 1;
186}
187
11e09c59 188/**
c1a920f1 189 * Adjust Metadata for Delete action.
6a488035 190 *
cf470720 191 * @param array $params
b081365f 192 * Array of parameters determined by getfields.
6a488035
TO
193 */
194function _civicrm_api3_case_delete_spec(&$params) {
195 $params['id']['api.required'] = 1;
196}
197
6a488035 198/**
211e2fca 199 * Get details of a particular case, or search for cases, depending on params.
6a488035
TO
200 *
201 * Please provide one (and only one) of the four get/search parameters:
202 *
6c552737
TO
203 * @param array $params
204 * 'id' => if set, will get all available info about a case, including contacts and activities
6a488035 205 *
6c552737
TO
206 * // if no case_id provided, this function will use one of the following search parameters:
207 * 'client_id' => finds all cases with a specific client
208 * 'activity_id' => returns the case containing a specific activity
209 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
6a488035 210 *
77b97be7 211 * @throws API_Exception
a6c01b45 212 * @return array
72b3a70c 213 * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
6a488035
TO
214 */
215function civicrm_api3_case_get($params) {
216 $options = _civicrm_api3_get_options_from_params($params);
48bdb3cd
CW
217 $sql = CRM_Utils_SQL_Select::fragment();
218
219 // Add clause to search by client
6a488035 220 if (!empty($params['contact_id'])) {
48bdb3cd
CW
221 $contacts = array();
222 foreach ((array) $params['contact_id'] as $c) {
223 if (!CRM_Utils_Rule::positiveInteger($c)) {
224 throw new API_Exception('Invalid parameter: contact_id. Must provide numeric value(s).');
6a488035 225 }
48bdb3cd 226 $contacts[] = $c;
6a488035 227 }
48bdb3cd
CW
228 $sql
229 ->join('civicrm_case_contact', 'INNER JOIN civicrm_case_contact ON civicrm_case_contact.case_id = a.id')
230 ->where('civicrm_case_contact.contact_id IN (' . implode(',', $contacts) . ')');
6a488035
TO
231 }
232
48bdb3cd 233 // Add clause to search by activity
6a488035 234 if (!empty($params['activity_id'])) {
48bdb3cd 235 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
784e85a1 236 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
6a488035 237 }
48bdb3cd
CW
238 $activityId = $params['activity_id'];
239 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
240 if ($originalId) {
241 $activityId .= ',' . $originalId;
6a488035 242 }
48bdb3cd
CW
243 $sql
244 ->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
245 ->where("civicrm_case_activity.activity_id IN ($activityId)");
6a488035 246 }
f21557af 247
a54ac083
CW
248 $foundcases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'Case', $sql);
249
abd06efc
CW
250 if (empty($options['is_count'])) {
251 // For historic reasons we return these by default only when fetching a case by id
252 if (!empty($params['id']) && empty($options['return'])) {
253 $options['return'] = array(
254 'contacts' => 1,
255 'activities' => 1,
256 'contact_id' => 1,
257 );
258 }
e01eccc0 259
abd06efc
CW
260 foreach ($foundcases['values'] as &$case) {
261 _civicrm_api3_case_read($case, $options);
262 }
35671d00 263 }
f21557af 264
a54ac083 265 return $foundcases;
6a488035
TO
266}
267
268/**
35823763
EM
269 * Deprecated API.
270 *
271 * Use activity API instead.
9657ccf2
EM
272 *
273 * @param array $params
274 *
275 * @throws API_Exception
276 * @return array
6a488035
TO
277 */
278function civicrm_api3_case_activity_create($params) {
a14e9d08
CW
279 require_once "api/v3/Activity.php";
280 return civicrm_api3_activity_create($params) + array(
281 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
282 );
283}
284
285/**
35823763
EM
286 * Declare deprecated api functions.
287 *
a14e9d08 288 * @deprecated api notice
a6c01b45 289 * @return array
16b10e64 290 * Array of deprecated actions
a14e9d08
CW
291 */
292function _civicrm_api3_case_deprecation() {
293 return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
6a488035
TO
294}
295
296/**
297 * Update a specified case.
298 *
6c552737
TO
299 * @param array $params
300 * //REQUIRED:
301 * 'case_id' => int
6a488035 302 *
6c552737
TO
303 * //OPTIONAL
304 * 'status_id' => int
305 * 'start_date' => str datestamp
306 * 'contact_id' => int // case client
6a488035 307 *
784e85a1 308 * @throws API_Exception
a6c01b45 309 * @return array
72b3a70c 310 * api result array
6a488035
TO
311 */
312function civicrm_api3_case_update($params) {
e720ce6e
CB
313 if (!isset($params['case_id']) && isset($params['id'])) {
314 $params['case_id'] = $params['id'];
315 }
316
6a488035
TO
317 //check parameters
318 civicrm_api3_verify_mandatory($params, NULL, array('id'));
319
784e85a1 320 // return error if modifying creator id
6a488035 321 if (array_key_exists('creator_id', $params)) {
784e85a1 322 throw new API_Exception(ts('You cannot update creator id'));
6a488035
TO
323 }
324
784e85a1 325 $mCaseId = $origContactIds = array();
6a488035
TO
326
327 // get original contact id and creator id of case
328 if (!empty($params['contact_id'])) {
c2e81506 329 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
6a488035
TO
330 $origContactId = $origContactIds[1];
331 }
332
333 if (count($origContactIds) > 1) {
334 // check valid orig contact id
335 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
784e85a1 336 throw new API_Exception('Invalid case contact id (orig_contact_id)');
6a488035
TO
337 }
338 elseif (empty($params['orig_contact_id'])) {
784e85a1 339 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
6a488035
TO
340 }
341 $origContactId = $params['orig_contact_id'];
342 }
343
344 // check for same contact id for edit Client
345 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
346 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
347 }
348
349 if (!empty($mCaseId[0])) {
c2e81506 350 $params['id'] = $mCaseId[0];
6a488035
TO
351 }
352
353 $dao = new CRM_Case_BAO_Case();
354 $dao->id = $params['id'];
355
356 $dao->copyValues($params);
357 $dao->save();
358
359 $case = array();
6a488035
TO
360 _civicrm_api3_object_to_array($dao, $case);
361
a54ac083 362 return civicrm_api3_create_success(array($dao->id => $case), $params, 'Case', 'update', $dao);
6a488035
TO
363}
364
365/**
366 * Delete a specified case.
367 *
6c552737 368 * @param array $params
37b8953e 369 *
244bbdd8 370 * @code
6c552737
TO
371 * //REQUIRED:
372 * 'id' => int
6a488035 373 *
6c552737
TO
374 * //OPTIONAL
375 * 'move_to_trash' => bool (defaults to false)
244bbdd8 376 * @endcode
6a488035 377 *
77b97be7 378 * @throws API_Exception
5c766a0b 379 * @return bool
72b3a70c 380 * true if success, else false
6a488035
TO
381 */
382function civicrm_api3_case_delete($params) {
383 //check parameters
384 civicrm_api3_verify_mandatory($params, NULL, array('id'));
385
386 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
244bbdd8 387 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
6a488035
TO
388 }
389 else {
784e85a1 390 throw new API_Exception('Could not delete case.');
6a488035
TO
391 }
392}
393
6a488035 394/**
a54ac083 395 * Augment a case with extra data.
6a488035 396 *
a54ac083 397 * @param array $case
e9ff5391 398 * @param array $options
6a488035 399 */
a54ac083
CW
400function _civicrm_api3_case_read(&$case, $options) {
401 if (empty($options['return']) || !empty($options['return']['contact_id'])) {
6a488035 402 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
a54ac083
CW
403 $case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id']);
404 }
405 if (!empty($options['return']['contacts'])) {
406 //get case contacts
407 $contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
408 $relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
409 $case['contacts'] = array_merge($contacts, $relations);
410 }
411 if (!empty($options['return']['activities'])) {
412 //get case activities
413 $case['activities'] = array();
414 $query = "SELECT activity_id FROM civicrm_case_activity WHERE case_id = %1";
415 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($case['id'], 'Integer')));
416 while ($dao->fetch()) {
417 $case['activities'][] = $dao->activity_id;
6a488035 418 }
6a488035
TO
419 }
420}
421
422/**
61fe4988 423 * Internal function to format create params for processing.
9657ccf2
EM
424 *
425 * @param array $params
6a488035
TO
426 */
427function _civicrm_api3_case_format_params(&$params) {
6a488035 428 // figure out case type id from case type and vice-versa
1be6caec 429 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
6a488035
TO
430 if (empty($params['case_type_id'])) {
431 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
3f25e694
TO
432
433 // DEPRECATED: lookup by label for backward compatibility
434 if (!$params['case_type_id']) {
435 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
436 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
61fe4988 437 $params['case_type'] = $caseTypes[$params['case_type_id']];
3f25e694 438 }
6a488035
TO
439 }
440 elseif (empty($params['case_type'])) {
441 $params['case_type'] = $caseTypes[$params['case_type_id']];
442 }
6a488035 443}
ff9340a4
CW
444
445/**
446 * It actually works a lot better to use the CaseContact api instead of the Case api
447 * for entityRef fields so we can perform the necessary joins,
448 * so we pass off getlist requests to the CaseContact api.
449 *
450 * @param array $params
451 * @return mixed
452 */
453function civicrm_api3_case_getList($params) {
454 require_once 'api/v3/Generic/Getlist.php';
455 require_once 'api/v3/CaseContact.php';
456 $params['id_field'] = 'case_id';
457 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
458 $params['description_field'] = array(
459 'case_id',
460 'case_id.case_type_id.title',
461 'case_id.subject',
462 'case_id.status_id',
463 'case_id.start_date',
464 );
465 $apiRequest = array(
466 'entity' => 'CaseContact',
467 'action' => 'getlist',
468 'params' => $params,
469 );
470 return civicrm_api3_generic_getList($apiRequest);
471}
472
473/**
474 * Needed due to the above override
475 * @param $params
476 * @param $apiRequest
477 */
478function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
479 require_once 'api/v3/Generic/Getlist.php';
480 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
481}