Merge pull request #12650 from JMAConsulting/dev-core-321
[civicrm-core.git] / api / v3 / Generic.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
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 * @package CiviCRM_APIv3
30 */
31
32 /**
33 * Get information about fields for a given api request.
34 *
35 * Getfields information is used for documentation, validation, default setting
36 * We first query the scheme using the $dao->fields function & then augment
37 * that information by calling the _spec functions that apply to the relevant function
38 * Note that we use 'unique' field names as described in the xml/schema files
39 * for get requests & just field name for create. This is because some get functions
40 * access multiple objects e.g. contact api accesses is_deleted from the activity
41 * table & from the contact table
42 *
43 * @param array $apiRequest
44 * Api request as an array. Keys are.
45 * - entity: string
46 * - action: string
47 * - version: string
48 * - function: callback (mixed)
49 * - params: array, varies
50 *
51 * @param bool $unique
52 * Determines whether to key by unique field names (only affects get-type) actions
53 *
54 * @return array
55 * API success object
56 */
57 function civicrm_api3_generic_getfields($apiRequest, $unique = TRUE) {
58 static $results = array();
59 if ((CRM_Utils_Array::value('cache_clear', $apiRequest['params']))) {
60 $results = array();
61 // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
62 CRM_Core_PseudoConstant::flush();
63 if (!empty($apiRequest['params']['fieldname'])) {
64 CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
65 }
66 if (!empty($apiRequest['params']['option_group_id'])) {
67 $optionGroupName = civicrm_api('option_group', 'getvalue', array(
68 'version' => 3,
69 'id' => $apiRequest['params']['option_group_id'],
70 'return' => 'name',
71 ));
72 if (is_string($optionGroupName)) {
73 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
74 }
75 }
76 }
77 $entity = $apiRequest['entity'];
78 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
79 $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
80 $action = CRM_Utils_Array::value('action', $apiRequest['params']);
81 $sequential = empty($apiRequest['params']['sequential']) ? 0 : 1;
82 $apiRequest['params']['options'] = CRM_Utils_Array::value('options', $apiRequest['params'], array());
83 $optionsToResolve = (array) CRM_Utils_Array::value('get_options', $apiRequest['params']['options'], array());
84
85 if (!$action || $action == 'getvalue' || $action == 'getcount') {
86 $action = 'get';
87 }
88 // If no options, return results from cache
89 if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
90 && isset($action, $results[$entity . $subentity][$sequential])) {
91 return $results[$entity . $subentity][$action][$sequential];
92 }
93 // defaults based on data model and API policy
94 switch ($action) {
95 case 'getfields':
96 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
97 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
98
99 case 'create':
100 case 'update':
101 case 'replace':
102 $unique = FALSE;
103 case 'get':
104 case 'getsingle':
105 case 'getcount':
106 case 'getstat':
107 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
108 if (empty($metadata['id'])) {
109 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
110 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
111 $metadata['id'] = $metadata[$lowercase_entity . '_id'];
112 unset($metadata[$lowercase_entity . '_id']);
113 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
114 }
115 }
116 else {
117 // really the preference would be to set the unique name in the xml
118 // question is which is a less risky fix this close to a release - setting in xml for the known failure
119 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
120 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
121 // inconsistency
122 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
123 }
124 break;
125
126 case 'delete':
127 $metadata = array(
128 'id' => array(
129 'title' => $entity . ' ID',
130 'api.required' => 1,
131 'api.aliases' => array($lowercase_entity . '_id'),
132 'type' => CRM_Utils_Type::T_INT,
133 ));
134 break;
135
136 // Note: adding setvalue case here instead of in a generic spec function because
137 // some APIs override the generic setvalue fn which causes the generic spec to be overlooked.
138 case 'setvalue':
139 $metadata = array(
140 'field' => array(
141 'title' => 'Field name',
142 'api.required' => 1,
143 'type' => CRM_Utils_Type::T_STRING,
144 ),
145 'id' => array(
146 'title' => $entity . ' ID',
147 'api.required' => 1,
148 'type' => CRM_Utils_Type::T_INT,
149 ),
150 'value' => array(
151 'title' => 'Value',
152 'description' => "Field value to set",
153 'api.required' => 1,
154 ),
155 );
156 if (array_intersect(array('all', 'field'), $optionsToResolve)) {
157 $options = civicrm_api3_generic_getfields(array('entity' => $entity, array('params' => array('action' => 'create'))));
158 $metadata['field']['options'] = CRM_Utils_Array::collect('title', $options['values']);
159 }
160 break;
161
162 default:
163 // oddballs are on their own
164 $metadata = array();
165 }
166
167 // Hack for product api to pass tests.
168 if (!is_string($apiRequest['params']['options'])) {
169 // Normalize this for the sake of spec funcions
170 $apiRequest['params']['options']['get_options'] = $optionsToResolve;
171 }
172
173 // find any supplemental information
174 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
175 if ($action == 'getsingle') {
176 $hypApiRequest['action'] = 'get';
177 }
178 try {
179 list ($apiProvider, $hypApiRequest) = \Civi::service('civi_api_kernel')->resolve($hypApiRequest);
180 if (isset($hypApiRequest['function'])) {
181 $helper = '_' . $hypApiRequest['function'] . '_spec';
182 }
183 else {
184 // not implemented MagicFunctionProvider
185 $helper = NULL;
186 }
187 }
188 catch (\Civi\API\Exception\NotImplementedException $e) {
189 $helper = NULL;
190 }
191 if (function_exists($helper)) {
192 // alter
193 $helper($metadata, $apiRequest);
194 }
195
196 foreach ($metadata as $fieldname => $fieldSpec) {
197 // Ensure 'name' is set
198 if (!isset($fieldSpec['name'])) {
199 $metadata[$fieldname]['name'] = $fieldname;
200 }
201 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec);
202
203 // Convert options to "sequential" format
204 if ($sequential && !empty($metadata[$fieldname]['options'])) {
205 $metadata[$fieldname]['options'] = CRM_Utils_Array::makeNonAssociative($metadata[$fieldname]['options']);
206 }
207 }
208
209 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
210 return $results[$entity][$action][$sequential];
211 }
212
213 /**
214 * Get metadata for a field
215 *
216 * @param array $apiRequest
217 *
218 * @return array
219 * API success object
220 */
221 function civicrm_api3_generic_getfield($apiRequest) {
222 $params = $apiRequest['params'];
223 $sequential = !empty($params['sequential']);
224 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $params['name'], $params['action']);
225 if (!$fieldName) {
226 return civicrm_api3_create_error("The field '{$params['name']}' doesn't exist.");
227 }
228 // Turn off sequential to make the field easier to find
229 $apiRequest['params']['sequential'] = 0;
230 if (isset($params['get_options'])) {
231 $apiRequest['params']['options']['get_options_context'] = $params['get_options'];
232 $apiRequest['params']['options']['get_options'] = $fieldName;
233 }
234 $result = civicrm_api3_generic_getfields($apiRequest, FALSE);
235 $result = $result['values'][$fieldName];
236 // Fix sequential options since we forced it off
237 if ($sequential && !empty($result['options'])) {
238 $result['options'] = CRM_Utils_Array::makeNonAssociative($result['options']);
239 }
240 return civicrm_api3_create_success($result, $apiRequest['params'], $apiRequest['entity'], 'getfield');
241 }
242
243 /**
244 * Get metadata for getfield action.
245 *
246 * @param array $params
247 * @param array $apiRequest
248 *
249 * @throws \CiviCRM_API3_Exception
250 * @throws \Exception
251 */
252 function _civicrm_api3_generic_getfield_spec(&$params, $apiRequest) {
253 $params = array(
254 'name' => array(
255 'title' => 'Field name',
256 'description' => 'Name or alias of field to lookup',
257 'api.required' => 1,
258 'type' => CRM_Utils_Type::T_STRING,
259 ),
260 'action' => array(
261 'title' => 'API Action',
262 'api.required' => 1,
263 'type' => CRM_Utils_Type::T_STRING,
264 'api.aliases' => array('api_action'),
265 ),
266 'get_options' => array(
267 'title' => 'Get Options',
268 'description' => 'Context for which to get field options, or null to skip fetching options.',
269 'type' => CRM_Utils_Type::T_STRING,
270 'options' => CRM_Core_DAO::buildOptionsContext(),
271 'api.aliases' => array('context'),
272 ),
273 );
274 // Add available options to these params if requested
275 if (array_intersect(array('all', 'action'), $apiRequest['params']['options']['get_options'])) {
276 $actions = civicrm_api3($apiRequest['entity'], 'getactions');
277 $actions = array_combine($actions['values'], $actions['values']);
278 // Let's not go meta-crazy
279 CRM_Utils_Array::remove($actions, 'getactions', 'getoptions', 'getfields', 'getfield', 'getcount', 'getrefcount', 'getsingle', 'getlist', 'getvalue', 'setvalue', 'update');
280 $params['action']['options'] = $actions;
281 }
282 }
283
284 /**
285 * API return function to reformat results as count.
286 *
287 * @param array $apiRequest
288 * Api request as an array. Keys are.
289 *
290 * @throws API_Exception
291 * @return int
292 * count of results
293 */
294 function civicrm_api3_generic_getcount($apiRequest) {
295 $apiRequest['params']['options']['is_count'] = TRUE;
296 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
297 if (is_numeric(CRM_Utils_Array::value('values', $result))) {
298 return (int) $result['values'];
299 }
300 if (!isset($result['count'])) {
301 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
302 }
303 return $result['count'];
304 }
305
306 /**
307 * API return function to reformat results as single result.
308 *
309 * @param array $apiRequest
310 * Api request as an array. Keys are.
311 *
312 * @return int
313 * count of results
314 */
315 function civicrm_api3_generic_getsingle($apiRequest) {
316 // So the first entity is always result['values'][0].
317 $apiRequest['params']['sequential'] = 1;
318 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
319 if ($result['is_error'] !== 0) {
320 return $result;
321 }
322 if ($result['count'] === 1) {
323 return $result['values'][0];
324 }
325 if ($result['count'] !== 1) {
326 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
327 }
328 return civicrm_api3_create_error("Undefined behavior");
329 }
330
331 /**
332 * API return function to reformat results as single value.
333 *
334 * @param array $apiRequest
335 * Api request as an array. Keys are.
336 *
337 * @return int
338 * count of results
339 */
340 function civicrm_api3_generic_getvalue($apiRequest) {
341 $apiRequest['params']['sequential'] = 1;
342 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
343 if ($result['is_error'] !== 0) {
344 return $result;
345 }
346 if ($result['count'] !== 1) {
347 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
348 return $result;
349 }
350
351 // we only take "return=" as valid options
352 if (!empty($apiRequest['params']['return'])) {
353 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
354 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
355 }
356
357 return $result['values'][0][$apiRequest['params']['return']];
358 }
359
360 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
361 }
362
363 /**
364 * Get count of contact references.
365 *
366 * @param array $params
367 * @param array $apiRequest
368 */
369 function _civicrm_api3_generic_getrefcount_spec(&$params, $apiRequest) {
370 $params['id']['api.required'] = 1;
371 $params['id']['title'] = $apiRequest['entity'] . ' ID';
372 $params['id']['type'] = CRM_Utils_Type::T_INT;
373 }
374
375 /**
376 * API to determine if a record is in-use.
377 *
378 * @param array $apiRequest
379 * Api request as an array.
380 *
381 * @throws API_Exception
382 * @return array
383 * API result (int 0 or 1)
384 */
385 function civicrm_api3_generic_getrefcount($apiRequest) {
386 $entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
387 if (!isset($entityToClassMap[$apiRequest['entity']])) {
388 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
389 }
390 $daoClass = $entityToClassMap[$apiRequest['entity']];
391
392 /* @var $dao CRM_Core_DAO */
393 $dao = new $daoClass();
394 $dao->id = $apiRequest['params']['id'];
395 if ($dao->find(TRUE)) {
396 return civicrm_api3_create_success($dao->getReferenceCounts());
397 }
398 else {
399 return civicrm_api3_create_success(array());
400 }
401 }
402
403 /**
404 * API wrapper for replace function.
405 *
406 * @param array $apiRequest
407 * Api request as an array. Keys are.
408 *
409 * @return int
410 * count of results
411 */
412 function civicrm_api3_generic_replace($apiRequest) {
413 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
414 }
415
416 /**
417 * API wrapper for getoptions function.
418 *
419 * @param array $apiRequest
420 * Api request as an array.
421 *
422 * @return array
423 * Array of results
424 */
425 function civicrm_api3_generic_getoptions($apiRequest) {
426 // Resolve aliases.
427 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
428 if (!$fieldName) {
429 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
430 }
431 // Validate 'context' from params
432 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
433 CRM_Core_DAO::buildOptionsContext($context);
434 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
435
436 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
437 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
438 if ($options === FALSE) {
439 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
440 }
441 // Support 'sequential' output as a non-associative array
442 if (!empty($apiRequest['params']['sequential'])) {
443 $options = CRM_Utils_Array::makeNonAssociative($options);
444 }
445 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
446 }
447
448 /**
449 * Provide metadata for this generic action
450 *
451 * @param $params
452 * @param $apiRequest
453 */
454 function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
455 $params += array(
456 'field' => array(
457 'title' => 'Field name',
458 'api.required' => 1,
459 'type' => CRM_Utils_Type::T_STRING,
460 ),
461 'context' => array(
462 'title' => 'Context',
463 'type' => CRM_Utils_Type::T_STRING,
464 'options' => CRM_Core_DAO::buildOptionsContext(),
465 ),
466 );
467
468 // Add available fields if requested
469 if (array_intersect(array('all', 'field'), $apiRequest['params']['options']['get_options'])) {
470 $fields = civicrm_api3_generic_getfields(array('entity' => $apiRequest['entity'], array('params' => array('action' => 'create'))));
471 $params['field']['options'] = array();
472 foreach ($fields['values'] as $name => $field) {
473 if (isset($field['pseudoconstant']) || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_BOOLEAN) {
474 $params['field']['options'][$name] = CRM_Utils_Array::value('title', $field, $name);
475 }
476 }
477 }
478
479 $entityName = _civicrm_api_get_entity_name_from_camel($apiRequest['entity']);
480 $getOptionsSpecFunction = '_civicrm_api3_' . $entityName . '_getoptions_spec';
481
482 if (function_exists($getOptionsSpecFunction)) {
483 $getOptionsSpecFunction($params);
484 }
485 }
486
487 /**
488 * Get metadata.
489 *
490 * Function fills the 'options' array on the metadata returned by getfields if
491 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
492 * (this is passed in as the $fieldsToResolve array)
493 * 2) the field is a pseudoconstant and is NOT an FK
494 * - the reason for this is that checking / transformation is done on pseudoconstants but
495 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
496 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
497 *
498 * This function is only split out for the purpose of code clarity / comment block documentation
499 *
500 * @param array $metadata
501 * The array of metadata that will form the result of the getfields function.
502 * @param array $apiRequest
503 * @param string $fieldname
504 * Field currently being processed.
505 * @param array $fieldSpec
506 * Metadata for that field.
507 */
508 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec) {
509 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
510 return;
511 }
512
513 $fieldsToResolve = $apiRequest['params']['options']['get_options'];
514
515 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
516 return;
517 }
518
519 // Allow caller to specify context
520 $context = CRM_Utils_Array::value('get_options_context', $apiRequest['params']['options']);
521 // Default to api action if it is a supported context.
522 if (!$context) {
523 $action = CRM_Utils_Array::value('action', $apiRequest['params']);
524 $contexts = CRM_Core_DAO::buildOptionsContext();
525 if (isset($contexts[$action])) {
526 $context = $action;
527 }
528 }
529
530 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname, 'context' => $context));
531 if (is_array(CRM_Utils_Array::value('values', $options))) {
532 $metadata[$fieldname]['options'] = $options['values'];
533 }
534 }