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