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