3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * @package CiviCRM_APIv3
33 * Get information about fields for a given api request.
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
43 * @param array $apiRequest
44 * Api request as an array. Keys are.
48 * - function: callback (mixed)
49 * - params: array, varies
52 * Determines whether to key by unique field names (only affects get-type) actions
57 function civicrm_api3_generic_getfields($apiRequest, $unique = TRUE) {
58 static $results = array();
59 if ((CRM_Utils_Array
::value('cache_clear', $apiRequest['params']))) {
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']);
66 if (!empty($apiRequest['params']['option_group_id'])) {
67 $optionGroupName = civicrm_api('option_group', 'getvalue', array(
69 'id' => $apiRequest['params']['option_group_id'],
72 if (is_string($optionGroupName)) {
73 CRM_Utils_PseudoConstant
::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
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());
85 if (!$action ||
$action == 'getvalue' ||
$action == 'getcount') {
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];
93 // defaults based on data model and API policy
96 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
97 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
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');
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
122 $metadata['id']['api.aliases'] = array($lowercase_entity . '_id');
129 'title' => $entity . ' ID',
131 'api.aliases' => array($lowercase_entity . '_id'),
132 'type' => CRM_Utils_Type
::T_INT
,
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.
141 'title' => 'Field name',
143 'type' => CRM_Utils_Type
::T_STRING
,
146 'title' => $entity . ' ID',
148 'type' => CRM_Utils_Type
::T_INT
,
152 'description' => "Field value to set",
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']);
163 // oddballs are on their own
167 // Normalize this for the sake of spec funcions
168 $apiRequest['params']['options']['get_options'] = $optionsToResolve;
170 // find any supplemental information
171 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
173 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container
::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
174 if (isset($hypApiRequest['function'])) {
175 $helper = '_' . $hypApiRequest['function'] . '_spec';
178 // not implemented MagicFunctionProvider
182 catch (\Civi\API\Exception\NotImplementedException
$e) {
185 if (function_exists($helper)) {
187 $helper($metadata, $apiRequest);
190 foreach ($metadata as $fieldname => $fieldSpec) {
191 // Ensure 'name' is set
192 if (!isset($fieldSpec['name'])) {
193 $metadata[$fieldname]['name'] = $fieldname;
195 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $optionsToResolve);
197 // Convert options to "sequential" format
198 if ($sequential && !empty($metadata[$fieldname]['options'])) {
199 $metadata[$fieldname]['options'] = CRM_Utils_Array
::makeNonAssociative($metadata[$fieldname]['options']);
203 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
204 return $results[$entity][$action][$sequential];
208 * Get metadata for a field
210 * @param array $apiRequest
215 function civicrm_api3_generic_getfield($apiRequest) {
216 $params = $apiRequest['params'];
217 $sequential = !empty($params['sequential']);
218 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $params['name'], $params['action']);
220 return civicrm_api3_create_error("The field '{$params['name']}' doesn't exist.");
222 // Turn off sequential to make the field easier to find
223 $apiRequest['params']['sequential'] = 0;
224 if (isset($params['get_options'])) {
225 $apiRequest['params']['options']['get_options_context'] = $params['get_options'];
226 $apiRequest['params']['options']['get_options'] = $fieldName;
228 $result = civicrm_api3_generic_getfields($apiRequest, FALSE);
229 $result = $result['values'][$fieldName];
230 // Fix sequential options since we forced it off
231 if ($sequential && !empty($result['options'])) {
232 $result['options'] = CRM_Utils_Array
::makeNonAssociative($result['options']);
234 return civicrm_api3_create_success($result, $apiRequest['params'], $apiRequest['entity'], 'getfield');
238 function _civicrm_api3_generic_getfield_spec(&$params, $apiRequest) {
241 'title' => 'Field name',
242 'description' => 'Name or alias of field to lookup',
244 'type' => CRM_Utils_Type
::T_STRING
,
247 'title' => 'API Action',
249 'type' => CRM_Utils_Type
::T_STRING
,
250 'api.aliases' => array('api_action'),
252 'get_options' => array(
253 'title' => 'Get Options',
254 'description' => 'Context for which to get field options, or null to skip fetching options.',
255 'type' => CRM_Utils_Type
::T_STRING
,
256 'options' => CRM_Core_DAO
::buildOptionsContext(),
257 'api.aliases' => array('context'),
260 // Add available options to these params if requested
261 if (array_intersect(array('all', 'action'), $apiRequest['params']['options']['get_options'])) {
262 $actions = civicrm_api3($apiRequest['entity'], 'getactions');
263 $actions = array_combine($actions['values'], $actions['values']);
264 // Let's not go meta-crazy
265 CRM_Utils_Array
::remove($actions, 'getactions', 'getoptions', 'getfields', 'getfield', 'getcount', 'getrefcount', 'getsingle', 'getlist', 'getvalue', 'setvalue', 'update');
266 $params['action']['options'] = $actions;
271 * API return function to reformat results as count.
273 * @param array $apiRequest
274 * Api request as an array. Keys are.
276 * @throws API_Exception
280 function civicrm_api3_generic_getcount($apiRequest) {
281 $apiRequest['params']['options']['is_count'] = TRUE;
282 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
283 if (is_numeric(CRM_Utils_Array
::value('values', $result))) {
284 return (int) $result['values'];
286 if (!isset($result['count'])) {
287 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
289 return $result['count'];
293 * API return function to reformat results as single result.
295 * @param array $apiRequest
296 * Api request as an array. Keys are.
301 function civicrm_api3_generic_getsingle($apiRequest) {
302 // So the first entity is always result['values'][0].
303 $apiRequest['params']['sequential'] = 1;
304 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
305 if ($result['is_error'] !== 0) {
308 if ($result['count'] === 1) {
309 return $result['values'][0];
311 if ($result['count'] !== 1) {
312 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
314 return civicrm_api3_create_error("Undefined behavior");
318 * API return function to reformat results as single value.
320 * @param array $apiRequest
321 * Api request as an array. Keys are.
326 function civicrm_api3_generic_getvalue($apiRequest) {
327 $apiRequest['params']['sequential'] = 1;
328 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
329 if ($result['is_error'] !== 0) {
332 if ($result['count'] !== 1) {
333 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
337 // we only take "return=" as valid options
338 if (!empty($apiRequest['params']['return'])) {
339 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
340 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
343 return $result['values'][0][$apiRequest['params']['return']];
346 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
350 * Get count of contact references.
352 * @param array $params
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(array());
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.
410 function civicrm_api3_generic_getoptions($apiRequest) {
412 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
414 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
416 // Validate 'context' from params
417 $context = CRM_Utils_Array
::value('context', $apiRequest['params']);
418 CRM_Core_DAO
::buildOptionsContext($context);
419 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
421 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
422 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
423 if ($options === FALSE) {
424 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
426 // Support 'sequential' output as a non-associative array
427 if (!empty($apiRequest['params']['sequential'])) {
428 $options = CRM_Utils_Array
::makeNonAssociative($options);
430 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
434 * Provide metadata for this generic action
439 function _civicrm_api3_generic_getoptions_spec(&$params, $apiRequest) {
442 'title' => 'Field name',
444 'type' => CRM_Utils_Type
::T_STRING
,
447 'title' => 'Context',
448 'type' => CRM_Utils_Type
::T_STRING
,
452 // Add available options to these params if requested
453 if (array_intersect(array('all', 'context'), $apiRequest['params']['options']['get_options'])) {
454 $params['context']['options'] = array_combine(array_keys(CRM_Core_DAO
::buildOptionsContext()), array_keys(CRM_Core_DAO
::buildOptionsContext()));
456 if (array_intersect(array('all', 'field'), $apiRequest['params']['options']['get_options'])) {
457 $fields = civicrm_api3_generic_getfields(array('entity' => $apiRequest['entity'], array('params' => array('action' => 'create'))));
458 $params['field']['options'] = array();
459 foreach ($fields['values'] as $name => $field) {
460 if (isset($field['pseudoconstant']) || CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_BOOLEAN
) {
461 $params['field']['options'][$name] = CRM_Utils_Array
::value('title', $field, $name);
470 * Function fills the 'options' array on the metadata returned by getfields if
471 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
472 * (this is passed in as the $fieldsToResolve array)
473 * 2) the field is a pseudoconstant and is NOT an FK
474 * - the reason for this is that checking / transformation is done on pseudoconstants but
475 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
476 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
478 * This function is only split out for the purpose of code clarity / comment block documentation
480 * @param array $metadata
481 * The array of metadata that will form the result of the getfields function.
482 * @param array $apiRequest
483 * @param string $fieldname
484 * Field currently being processed.
485 * @param array $fieldSpec
486 * Metadata for that field.
487 * @param array $fieldsToResolve
488 * Any field resolutions specifically requested.
490 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
491 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
495 if (!empty($metadata[$fieldname]['options']) ||
(!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
499 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname));
500 if (is_array(CRM_Utils_Array
::value('values', $options))) {
501 $metadata[$fieldname]['options'] = $options['values'];