00ce07b107b65431c2d9c96ccb0e65d66d6904e7
[civicrm-core.git] / api / v3 / Generic.php
1 <?php
2
3 /**
4 * Get information about fields for a given api request. Getfields information
5 * is used for documentation, validation, default setting
6 * We first query the scheme using the $dao->fields function & then augment
7 * that information by calling the _spec functions that apply to the relevant function
8 * Note that we use 'unique' field names as described in the xml/schema files
9 * for get requests & just field name for create. This is because some get functions
10 * access multiple objects e.g. contact api accesses is_deleted from the activity
11 * table & from the contact table
12 *
13 * @param array $apiRequest
14 * Api request as an array. Keys are.
15 * - entity: string
16 * - action: string
17 * - version: string
18 * - function: callback (mixed)
19 * - params: array, varies
20 * @return array API success object
21 */
22 function civicrm_api3_generic_getfields($apiRequest) {
23 static $results = array();
24 if ((CRM_Utils_Array::value('cache_clear', $apiRequest['params']))) {
25 $results = array();
26 // we will also clear pseudoconstants here - should potentially be moved to relevant BAO classes
27 CRM_Core_PseudoConstant::flush();
28 if (!empty($apiRequest['params']['fieldname'])) {
29 CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
30 }
31 if (!empty($apiRequest['params']['option_group_id'])) {
32 $optionGroupName = civicrm_api('option_group', 'getvalue', array('version' => 3, 'id' => $apiRequest['params']['option_group_id'], 'return' => 'name'));
33 if (is_string($optionGroupName)) {
34 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
35 }
36 }
37 }
38 $entity = _civicrm_api_get_camel_name($apiRequest['entity']);
39 $lcase_entity = _civicrm_api_get_entity_name_from_camel($entity);
40 $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
41 $action = strtolower(CRM_Utils_Array::value('action', $apiRequest['params']));
42 $sequential = empty($apiRequest['params']) ? 0 : 1;
43 $apiOptions = CRM_Utils_Array::value('options', $apiRequest['params'], array());
44 if (!$action || $action == 'getvalue' || $action == 'getcount') {
45 $action = 'get';
46 }
47 // determines whether to use unique field names - seem comment block above
48 $unique = TRUE;
49 if (empty($apiOptions) && isset($results[$entity . $subentity]) && isset($action, $results[$entity . $subentity])
50 && isset($action, $results[$entity . $subentity][$sequential])) {
51 return $results[$entity . $subentity][$action][$sequential];
52 }
53 // defaults based on data model and API policy
54 switch ($action) {
55 case 'getfields':
56 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
57 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
58 case 'create':
59 case 'update':
60 case 'replace':
61 $unique = FALSE;
62 case 'get':
63 case 'getsingle':
64 case 'getcount':
65 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
66 if (empty($metadata['id'])) {
67 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
68 if (!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
69 $metadata['id'] = $metadata[$lcase_entity . '_id'];
70 unset($metadata[$lcase_entity . '_id']);
71 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
72 }
73 }
74 else {
75 // really the preference would be to set the unique name in the xml
76 // question is which is a less risky fix this close to a release - setting in xml for the known failure
77 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
78 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
79 // inconsistency
80 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
81 }
82 break;
83
84 case 'delete':
85 $metadata = array(
86 'id' => array(
87 'title' => $entity . ' ID',
88 'name' => 'id',
89 'api.required' => 1,
90 'api.aliases' => array($lcase_entity . '_id'),
91 'type' => CRM_Utils_Type::T_INT,
92 ));
93 break;
94
95 case 'getoptions':
96 $metadata = array(
97 'field' => array(
98 'name' => 'field',
99 'title' => 'Field name',
100 'api.required' => 1,
101 ),
102 'context' => array(
103 'name' => 'context',
104 'title' => 'Context',
105 ),
106 );
107 break;
108
109 default:
110 // oddballs are on their own
111 $metadata = array();
112 }
113
114 // find any supplemental information
115 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
116 try {
117 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
118 if (isset($hypApiRequest['function'])) {
119 $helper = '_' . $hypApiRequest['function'] . '_spec';
120 }
121 else {
122 // not implemented MagicFunctionProvider
123 $helper = NULL;
124 }
125 }
126 catch (\Civi\API\Exception\NotImplementedException $e) {
127 $helper = NULL;
128 }
129 if (function_exists($helper)) {
130 // alter
131 $helper($metadata, $apiRequest);
132 }
133
134 $fieldsToResolve = (array) CRM_Utils_Array::value('get_options', $apiOptions, array());
135
136 foreach ($metadata as $fieldname => $fieldSpec) {
137 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve);
138 }
139
140 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
141 return $results[$entity][$action][$sequential];
142 }
143
144 /**
145 * API return function to reformat results as count
146 *
147 * @param array $apiRequest
148 * Api request as an array. Keys are.
149 *
150 * @throws API_Exception
151 * @return integer count of results
152 */
153 function civicrm_api3_generic_getcount($apiRequest) {
154 $apiRequest['params']['options']['is_count'] = TRUE;
155 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
156 if (is_numeric(CRM_Utils_Array::value('values', $result))) {
157 return (int) $result['values'];
158 }
159 if (!isset($result['count'])) {
160 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
161 }
162 return $result['count'];
163 }
164
165 /**
166 * API return function to reformat results as single result
167 *
168 * @param array $apiRequest
169 * Api request as an array. Keys are.
170 *
171 * @return integer count of results
172 */
173 function civicrm_api3_generic_getsingle($apiRequest) {
174 // so the first entity is always result['values'][0]
175 $apiRequest['params']['sequential'] = 1;
176 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
177 if ($result['is_error'] !== 0) {
178 return $result;
179 }
180 if ($result['count'] === 1) {
181 return $result['values'][0];
182 }
183 if ($result['count'] !== 1) {
184 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
185 }
186 return civicrm_api3_create_error("Undefined behavior");
187 }
188
189 /**
190 * API return function to reformat results as single value
191 *
192 * @param array $apiRequest
193 * Api request as an array. Keys are.
194 *
195 * @return integer count of results
196 */
197 function civicrm_api3_generic_getvalue($apiRequest) {
198 $apiRequest['params']['sequential'] = 1;
199 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
200 if ($result['is_error'] !== 0) {
201 return $result;
202 }
203 if ($result['count'] !== 1) {
204 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
205 return $result;
206 }
207
208 // we only take "return=" as valid options
209 if (!empty($apiRequest['params']['return'])) {
210 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
211 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
212 }
213
214 return $result['values'][0][$apiRequest['params']['return']];
215 }
216
217 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
218 }
219
220 /**
221 * @param array $params
222 */
223 function _civicrm_api3_generic_getrefcount_spec(&$params) {
224 $params['id']['api.required'] = 1;
225 $params['id']['title'] = 'Entity ID';
226 }
227
228 /**
229 * API to determine if a record is in-use
230 *
231 * @param array $apiRequest
232 * Api request as an array.
233 *
234 * @throws API_Exception
235 * @return array API result (int 0 or 1)
236 */
237 function civicrm_api3_generic_getrefcount($apiRequest) {
238 $entityToClassMap = CRM_Core_DAO_AllCoreTables::daoToClass();
239 if (!isset($entityToClassMap[$apiRequest['entity']])) {
240 throw new API_Exception("The entity '{$apiRequest['entity']}' is unknown or unsupported by 'getrefcount'. Consider implementing this API.", 'getrefcount_unsupported');
241 }
242 $daoClass = $entityToClassMap[$apiRequest['entity']];
243
244 /* @var $dao CRM_Core_DAO */
245 $dao = new $daoClass();
246 $dao->id = $apiRequest['params']['id'];
247 if ($dao->find(TRUE)) {
248 return civicrm_api3_create_success($dao->getReferenceCounts());
249 }
250 else {
251 return civicrm_api3_create_success(array());
252 }
253 }
254
255 /**
256 * API wrapper for replace function
257 *
258 * @param array $apiRequest
259 * Api request as an array. Keys are.
260 *
261 * @return integer count of results
262 */
263 function civicrm_api3_generic_replace($apiRequest) {
264 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
265 }
266
267 /**
268 * API wrapper for getoptions function
269 *
270 * @param array $apiRequest
271 * Api request as an array.
272 *
273 * @return array of results
274 */
275 function civicrm_api3_generic_getoptions($apiRequest) {
276 // Resolve aliases
277 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
278 if (!$fieldName) {
279 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
280 }
281 // Validate 'context' from params
282 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
283 CRM_Core_DAO::buildOptionsContext($context);
284 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
285
286 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
287 $options = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
288 if ($options === FALSE) {
289 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
290 }
291 // Support 'sequential' output as a non-associative array
292 if (!empty($apiRequest['params']['sequential'])) {
293 $options = CRM_Utils_Array::makeNonAssociative($options);
294 }
295 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
296 }
297
298 /**
299 * Function fills the 'options' array on the metadata returned by getfields if
300 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
301 * (this is passed in as the $fieldsToResolve array)
302 * 2) the field is a pseudoconstant and is NOT an FK
303 * - the reason for this is that checking / transformation is done on pseudoconstants but
304 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
305 * @todo - if may be we should define a 'resolve' key on the pseudoconstant for when these rules are not fine enough
306 *
307 * This function is only split out for the purpose of code clarity / comment block documentation
308 *
309 * @param array $metadata
310 * The array of metadata that will form the result of the getfields function.
311 * @param $apiRequest
312 * @param string $fieldname
313 * Field currently being processed.
314 * @param array $fieldSpec
315 * Metadata for that field.
316 * @param array $fieldsToResolve
317 * Anny field resolutions specifically requested.
318 */
319 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
320 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
321 return;
322 }
323
324 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
325 return;
326 }
327
328 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname, 'sequential' => !empty($apiRequest['params']['sequential'])));
329 if (is_array(CRM_Utils_Array::value('values', $options))) {
330 $metadata[$fieldname]['options'] = $options['values'];
331 }
332 }