Merge pull request #5035 from TeNNoX/master
[civicrm-core.git] / api / v3 / Generic.php
1 <?php
2
3 /**
4 * Get information about fields for a given api request.
5 *
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
13 *
14 * @param array $apiRequest
15 * Api request as an array. Keys are.
16 * - entity: string
17 * - action: string
18 * - version: string
19 * - function: callback (mixed)
20 * - params: array, varies
21 *
22 * @return array
23 * API success object
24 */
25 function civicrm_api3_generic_getfields($apiRequest) {
26 static $results = array();
27 if ((CRM_Utils_Array::value('cache_clear', $apiRequest['params']))) {
28 $results = array();
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']);
33 }
34 if (!empty($apiRequest['params']['option_group_id'])) {
35 $optionGroupName = civicrm_api('option_group', 'getvalue', array(
36 'version' => 3,
37 'id' => $apiRequest['params']['option_group_id'],
38 'return' => 'name',
39 ));
40 if (is_string($optionGroupName)) {
41 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
42 }
43 }
44 }
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') {
52 $action = 'get';
53 }
54 // determines whether to use unique field names - seem comment block above
55 $unique = TRUE;
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];
59 }
60 // defaults based on data model and API policy
61 switch ($action) {
62 case 'getfields':
63 $values = _civicrm_api_get_fields($entity, FALSE, $apiRequest['params']);
64 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
65
66 case 'create':
67 case 'update':
68 case 'replace':
69 $unique = FALSE;
70 case 'get':
71 case 'getsingle':
72 case 'getcount':
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');
80 }
81 }
82 else {
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
87 // inconsistency
88 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
89 }
90 break;
91
92 case 'delete':
93 $metadata = array(
94 'id' => array(
95 'title' => $entity . ' ID',
96 'name' => 'id',
97 'api.required' => 1,
98 'api.aliases' => array($lcase_entity . '_id'),
99 'type' => CRM_Utils_Type::T_INT,
100 ));
101 break;
102
103 case 'getoptions':
104 $metadata = array(
105 'field' => array(
106 'name' => 'field',
107 'title' => 'Field name',
108 'api.required' => 1,
109 ),
110 'context' => array(
111 'name' => 'context',
112 'title' => 'Context',
113 ),
114 );
115 break;
116
117 default:
118 // oddballs are on their own
119 $metadata = array();
120 }
121
122 // find any supplemental information
123 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
124 try {
125 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
126 if (isset($hypApiRequest['function'])) {
127 $helper = '_' . $hypApiRequest['function'] . '_spec';
128 }
129 else {
130 // not implemented MagicFunctionProvider
131 $helper = NULL;
132 }
133 }
134 catch (\Civi\API\Exception\NotImplementedException $e) {
135 $helper = NULL;
136 }
137 if (function_exists($helper)) {
138 // alter
139 $helper($metadata, $apiRequest);
140 }
141
142 $fieldsToResolve = (array) CRM_Utils_Array::value('get_options', $apiOptions, array());
143
144 foreach ($metadata as $fieldname => $fieldSpec) {
145 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve);
146 }
147
148 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], $entity, 'getfields');
149 return $results[$entity][$action][$sequential];
150 }
151
152 /**
153 * API return function to reformat results as count.
154 *
155 * @param array $apiRequest
156 * Api request as an array. Keys are.
157 *
158 * @throws API_Exception
159 * @return int
160 * count of results
161 */
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'];
167 }
168 if (!isset($result['count'])) {
169 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
170 }
171 return $result['count'];
172 }
173
174 /**
175 * API return function to reformat results as single result.
176 *
177 * @param array $apiRequest
178 * Api request as an array. Keys are.
179 *
180 * @return int
181 * count of results
182 */
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) {
188 return $result;
189 }
190 if ($result['count'] === 1) {
191 return $result['values'][0];
192 }
193 if ($result['count'] !== 1) {
194 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
195 }
196 return civicrm_api3_create_error("Undefined behavior");
197 }
198
199 /**
200 * API return function to reformat results as single value.
201 *
202 * @param array $apiRequest
203 * Api request as an array. Keys are.
204 *
205 * @return int
206 * count of results
207 */
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) {
212 return $result;
213 }
214 if ($result['count'] !== 1) {
215 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
216 return $result;
217 }
218
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']));
223 }
224
225 return $result['values'][0][$apiRequest['params']['return']];
226 }
227
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'));
229 }
230
231 /**
232 * Get count of contact references.
233 *
234 * @param array $params
235 */
236 function _civicrm_api3_generic_getrefcount_spec(&$params) {
237 $params['id']['api.required'] = 1;
238 $params['id']['title'] = 'Entity ID';
239 }
240
241 /**
242 * API to determine if a record is in-use.
243 *
244 * @param array $apiRequest
245 * Api request as an array.
246 *
247 * @throws API_Exception
248 * @return array
249 * API result (int 0 or 1)
250 */
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');
255 }
256 $daoClass = $entityToClassMap[$apiRequest['entity']];
257
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());
263 }
264 else {
265 return civicrm_api3_create_success(array());
266 }
267 }
268
269 /**
270 * API wrapper for replace function.
271 *
272 * @param array $apiRequest
273 * Api request as an array. Keys are.
274 *
275 * @return int
276 * count of results
277 */
278 function civicrm_api3_generic_replace($apiRequest) {
279 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
280 }
281
282 /**
283 * API wrapper for getoptions function.
284 *
285 * @param array $apiRequest
286 * Api request as an array.
287 *
288 * @return array
289 * Array of results
290 */
291 function civicrm_api3_generic_getoptions($apiRequest) {
292 // Resolve aliases.
293 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
294 if (!$fieldName) {
295 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
296 }
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']);
301
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.");
306 }
307 // Support 'sequential' output as a non-associative array
308 if (!empty($apiRequest['params']['sequential'])) {
309 $options = CRM_Utils_Array::makeNonAssociative($options);
310 }
311 return civicrm_api3_create_success($options, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
312 }
313
314 /**
315 * Get metadata.
316 *
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
324 *
325 * This function is only split out for the purpose of code clarity / comment block documentation
326 *
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.
336 */
337 function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve) {
338 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
339 return;
340 }
341
342 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
343 return;
344 }
345
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'];
349 }
350 }