Refactor based on comments from @davialexandre
[civicrm-core.git] / api / v3 / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 _civicrm_api3_case_format_params($params);
64
65 if (empty($params['id'])) {
66 // Creating a new case, so make sure we have the necessary parameters
67 civicrm_api3_verify_mandatory($params, NULL, array(
68 'contact_id',
69 'subject',
70 array('case_type', 'case_type_id')
71 )
72 );
73 }
74 else {
75 // Update an existing case
76 // FIXME: Some of this logic should move to the BAO object?
77 // FIXME: Should we check if case with ID actually exists?
78 if (!isset($params['case_id']) && isset($params['id'])) {
79 $params['case_id'] = $params['id'];
80 }
81
82 if (array_key_exists('creator_id', $params)) {
83 throw new API_Exception(ts('You cannot update creator id'));
84 }
85
86 $mergedCaseId = $origContactIds = array();
87
88 // get original contact id and creator id of case
89 if (!empty($params['contact_id'])) {
90 // FIXME: CRM_Case_BAO_Case::retrieveContactIdsByCaseId returns a 1-based array (1 is the first element)
91 // It should really return a 0-based array for consistency.
92 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
93 $origContactId = $origContactIds[1];
94 }
95
96 // FIXME: Refactor as separate method to get contactId
97 if (count($origContactIds) > 1) {
98 // check valid orig contact id
99 if (empty($params['orig_contact_id'])) {
100 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
101 }
102 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
103 throw new API_Exception('Invalid case contact id (orig_contact_id)');
104 }
105 $origContactId = $params['orig_contact_id'];
106 }
107
108 // check for same contact id for edit Client
109 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
110 $mergedCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
111 }
112
113 // If we merged cases then update the merged case
114 if (!empty($mergedCaseId[0])) {
115 $params['id'] = $mergedCaseId[0];
116 }
117 }
118
119 // Create/update the case
120 $caseBAO = CRM_Case_BAO_Case::create($params);
121
122 if (!$caseBAO) {
123 throw new API_Exception('Case not created. Please check input params.');
124 }
125
126 foreach ((array) $params['contact_id'] as $cid) {
127 $contactParams = array('case_id' => $caseBAO->id, 'contact_id' => $cid);
128 CRM_Case_BAO_CaseContact::create($contactParams);
129 }
130
131 if (!isset($params['id'])) {
132 // As the API was not passed an id we have created a new case.
133 // Only run the xmlProcessor for new cases to get all configuration for the new case.
134 _civicrm_api3_case_create_xmlProcessor($params, $caseBAO);
135 }
136
137 // return case
138 $values = array();
139 _civicrm_api3_object_to_array($caseBAO, $values[$caseBAO->id]);
140
141 // Add custom data
142 if (isset($params['custom'])) {
143 _civicrm_api3_custom_data_get($values[$caseBAO->id], TRUE, 'case', $caseBAO->id);
144 }
145
146 return civicrm_api3_create_success($values, $params, 'Case', 'create', $caseBAO);
147 }
148
149 /**
150 * When creating a new case, run the xmlProcessor to get all necessary params/configuration
151 * for the new case, as cases use an xml file to store their configuration.
152 * @param $params
153 * @param $caseBAO
154 */
155 function _civicrm_api3_case_create_xmlProcessor($params, $caseBAO) {
156 // Format params for xmlProcessor
157 if (isset($caseBAO->id)) { $params['id'] = $caseBAO->id; }
158
159 // Initialize XML processor with $params
160 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
161 $xmlProcessorParams = array(
162 'clientID' => CRM_Utils_Array::value('contact_id', $params),
163 'creatorID' => CRM_Utils_Array::value('creator_id', $params),
164 'standardTimeline' => 1,
165 'activityTypeName' => 'Open Case',
166 'caseID' => CRM_Utils_Array::value('id', $params),
167 'subject' => CRM_Utils_Array::value('subject', $params),
168 'location' => CRM_Utils_Array::value('location', $params),
169 'activity_date_time' => CRM_Utils_Array::value('start_date', $params),
170 'duration' => CRM_Utils_Array::value('duration', $params),
171 'medium_id' => CRM_Utils_Array::value('medium_id', $params),
172 'details' => CRM_Utils_Array::value('details', $params),
173 'custom' => array(),
174 );
175
176 // Do it! :-D
177 $xmlProcessor->run($params['case_type'], $xmlProcessorParams);
178 }
179
180 /**
181 * Adjust Metadata for Get Action.
182 *
183 * @param array $params
184 * Parameters determined by getfields.
185 */
186 function _civicrm_api3_case_get_spec(&$params) {
187 $params['contact_id'] = array(
188 'api.aliases' => array('client_id'),
189 'title' => 'Case Client',
190 'description' => 'Contact id of one or more clients to retrieve cases for',
191 'type' => CRM_Utils_Type::T_INT,
192 );
193 $params['activity_id'] = array(
194 'title' => 'Case Activity',
195 'description' => 'Id of an activity in the case',
196 'type' => CRM_Utils_Type::T_INT,
197 );
198 $params['tag_id'] = array(
199 'title' => 'Tags',
200 'description' => 'Find activities with specified tags.',
201 'type' => 1,
202 'FKClassName' => 'CRM_Core_DAO_Tag',
203 'FKApiName' => 'Tag',
204 'supports_joins' => TRUE,
205 );
206 }
207
208 /**
209 * Adjust Metadata for Create Action.
210 *
211 * @param array $params
212 * Array of parameters determined by getfields.
213 */
214 function _civicrm_api3_case_create_spec(&$params) {
215 $params['contact_id'] = array(
216 'api.aliases' => array('client_id'),
217 'title' => 'Case Client',
218 'description' => 'Contact id of case client(s)',
219 'api.required' => 1,
220 'type' => CRM_Utils_Type::T_INT,
221 );
222 $params['status_id']['api.default'] = 1;
223 $params['status_id']['api.aliases'] = array('case_status');
224 $params['creator_id']['api.default'] = 'user_contact_id';
225 $params['creator_id']['type'] = CRM_Utils_Type::T_INT;
226 $params['creator_id']['title'] = 'Case Created By';
227 $params['start_date']['api.default'] = 'now';
228 $params['medium_id'] = array(
229 'name' => 'medium_id',
230 'title' => 'Activity Medium',
231 'type' => CRM_Utils_Type::T_INT,
232 );
233 }
234
235 /**
236 * Adjust Metadata for Update action.
237 *
238 * @param array $params
239 * Array of parameters determined by getfields.
240 */
241 function _civicrm_api3_case_update_spec(&$params) {
242 $params['id']['api.required'] = 1;
243 }
244
245 /**
246 * Adjust Metadata for Delete action.
247 *
248 * @param array $params
249 * Array of parameters determined by getfields.
250 */
251 function _civicrm_api3_case_delete_spec(&$params) {
252 $params['id']['api.required'] = 1;
253 }
254
255 /**
256 * Get details of a particular case, or search for cases, depending on params.
257 *
258 * Please provide one (and only one) of the four get/search parameters:
259 *
260 * @param array $params
261 * 'id' => if set, will get all available info about a case, including contacts and activities
262 *
263 * // if no case_id provided, this function will use one of the following search parameters:
264 * 'client_id' => finds all cases with a specific client
265 * 'activity_id' => returns the case containing a specific activity
266 * 'contact_id' => finds all cases associated with a contact (in any role, not just client)
267 * $params CRM_Utils_SQL_Select $sql
268 * Other apis wishing to wrap & extend this one can pass in a $sql object with extra clauses
269 *
270 * @throws API_Exception
271 * @return array
272 * (get mode, case_id provided): Array with case details, case roles, case activity ids, (search mode, case_id not provided): Array of cases found
273 */
274 function civicrm_api3_case_get($params, $sql = NULL) {
275 $options = _civicrm_api3_get_options_from_params($params);
276 if (!is_a($sql, 'CRM_Utils_SQL_Select')) {
277 $sql = CRM_Utils_SQL_Select::fragment();
278 }
279
280 // Add clause to search by client
281 if (!empty($params['contact_id'])) {
282 // Legacy support - this field historically supports a nonstandard format of array(1,2,3) as a synonym for array('IN' => array(1,2,3))
283 if (is_array($params['contact_id'])) {
284 $operator = CRM_Utils_Array::first(array_keys($params['contact_id']));
285 if (!in_array($operator, \CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
286 $params['contact_id'] = array('IN' => $params['contact_id']);
287 }
288 }
289 else {
290 $params['contact_id'] = array('=' => $params['contact_id']);
291 }
292 $clause = CRM_Core_DAO::createSQLFilter('contact_id', $params['contact_id']);
293 $sql->where("a.id IN (SELECT case_id FROM civicrm_case_contact WHERE $clause)");
294 }
295
296 // Order by case contact (primary client)
297 // Ex: "contact_id", "contact_id.display_name", "contact_id.sort_name DESC".
298 if (!empty($options['sort']) && strpos($options['sort'], 'contact_id') !== FALSE) {
299 $sort = explode(', ', $options['sort']);
300 $contactSort = NULL;
301 foreach ($sort as $index => &$sortString) {
302 if (strpos($sortString, 'contact_id') === 0) {
303 $contactSort = $sortString;
304 $sortString = '(1)';
305 // Get sort field and direction
306 list($sortField, $dir) = array_pad(explode(' ', $contactSort), 2, 'ASC');
307 list(, $sortField) = array_pad(explode('.', $sortField), 2, 'id');
308 // Validate inputs
309 if (!array_key_exists($sortField, CRM_Contact_DAO_Contact::fieldKeys()) || ($dir != 'ASC' && $dir != 'DESC')) {
310 throw new API_Exception("Unknown field specified for sort. Cannot order by '$contactSort'");
311 }
312 $sql->orderBy("case_contact.$sortField $dir", NULL, $index);
313 }
314 }
315 // Remove contact sort params so the basic_get function doesn't see them
316 $params['options']['sort'] = implode(', ', $sort);
317 unset($params['option_sort'], $params['option.sort'], $params['sort']);
318 // Add necessary joins to the first case client
319 if ($contactSort) {
320 $sql->join('ccc', 'LEFT JOIN (SELECT * FROM civicrm_case_contact WHERE id IN (SELECT MIN(id) FROM civicrm_case_contact GROUP BY case_id)) AS ccc ON ccc.case_id = a.id');
321 $sql->join('case_contact', 'LEFT JOIN civicrm_contact AS case_contact ON ccc.contact_id = case_contact.id AND case_contact.is_deleted <> 1');
322 }
323 }
324
325 // Add clause to search by activity
326 if (!empty($params['activity_id'])) {
327 if (!CRM_Utils_Rule::positiveInteger($params['activity_id'])) {
328 throw new API_Exception('Invalid parameter: activity_id. Must provide a numeric value.');
329 }
330 $activityId = $params['activity_id'];
331 $originalId = CRM_Core_DAO::getFieldValue('CRM_Activity_BAO_Activity', $activityId, 'original_id');
332 if ($originalId) {
333 $activityId .= ',' . $originalId;
334 }
335 $sql
336 ->join('civicrm_case_activity', 'INNER JOIN civicrm_case_activity ON civicrm_case_activity.case_id = a.id')
337 ->where("civicrm_case_activity.activity_id IN ($activityId)");
338 }
339
340 // Clause to search by tag
341 if (!empty($params['tag_id'])) {
342 $dummySpec = array();
343 _civicrm_api3_validate_integer($params, 'tag_id', $dummySpec, 'Case');
344 if (!is_array($params['tag_id'])) {
345 $params['tag_id'] = array('=' => $params['tag_id']);
346 }
347 $clause = \CRM_Core_DAO::createSQLFilter('tag_id', $params['tag_id']);
348 if ($clause) {
349 $sql->where('a.id IN (SELECT entity_id FROM civicrm_entity_tag WHERE entity_table = "civicrm_case" AND !clause)', array('!clause' => $clause));
350 }
351 }
352
353 $cases = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), array('sequential' => 0) + $params, TRUE, 'Case', $sql);
354
355 if (empty($options['is_count']) && !empty($cases['values'])) {
356 // For historic reasons we return these by default only when fetching a case by id
357 if (!empty($params['id']) && is_numeric($params['id']) && empty($options['return'])) {
358 $options['return'] = array(
359 'contacts' => 1,
360 'activities' => 1,
361 'contact_id' => 1,
362 );
363 }
364
365 _civicrm_api3_case_read($cases['values'], $options);
366
367 // We disabled sequential to keep the list indexed for case_read(). Now add it back.
368 if (!empty($params['sequential'])) {
369 $cases['values'] = array_values($cases['values']);
370 }
371 }
372
373 return $cases;
374 }
375
376 /**
377 * Deprecated API.
378 *
379 * Use activity API instead.
380 *
381 * @param array $params
382 *
383 * @throws API_Exception
384 * @return array
385 */
386 function civicrm_api3_case_activity_create($params) {
387 require_once "api/v3/Activity.php";
388 return civicrm_api3_activity_create($params) + array(
389 'deprecated' => CRM_Utils_Array::value('activity_create', _civicrm_api3_case_deprecation()),
390 );
391 }
392
393 /**
394 * Add a timeline to a case.
395 *
396 * @param array $params
397 *
398 * @throws API_Exception
399 * @return array
400 */
401 function civicrm_api3_case_addtimeline($params) {
402 $caseType = CRM_Case_BAO_Case::getCaseType($params['case_id'], 'name');
403 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
404 $xmlProcessorParams = array(
405 'clientID' => CRM_Case_BAO_Case::getCaseClients($params['case_id']),
406 'creatorID' => $params['creator_id'],
407 'standardTimeline' => 0,
408 'activity_date_time' => $params['activity_date_time'],
409 'caseID' => $params['case_id'],
410 'caseType' => $caseType,
411 'activitySetName' => $params['timeline'],
412 );
413 $xmlProcessor->run($caseType, $xmlProcessorParams);
414 return civicrm_api3_create_success();
415 }
416
417 /**
418 * Adjust Metadata for addtimeline action.
419 *
420 * @param array $params
421 * Array of parameters determined by getfields.
422 */
423 function _civicrm_api3_case_addtimeline_spec(&$params) {
424 $params['case_id'] = array(
425 'title' => 'Case ID',
426 'description' => 'Id of case to update',
427 'type' => CRM_Utils_Type::T_INT,
428 'api.required' => 1,
429 );
430 $params['timeline'] = array(
431 'title' => 'Timeline',
432 'description' => 'Name of activity set',
433 'type' => CRM_Utils_Type::T_STRING,
434 'api.required' => 1,
435 );
436 $params['activity_date_time'] = array(
437 'api.default' => 'now',
438 'title' => 'Activity date time',
439 'description' => 'Timeline start date',
440 'type' => CRM_Utils_Type::T_DATE,
441 );
442 $params['creator_id'] = array(
443 'api.default' => 'user_contact_id',
444 'title' => 'Activity creator',
445 'description' => 'Contact id of timeline creator',
446 'type' => CRM_Utils_Type::T_INT,
447 );
448 }
449
450 /**
451 * Merge 2 cases.
452 *
453 * @param array $params
454 *
455 * @throws API_Exception
456 * @return array
457 */
458 function civicrm_api3_case_merge($params) {
459 $clients1 = CRM_Case_BAO_Case::getCaseClients($params['case_id_1']);
460 $clients2 = CRM_Case_BAO_Case::getCaseClients($params['case_id_2']);
461 CRM_Case_BAO_Case::mergeCases($clients1[0], $params['case_id_1'], $clients2[0], $params['case_id_2']);
462 return civicrm_api3_create_success();
463 }
464
465 /**
466 * Adjust Metadata for merge action.
467 *
468 * @param array $params
469 * Array of parameters determined by getfields.
470 */
471 function _civicrm_api3_case_merge_spec(&$params) {
472 $params['case_id_1'] = array(
473 'title' => 'Case ID 1',
474 'description' => 'Id of main case',
475 'type' => CRM_Utils_Type::T_INT,
476 'api.required' => 1,
477 );
478 $params['case_id_2'] = array(
479 'title' => 'Case ID 2',
480 'description' => 'Id of second case',
481 'type' => CRM_Utils_Type::T_INT,
482 'api.required' => 1,
483 );
484 }
485
486 /**
487 * Declare deprecated api functions.
488 *
489 * @deprecated api notice
490 * @return array
491 * Array of deprecated actions
492 */
493 function _civicrm_api3_case_deprecation() {
494 return array('activity_create' => 'Case api "activity_create" action is deprecated. Use the activity api instead.');
495 }
496
497 /**
498 * Update a specified case.
499 *
500 * @param array $params
501 * //REQUIRED:
502 * 'case_id' => int
503 *
504 * //OPTIONAL
505 * 'status_id' => int
506 * 'start_date' => str datestamp
507 * 'contact_id' => int // case client
508 *
509 * @throws API_Exception
510 * @return array
511 * api result array
512 */
513 function civicrm_api3_case_update($params) {
514 if (!isset($params['case_id']) && isset($params['id'])) {
515 $params['case_id'] = $params['id'];
516 }
517
518 //check parameters
519 civicrm_api3_verify_mandatory($params, NULL, array('id'));
520
521 // return error if modifying creator id
522 if (array_key_exists('creator_id', $params)) {
523 throw new API_Exception(ts('You cannot update creator id'));
524 }
525
526 $mCaseId = $origContactIds = array();
527
528 // get original contact id and creator id of case
529 if (!empty($params['contact_id'])) {
530 $origContactIds = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($params['id']);
531 $origContactId = $origContactIds[1];
532 }
533
534 if (count($origContactIds) > 1) {
535 // check valid orig contact id
536 if (!empty($params['orig_contact_id']) && !in_array($params['orig_contact_id'], $origContactIds)) {
537 throw new API_Exception('Invalid case contact id (orig_contact_id)');
538 }
539 elseif (empty($params['orig_contact_id'])) {
540 throw new API_Exception('Case is linked with more than one contact id. Provide the required params orig_contact_id to be replaced');
541 }
542 $origContactId = $params['orig_contact_id'];
543 }
544
545 // check for same contact id for edit Client
546 if (!empty($params['contact_id']) && !in_array($params['contact_id'], $origContactIds)) {
547 $mCaseId = CRM_Case_BAO_Case::mergeCases($params['contact_id'], $params['case_id'], $origContactId, NULL, TRUE);
548 }
549
550 if (!empty($mCaseId[0])) {
551 $params['id'] = $mCaseId[0];
552 }
553
554 $dao = new CRM_Case_BAO_Case();
555 $dao->id = $params['id'];
556
557 $dao->copyValues($params);
558 $dao->save();
559
560 $case = array();
561 _civicrm_api3_object_to_array($dao, $case);
562
563 return civicrm_api3_create_success(array($dao->id => $case), $params, 'Case', 'update', $dao);
564 }
565
566 /**
567 * Delete a specified case.
568 *
569 * @param array $params
570 *
571 * @code
572 * //REQUIRED:
573 * 'id' => int
574 *
575 * //OPTIONAL
576 * 'move_to_trash' => bool (defaults to false)
577 * @endcode
578 *
579 * @throws API_Exception
580 * @return mixed
581 */
582 function civicrm_api3_case_delete($params) {
583 //check parameters
584 civicrm_api3_verify_mandatory($params, NULL, array('id'));
585
586 if (CRM_Case_BAO_Case::deleteCase($params['id'], CRM_Utils_Array::value('move_to_trash', $params, FALSE))) {
587 return civicrm_api3_create_success($params, $params, 'Case', 'delete');
588 }
589 else {
590 throw new API_Exception('Could not delete case.');
591 }
592 }
593
594 /**
595 * Case.restore API specification
596 *
597 * @param array $spec description of fields supported by this API call
598 * @return void
599 */
600 function _civicrm_api3_case_restore_spec(&$spec) {
601 $result = civicrm_api3('Case', 'getfields', array('api_action' => 'delete'));
602 $spec = array('id' => $result['values']['id']);
603 }
604
605 /**
606 * Restore a specified case from the trash.
607 *
608 * @param array $params
609 * @throws API_Exception
610 * @return mixed
611 */
612 function civicrm_api3_case_restore($params) {
613 if (CRM_Case_BAO_Case::restoreCase($params['id'])) {
614 return civicrm_api3_create_success($params, $params, 'Case', 'restore');
615 }
616 else {
617 throw new API_Exception('Could not restore case.');
618 }
619 }
620
621 /**
622 * Augment case results with extra data.
623 *
624 * @param array $cases
625 * @param array $options
626 */
627 function _civicrm_api3_case_read(&$cases, $options) {
628 foreach ($cases as &$case) {
629 if (empty($options['return']) || !empty($options['return']['contact_id'])) {
630 // Legacy support for client_id - TODO: in apiv4 remove 'client_id'
631 $case['client_id'] = $case['contact_id'] = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($case['id']);
632 }
633 if (!empty($options['return']['contacts'])) {
634 //get case contacts
635 $contacts = CRM_Case_BAO_Case::getcontactNames($case['id']);
636 $relations = CRM_Case_BAO_Case::getRelatedContacts($case['id']);
637 $case['contacts'] = array_unique(array_merge($contacts, $relations), SORT_REGULAR);
638 }
639 if (!empty($options['return']['activities'])) {
640 // add case activities array - we'll populate them in bulk below
641 $case['activities'] = array();
642 }
643 // Properly render this joined field
644 if (!empty($options['return']['case_type_id.definition'])) {
645 if (!empty($case['case_type_id.definition'])) {
646 list($xml) = CRM_Utils_XML::parseString($case['case_type_id.definition']);
647 }
648 else {
649 $caseTypeId = !empty($case['case_type_id']) ? $case['case_type_id'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $case['id'], 'case_type_id');
650 $caseTypeName = !empty($case['case_type_id.name']) ? $case['case_type_id.name'] : CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name');
651 $xml = CRM_Case_XMLRepository::singleton()->retrieve($caseTypeName);
652 }
653 $case['case_type_id.definition'] = array();
654 if ($xml) {
655 $case['case_type_id.definition'] = CRM_Case_BAO_CaseType::convertXmlToDefinition($xml);
656 }
657 }
658 }
659 // Bulk-load activities
660 if (!empty($options['return']['activities'])) {
661 $query = "SELECT case_id, activity_id FROM civicrm_case_activity WHERE case_id IN (%1)";
662 $params = array(1 => array(implode(',', array_keys($cases)), 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES));
663 $dao = CRM_Core_DAO::executeQuery($query, $params);
664 while ($dao->fetch()) {
665 $cases[$dao->case_id]['activities'][] = $dao->activity_id;
666 }
667 }
668 // Bulk-load tags. Supports joins onto the tag entity.
669 $tagGet = array('tag_id', 'entity_id');
670 foreach (array_keys($options['return']) as $key) {
671 if (strpos($key, 'tag_id.') === 0) {
672 $tagGet[] = $key;
673 $options['return']['tag_id'] = 1;
674 }
675 }
676 if (!empty($options['return']['tag_id'])) {
677 $tags = civicrm_api3('EntityTag', 'get', array(
678 'entity_table' => 'civicrm_case',
679 'entity_id' => array('IN' => array_keys($cases)),
680 'return' => $tagGet,
681 'options' => array('limit' => 0),
682 ));
683 foreach ($tags['values'] as $tag) {
684 $key = (int) $tag['entity_id'];
685 unset($tag['entity_id'], $tag['id']);
686 $cases[$key]['tag_id'][$tag['tag_id']] = $tag;
687 }
688 }
689 }
690
691 /**
692 * Internal function to format create params for processing.
693 *
694 * @param array $params
695 */
696 function _civicrm_api3_case_format_params(&$params) {
697 // Format/include custom params
698 $values = array();
699 _civicrm_api3_custom_format_params($params, $values, 'Case');
700 $params = array_merge($params, $values);
701
702 if (empty($params['case_type_id']) && empty($params['case_type'])) {
703 return;
704 }
705
706 // figure out case_type_id from case_type and vice-versa
707 $caseTypes = CRM_Case_PseudoConstant::caseType('name', FALSE);
708 if (empty($params['case_type_id'])) {
709 $params['case_type_id'] = array_search($params['case_type'], $caseTypes);
710
711 // DEPRECATED: lookup by label for backward compatibility
712 if (!$params['case_type_id']) {
713 $caseTypeLabels = CRM_Case_PseudoConstant::caseType('title', FALSE);
714 $params['case_type_id'] = array_search($params['case_type'], $caseTypeLabels);
715 $params['case_type'] = $caseTypes[$params['case_type_id']];
716 }
717 }
718 elseif (empty($params['case_type'])) {
719 $params['case_type'] = $caseTypes[$params['case_type_id']];
720 }
721 }
722
723
724 /**
725 * It actually works a lot better to use the CaseContact api instead of the Case api
726 * for entityRef fields so we can perform the necessary joins,
727 * so we pass off getlist requests to the CaseContact api.
728 *
729 * @param array $params
730 * @return mixed
731 */
732 function civicrm_api3_case_getList($params) {
733 require_once 'api/v3/Generic/Getlist.php';
734 require_once 'api/v3/CaseContact.php';
735 //CRM:19956 - Assign case_id param if both id and case_id is passed to retrieve the case
736 if (!empty($params['id']) && !empty($params['params']) && !empty($params['params']['case_id'])) {
737 $params['params']['case_id'] = array('IN' => $params['id']);
738 unset($params['id']);
739 }
740 $params['id_field'] = 'case_id';
741 $params['label_field'] = $params['search_field'] = 'contact_id.sort_name';
742 $params['description_field'] = array(
743 'case_id',
744 'case_id.case_type_id.title',
745 'case_id.subject',
746 'case_id.status_id',
747 'case_id.start_date',
748 );
749 $apiRequest = array(
750 'version' => 3,
751 'entity' => 'CaseContact',
752 'action' => 'getlist',
753 'params' => $params,
754 );
755 return civicrm_api3_generic_getList($apiRequest);
756 }
757
758 /**
759 * Needed due to the above override
760 * @param $params
761 * @param $apiRequest
762 */
763 function _civicrm_api3_case_getlist_spec(&$params, $apiRequest) {
764 require_once 'api/v3/Generic/Getlist.php';
765 _civicrm_api3_generic_getlist_spec($params, $apiRequest);
766 }