4 * Get information about fields for a given api request.
6 * Getfields information is used for documentation, validation, default setting
7 * We first query the scheme using the $dao->fields function & then augment
8 * that information by calling the _spec functions that apply to the relevant function
9 * Note that we use 'unique' field names as described in the xml/schema files
10 * for get requests & just field name for create. This is because some get functions
11 * access multiple objects e.g. contact api accesses is_deleted from the activity
12 * table & from the contact table
14 * @param array $apiRequest
15 * Api request as an array. Keys are.
19 * - function: callback (mixed)
20 * - params: array, varies
25 function civicrm_api3_generic_getfields($apiRequest) {
26 static $results = array();
27 if ((CRM_Utils_Array
::value('cache_clear', $apiRequest['params']))) {
29 // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
30 CRM_Core_PseudoConstant
::flush();
31 if (!empty($apiRequest['params']['fieldname'])) {
32 CRM_Utils_PseudoConstant
::flushConstant($apiRequest['params']['fieldname']);
34 if (!empty($apiRequest['params']['option_group_id'])) {
35 $optionGroupName = civicrm_api('option_group', 'getvalue', array(
37 'id' => $apiRequest['params']['option_group_id'],
40 if (is_string($optionGroupName)) {
41 CRM_Utils_PseudoConstant
::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
45 $entity = _civicrm_api_get_camel_name($apiRequest['entity']);
46 $lcase_entity = _civicrm_api_get_entity_name_from_camel($entity);
47 $subentity = CRM_Utils_Array
::value('contact_type', $apiRequest['params']);
48 $action = strtolower(CRM_Utils_Array
::value('action', $apiRequest['params']));
49 $sequential = empty($apiRequest['params']) ?
0 : 1;
50 $apiOptions = CRM_Utils_Array
::value('options', $apiRequest['params'], array());
51 if (!$action ||
$action == 'getvalue' ||
$action == 'getcount') {
54 // determines whether to use unique field names - seem comment block above
56 if (empty($apiOptions) && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
57 && isset($action, $results[$entity . $subentity][$sequential])) {
58 return $results[$entity . $subentity][$action][$sequential];
60 // defaults based on data model and API policy
63 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
64 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
73 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
74 if (empty($metadata['id'])) {
75 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
76 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
77 $metadata['id'] = $metadata[$lcase_entity . '_id'];
78 unset($metadata[$lcase_entity . '_id']);
79 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
83 // really the preference would be to set the unique name in the xml
84 // question is which is a less risky fix this close to a release - setting in xml for the known failure
85 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
86 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
88 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
95 'title' => $entity . ' ID',
98 'api.aliases' => array($lcase_entity . '_id'),
99 'type' => CRM_Utils_Type
::T_INT
,
107 'title' => 'Field name',
112 'title' => 'Context',
118 // oddballs are on their own
122 // find any supplemental information
123 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
125 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container
::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
126 if (isset($hypApiRequest['function'])) {
127 $helper = '_' . $hypApiRequest['function'] . '_spec';
130 // not implemented MagicFunctionProvider
134 catch (\Civi\API\Exception\NotImplementedException
$e) {
137 if (function_exists($helper)) {
139 $helper($metadata, $apiRequest);
142 $fieldsToResolve = (array) CRM_Utils_Array
::value('get_options', $apiOptions, array());
144 foreach ($metadata as $fieldname => $fieldSpec) {
145 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve);
148 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
149 return $results[$entity][$action][$sequential];
153 * API return function to reformat results as count.
155 * @param array $apiRequest
156 * Api request as an array. Keys are.
158 * @throws API_Exception
162 function civicrm_api3_generic_getcount($apiRequest) {
163 $apiRequest['params']['options']['is_count'] = TRUE;
164 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
165 if (is_numeric(CRM_Utils_Array
::value('values', $result))) {
166 return (int) $result['values'];
168 if (!isset($result['count'])) {
169 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
171 return $result['count'];
175 * API return function to reformat results as single result.
177 * @param array $apiRequest
178 * Api request as an array. Keys are.
183 function civicrm_api3_generic_getsingle($apiRequest) {
184 // So the first entity is always result['values'][0].
185 $apiRequest['params']['sequential'] = 1;
186 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
187 if ($result['is_error'] !== 0) {
190 if ($result['count'] === 1) {
191 return $result['values'][0];
193 if ($result['count'] !== 1) {
194 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
196 return civicrm_api3_create_error("Undefined behavior");
200 * API return function to reformat results as single value.
202 * @param array $apiRequest
203 * Api request as an array. Keys are.
208 function civicrm_api3_generic_getvalue($apiRequest) {
209 $apiRequest['params']['sequential'] = 1;
210 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
211 if ($result['is_error'] !== 0) {
214 if ($result['count'] !== 1) {
215 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
219 // we only take "return=" as valid options
220 if (!empty($apiRequest['params']['return'])) {
221 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
222 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
225 return $result['values'][0][$apiRequest['params']['return']];
228 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
232 * Get count of contact references.
234 * @param array $params
236 function _civicrm_api3_generic_getrefcount_spec(&$params) {
237 $params['id']['api.required'] = 1;
238 $params['id']['title'] = 'Entity ID';
242 * API to determine if a record is in-use.
244 * @param array $apiRequest
245 * Api request as an array.
247 * @throws API_Exception
249 * API result (int 0 or 1)
251 function civicrm_api3_generic_getrefcount($apiRequest) {
252 $entityToClassMap = CRM_Core_DAO_AllCoreTables
::daoToClass();
253 if (!isset($entityToClassMap[$apiRequest['entity']])) {
254 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
256 $daoClass = $entityToClassMap[$apiRequest['entity']];
258 /* @var $dao CRM_Core_DAO */
259 $dao = new $daoClass();
260 $dao->id
= $apiRequest['params']['id'];
261 if ($dao->find(TRUE)) {
262 return civicrm_api3_create_success($dao->getReferenceCounts());
265 return civicrm_api3_create_success(array());
270 * API wrapper for replace function.
272 * @param array $apiRequest
273 * Api request as an array. Keys are.
278 function civicrm_api3_generic_replace($apiRequest) {
279 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
283 * API wrapper for getoptions function.
285 * @param array $apiRequest
286 * Api request as an array.
291 function civicrm_api3_generic_getoptions($apiRequest) {
293 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
295 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
297 // Validate 'context' from params
298 $context = CRM_Utils_Array
::value('context', $apiRequest['params']);
299 CRM_Core_DAO
::buildOptionsContext($context);
300 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
302 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
303 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
304 if ($options === FALSE) {
305 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
307 // Support 'sequential' output as a non-associative array
308 if (!empty($apiRequest['params']['sequential'])) {
309 $options = CRM_Utils_Array
::makeNonAssociative($options);
311 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
317 * Function fills the 'options' array on the metadata returned by getfields if
318 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
319 * (this is passed in as the $fieldsToResolve array)
320 * 2) the field is a pseudoconstant and is NOT an FK
321 * - the reason for this is that checking / transformation is done on pseudoconstants but
322 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
323 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
325 * This function is only split out for the purpose of code clarity / comment block documentation
327 * @param array $metadata
328 * The array of metadata that will form the result of the getfields function.
329 * @param array $apiRequest
330 * @param string $fieldname
331 * Field currently being processed.
332 * @param array $fieldSpec
333 * Metadata for that field.
334 * @param array $fieldsToResolve
335 * Anny field resolutions specifically requested.
337 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
338 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
342 if (!empty($metadata[$fieldname]['options']) ||
(!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
346 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname, 'sequential' => !empty($apiRequest['params']['sequential'])));
347 if (is_array(CRM_Utils_Array
::value('values', $options))) {
348 $metadata[$fieldname]['options'] = $options['values'];