3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * @package CiviCRM_APIv3
17 * Get information about fields for a given api request.
19 * Getfields information is used for documentation, validation, default setting
20 * We first query the scheme using the $dao->fields function & then augment
21 * that information by calling the _spec functions that apply to the relevant function
22 * Note that we use 'unique' field names as described in the xml/schema files
23 * for get requests & just field name for create. This is because some get functions
24 * access multiple objects e.g. contact api accesses is_deleted from the activity
25 * table & from the contact table
27 * @param array $apiRequest
28 * Api request as an array. Keys are.
32 * - function: callback (mixed)
33 * - params: array, varies
36 * Determines whether to key by unique field names (only affects get-type) actions
41 function civicrm_api3_generic_getfields($apiRequest, $unique = TRUE) {
43 if ((CRM_Utils_Array
::value('cache_clear', $apiRequest['params']))) {
45 // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
46 CRM_Core_PseudoConstant
::flush();
47 if (!empty($apiRequest['params']['fieldname'])) {
48 CRM_Utils_PseudoConstant
::flushConstant($apiRequest['params']['fieldname']);
50 if (!empty($apiRequest['params']['option_group_id'])) {
51 $optionGroupName = civicrm_api('option_group', 'getvalue', [
53 'id' => $apiRequest['params']['option_group_id'],
56 if (is_string($optionGroupName)) {
57 CRM_Utils_PseudoConstant
::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
61 $entity = $apiRequest['entity'];
62 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
63 $subentity = $apiRequest['params']['contact_type'] ??
NULL;
64 $action = $apiRequest['params']['action'] ??
NULL;
65 $sequential = empty($apiRequest['params']['sequential']) ?
0 : 1;
66 $apiRequest['params']['options'] = CRM_Utils_Array
::value('options', $apiRequest['params'], []);
67 $optionsToResolve = (array) CRM_Utils_Array
::value('get_options', $apiRequest['params']['options'], []);
69 if (!$action ||
$action == 'getvalue' ||
$action == 'getcount') {
72 // If no options, return results from cache
73 if (!$apiRequest['params']['options'] && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
74 && isset($action, $results[$entity . $subentity][$sequential])) {
75 return $results[$entity . $subentity][$action][$sequential];
77 // defaults based on data model and API policy
80 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
81 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
91 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
92 if (empty($metadata['id'])) {
93 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
94 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
95 $metadata['id'] = $metadata[$lowercase_entity . '_id'];
96 unset($metadata[$lowercase_entity . '_id']);
97 $metadata['id']['api.aliases'] = [$lowercase_entity . '_id'];
101 // really the preference would be to set the unique name in the xml
102 // question is which is a less risky fix this close to a release - setting in xml for the known failure
103 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
104 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
106 $metadata['id']['api.aliases'] = [$lowercase_entity . '_id'];
113 'title' => $entity . ' ID',
115 'api.aliases' => [$lowercase_entity . '_id'],
116 'type' => CRM_Utils_Type
::T_INT
,
121 // Note: adding setvalue case here instead of in a generic spec function because
122 // some APIs override the generic setvalue fn which causes the generic spec to be overlooked.
126 'title' => 'Field name',
128 'type' => CRM_Utils_Type
::T_STRING
,
131 'title' => $entity . ' ID',
133 'type' => CRM_Utils_Type
::T_INT
,
137 'description' => "Field value to set",
141 if (array_intersect(['all', 'field'], $optionsToResolve)) {
142 $options = civicrm_api3_generic_getfields(['entity' => $entity, ['params' => ['action' => 'create']]]);
143 $metadata['field']['options'] = CRM_Utils_Array
::collect('title', $options['values']);
148 // oddballs are on their own
152 // Hack for product api to pass tests.
153 if (!is_string($apiRequest['params']['options'])) {
154 // Normalize this for the sake of spec funcions
155 $apiRequest['params']['options']['get_options'] = $optionsToResolve;
158 // find any supplemental information
159 $hypApiRequest = ['entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']];
160 if ($action == 'getsingle') {
161 $hypApiRequest['action'] = 'get';
164 list ($apiProvider, $hypApiRequest) = \Civi
::service('civi_api_kernel')->resolve($hypApiRequest);
165 if (isset($hypApiRequest['function'])) {
166 $helper = '_' . $hypApiRequest['function'] . '_spec';
169 // not implemented MagicFunctionProvider
173 catch (\Civi\API\Exception\NotImplementedException
$e) {
176 if (function_exists($helper)) {
178 $helper($metadata, $apiRequest);
181 foreach ($metadata as $fieldname => $fieldSpec) {
182 // Ensure 'name' is set
183 if (!isset($fieldSpec['name'])) {
184 $metadata[$fieldname]['name'] = $fieldname;
186 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec);
188 // Convert options to "sequential" format
189 if ($sequential && !empty($metadata[$fieldname]['options'])) {
190 $metadata[$fieldname]['options'] = CRM_Utils_Array
::makeNonAssociative($metadata[$fieldname]['options']);
194 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
195 return $results[$entity][$action][$sequential];
199 * Get metadata for a field
201 * @param array $apiRequest
206 function civicrm_api3_generic_getfield($apiRequest) {
207 $params = $apiRequest['params'];
208 $sequential = !empty($params['sequential']);
209 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $params['name'], $params['action']);
211 return civicrm_api3_create_error("The field '{$params['name']}' doesn't exist.");
213 // Turn off sequential to make the field easier to find
214 $apiRequest['params']['sequential'] = 0;
215 if (isset($params['get_options'])) {
216 $apiRequest['params']['options']['get_options_context'] = $params['get_options'];
217 $apiRequest['params']['options']['get_options'] = $fieldName;
219 $result = civicrm_api3_generic_getfields($apiRequest, FALSE);
220 $result = $result['values'][$fieldName];
221 // Fix sequential options since we forced it off
222 if ($sequential && !empty($result['options'])) {
223 $result['options'] = CRM_Utils_Array
::makeNonAssociative($result['options']);
225 return civicrm_api3_create_success($result, $apiRequest['params'], $apiRequest['entity'], 'getfield');
229 * Get metadata for getfield action.
231 * @param array $params
232 * @param array $apiRequest
234 * @throws \CiviCRM_API3_Exception
237 function _civicrm_api3_generic_getfield_spec(&$params, $apiRequest) {
240 'title' => 'Field name',
241 'description' => 'Name or alias of field to lookup',
243 'type' => CRM_Utils_Type
::T_STRING
,
246 'title' => 'API Action',
248 'type' => CRM_Utils_Type
::T_STRING
,
249 'api.aliases' => ['api_action'],
252 'title' => 'Get Options',
253 'description' => 'Context for which to get field options, or null to skip fetching options.',
254 'type' => CRM_Utils_Type
::T_STRING
,
255 'options' => CRM_Core_DAO
::buildOptionsContext(),
256 'api.aliases' => ['context'],
259 // Add available options to these params if requested
260 if (array_intersect(['all', 'action'], $apiRequest['params']['options']['get_options'])) {
261 $actions = civicrm_api3($apiRequest['entity'], 'getactions');
262 $actions = array_combine($actions['values'], $actions['values']);
263 // Let's not go meta-crazy
264 CRM_Utils_Array
::remove($actions, 'getactions', 'getoptions', 'getfields', 'getfield', 'getcount', 'getrefcount', 'getsingle', 'getlist', 'getvalue', 'setvalue', 'update');
265 $params['action']['options'] = $actions;
270 * API return function to reformat results as count.
272 * @param array $apiRequest
273 * Api request as an array. Keys are.
275 * @throws API_Exception
279 function civicrm_api3_generic_getcount($apiRequest) {
280 $apiRequest['params']['options']['is_count'] = TRUE;
281 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
282 if (is_numeric(CRM_Utils_Array
::value('values', $result))) {
283 return (int) $result['values'];
285 if (!isset($result['count'])) {
286 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
288 return $result['count'];
292 * API return function to reformat results as single result.
294 * @param array $apiRequest
295 * Api request as an array. Keys are.
300 function civicrm_api3_generic_getsingle($apiRequest) {
301 // So the first entity is always result['values'][0].
302 $apiRequest['params']['sequential'] = 1;
303 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
304 if ($result['is_error'] !== 0) {
307 if ($result['count'] === 1) {
308 return $result['values'][0];
310 if ($result['count'] !== 1) {
311 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], ['count' => $result['count']]);
313 return civicrm_api3_create_error("Undefined behavior");
317 * API return function to reformat results as single value.
319 * @param array $apiRequest
320 * Api request as an array. Keys are.
325 function civicrm_api3_generic_getvalue($apiRequest) {
326 $apiRequest['params']['sequential'] = 1;
327 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
328 if ($result['is_error'] !== 0) {
331 if ($result['count'] !== 1) {
332 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], ['count' => $result['count']]);
336 // we only take "return=" as valid options
337 if (!empty($apiRequest['params']['return'])) {
338 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
339 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", ['invalid_field' => $apiRequest['params']['return']]);
342 return $result['values'][0][$apiRequest['params']['return']];
345 return civicrm_api3_create_error("missing param return=field you want to read the value of", ['error_type' => 'mandatory_missing', 'missing_param' => 'return']);
349 * Get count of contact references.
351 * @param array $params
352 * @param array $apiRequest
354 function _civicrm_api3_generic_getrefcount_spec(&$params, $apiRequest) {
355 $params['id']['api.required'] = 1;
356 $params['id']['title'] = $apiRequest['entity'] . ' ID';
357 $params['id']['type'] = CRM_Utils_Type
::T_INT
;
361 * API to determine if a record is in-use.
363 * @param array $apiRequest
364 * Api request as an array.
366 * @throws API_Exception
368 * API result (int 0 or 1)
370 function civicrm_api3_generic_getrefcount($apiRequest) {
371 $entityToClassMap = CRM_Core_DAO_AllCoreTables
::daoToClass();
372 if (!isset($entityToClassMap[$apiRequest['entity']])) {
373 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
375 $daoClass = $entityToClassMap[$apiRequest['entity']];
377 /* @var $dao CRM_Core_DAO */
378 $dao = new $daoClass();
379 $dao->id
= $apiRequest['params']['id'];
380 if ($dao->find(TRUE)) {
381 return civicrm_api3_create_success($dao->getReferenceCounts());
384 return civicrm_api3_create_success([]);
389 * API wrapper for replace function.
391 * @param array $apiRequest
392 * Api request as an array. Keys are.
397 function civicrm_api3_generic_replace($apiRequest) {
398 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
402 * API wrapper for getoptions function.
404 * @param array $apiRequest
405 * Api request as an array.
409 * @throws \CiviCRM_API3_Exception
411 function civicrm_api3_generic_getoptions($apiRequest) {
413 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
415 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
417 // Validate 'context' from params
418 $context = $apiRequest['params']['context'] ??
NULL;
419 CRM_Core_DAO
::buildOptionsContext($context);
420 unset($apiRequest['params']['context'], $apiRequest['params']['field'], $apiRequest['params']['condition']);
422 // Legacy support for campaign_id fields which used to have a pseudoconstant
423 if ($fieldName === 'campaign_id') {
425 'select' => ['id', 'name', 'title'],
426 'options' => ['limit' => 0],
428 if ($context === 'match' ||
$context === 'create') {
429 $campaignParams['is_active'] = 1;
431 $labelField = $context === 'validate' ?
'name' : 'title';
432 $keyField = $context === 'match' ?
'name' : 'id';
433 $options = array_column(civicrm_api3('Campaign', 'get', $campaignParams)['values'], $labelField, $keyField);
436 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
437 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
439 if ($options === FALSE) {
440 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
442 // Support 'sequential' output as a non-associative array
443 if (!empty($apiRequest['params']['sequential'])) {
444 $options = CRM_Utils_Array
::makeNonAssociative($options);
446 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
450 * Provide metadata for this generic action
455 function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
458 'title' => 'Field name',
460 'type' => CRM_Utils_Type
::T_STRING
,
463 'title' => 'Context',
464 'type' => CRM_Utils_Type
::T_STRING
,
465 'options' => CRM_Core_DAO
::buildOptionsContext(),
469 // Add available fields if requested
470 if (array_intersect(['all', 'field'], $apiRequest['params']['options']['get_options'])) {
471 $fields = civicrm_api3_generic_getfields(['entity' => $apiRequest['entity'], ['params' => ['action' => 'create']]]);
472 $params['field']['options'] = [];
473 foreach ($fields['values'] as $name => $field) {
474 if (isset($field['pseudoconstant']) || CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_BOOLEAN
) {
475 $params['field']['options'][$name] = CRM_Utils_Array
::value('title', $field, $name);
480 $entityName = _civicrm_api_get_entity_name_from_camel($apiRequest['entity']);
481 $getOptionsSpecFunction = '_civicrm_api3_' . $entityName . '_getoptions_spec';
483 if (function_exists($getOptionsSpecFunction)) {
484 $getOptionsSpecFunction($params);
491 * Function fills the 'options' array on the metadata returned by getfields if
492 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
493 * (this is passed in as the $fieldsToResolve array)
494 * 2) the field is a pseudoconstant and is NOT an FK
495 * - the reason for this is that checking / transformation is done on pseudoconstants but
496 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
497 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
499 * This function is only split out for the purpose of code clarity / comment block documentation
501 * @param array $metadata
502 * The array of metadata that will form the result of the getfields function.
503 * @param array $apiRequest
504 * @param string $fieldname
505 * Field currently being processed.
506 * @param array $fieldSpec
507 * Metadata for that field.
509 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec) {
510 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
514 $fieldsToResolve = $apiRequest['params']['options']['get_options'];
516 if (!empty($metadata[$fieldname]['options']) ||
(!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
520 // Allow caller to specify context
521 $context = $apiRequest['params']['options']['get_options_context'] ??
NULL;
522 // Default to api action if it is a supported context.
524 $action = $apiRequest['params']['action'] ??
NULL;
525 $contexts = CRM_Core_DAO
::buildOptionsContext();
526 if (isset($contexts[$action])) {
531 $options = civicrm_api($apiRequest['entity'], 'getoptions', ['version' => 3, 'field' => $fieldname, 'context' => $context]);
532 if (isset($options['values']) && is_array($options['values'])) {
533 $metadata[$fieldname]['options'] = $options['values'];