Merge pull request #583 from yashodha/CRM-12463
[civicrm-core.git] / api / v3 / Generic.php
CommitLineData
6a488035
TO
1<?php
2// $Id$
3
4/**
5 * Get information about fields for a given api request. Getfields information
6 * 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 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 */
22function 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 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 $apiOptions = CRM_Utils_Array::value('options', $apiRequest['params'], array());
42 if ($action == 'getvalue' || $action == 'getvalue' || $action == 'getcount') {
43 $action = 'get';
44 }
45
46 if (empty($action)) {
47 $action='get';
48 }
49 // determines whether to use unique field names - seem comment block above
50 $unique = TRUE;
51 if (isset($results[$entity . $subentity]) && CRM_Utils_Array::value($action, $results[$entity])
52 && empty($apiOptions)) {
53 return $results[$entity . $subentity][$action];
54 }
55 // defaults based on data model and API policy
56 switch ($action) {
57 case 'getfields':
58 $values = _civicrm_api_get_fields($entity, false, $apiRequest['params']);
59 $results[$entity][$action] = civicrm_api3_create_success($values,
60 $apiRequest['params'], $entity, 'getfields'
61 );
62 return $results[$entity][$action];
63
64 case 'getfields':
65 return civicrm_api3_create_success(_civicrm_api_get_fields($apiRequest['entity']));
66 case 'create':
67 case 'update':
68 case 'replace':
69 $unique = FALSE;
70 case 'get':
71 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
9ec90e57 72 if (empty($metadata['id'])){
73 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
74 if(!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
75 $metadata['id'] = $metadata[$lcase_entity . '_id'];
76 unset($metadata[$lcase_entity . '_id']);
77 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
78 }
79 }
80 else{
81 // really the preference would be to set the unique name in the xml
82 // question is which is a less risky fix this close to a release - setting in xml for the known failure
83 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
84 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
85 // inconsistency
6a488035 86 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
6a488035 87 }
9ec90e57 88
6a488035
TO
89 break;
90
91 case 'delete':
92 $metadata = array(
93 'id' => array('title' => 'Unique Identifier',
94 'api.required' => 1,
95 'api.aliases' => array($lcase_entity . '_id'),
96 ));
97 break;
98
99 case 'getoptions':
100 $metadata = array(
101 'field' => array('title' => 'Field to retrieve options for',
102 'api.required' => 1,
103 ));
104 break;
105 default:
106 // oddballs are on their own
107 $metadata = array();
108 }
109
110 // find any supplemental information
111 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
112 $hypApiRequest += _civicrm_api_resolve($hypApiRequest);
113 $helper = '_' . $hypApiRequest['function'] . '_spec';
114 if (function_exists($helper)) {
115 // alter
116 $helper($metadata);
117 }
118
119 $fieldsToResolve = CRM_Utils_Array::value('get_options', $apiOptions, array());
120
121 foreach ($metadata as $fieldname => $fieldSpec) {
122 _civicrm_api3_generic_get_metadata_options($metadata, $fieldname, $fieldSpec, $fieldsToResolve);
123 }
124
125 $results[$entity][$action] = civicrm_api3_create_success($metadata, $apiRequest['params'], NULL, 'getfields');
126 return $results[$entity][$action];
127}
128
129/**
130 * API return function to reformat results as count
131 *
132 * @param array $apiRequest api request as an array. Keys are
133 *
134 * @return integer count of results
135 */
136function civicrm_api3_generic_getcount($apiRequest) {
137 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
138 return $result['count'];
139}
140
141/**
142 * API return function to reformat results as single result
143 *
144 * @param array $apiRequest api request as an array. Keys are
145 *
146 * @return integer count of results
147 */
148function civicrm_api3_generic_getsingle($apiRequest) {
149 // so the first entity is always result['values'][0]
150 $apiRequest['params']['sequential'] = 1;
151 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
152 if ($result['is_error'] !== 0) {
153 return $result;
154 }
155 if ($result['count'] === 1) {
156 return $result['values'][0];
157 }
158 if ($result['count'] !== 1) {
159 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
160 }
161 return civicrm_api3_create_error("Undefined behavior");
162}
163
164/**
165 * API return function to reformat results as single value
166 *
167 * @param array $apiRequest api request as an array. Keys are
168 *
169 * @return integer count of results
170 */
171function civicrm_api3_generic_getvalue($apiRequest) {
172 $apiRequest['params']['sequential'] = 1;
173 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
174 if ($result['is_error'] !== 0) {
175 return $result;
176 }
177 if ($result['count'] !== 1) {
178 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
179 return $result;
180 }
181
182 // we only take "return=" as valid options
183 if (CRM_Utils_Array::value('return', $apiRequest['params'])) {
184 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
185 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
186 }
187
188 return $result['values'][0][$apiRequest['params']['return']];
189 }
190
191 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
192}
193
194/**
195 * API wrapper for replace function
196 *
197 * @param array $apiRequest api request as an array. Keys are
198 *
199 * @return integer count of results
200 */
201function civicrm_api3_generic_replace($apiRequest) {
202 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
203}
204
205/**
206 * API wrapper for getoptions function
207 *
208 * @param array $apiRequest api request as an array. Keys are
209 *
210 * @return array of results
211 */
212function civicrm_api3_generic_getoptions($apiRequest) {
213 $field = $apiRequest['params']['field'];
214 $getFieldsArray = array(
215 'version' => 3,
216 'action' => 'create',
217 'options' => array('get_options' => $field),
218 );
219 // First try to retrieve the options from getfields
220 $result = civicrm_api($apiRequest['entity'], 'getfields', $getFieldsArray);
221 if (!isset($result['values'][$field]) && isset($result['values'][$field . '_id'])) {
222 $field = $field . '_id';
223 }
224 if (!empty($result['values'][$field]['options'])) {
225 return civicrm_api3_create_success($result['values'][$field]['options']);
226 }
227 // If that didn't work, try the constant api
228 if (substr($field, -3) == '_id') {
229 // Convert foo_id to just plain foo
230 $field = substr($field, 0, -3);
231 }
232 $params = array('name' => _civicrm_api_get_camel_name($field));
233 $entity = strtolower($apiRequest['entity']);
234 if ($entity == 'contribution') {
235 $params['class'] = 'CRM_Contribute_PseudoConstant';
236 }
237 elseif ($entity == 'event' || $entity == 'participant') {
238 $params['class'] = 'CRM_Event_PseudoConstant';
239 }
240 elseif (strpos($entity, 'membership') === 0) {
241 $params['class'] = 'CRM_Member_PseudoConstant';
242 }
243 require_once 'api/v3/Constant.php';
244 return civicrm_api3_constant_get($params);
245}
246
11e09c59 247/**
6a488035
TO
248 * Function fills the 'options' array on the metadata returned by getfields if
249 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
250 * (this is passed in as the $fieldsToResolve array)
251 * 2) the field is a pseudoconstant and is NOT an FK
252 * - the reason for this is that checking / transformation is done on pseudoconstants but
253 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
254 * @todo - if may be we should define a 'resolve' key on the psuedoconstant for when these rules are not fine enough
255 * 3) if there is an 'enum' then it is split up into the relevant options
256 *
257 * This function is only split out for the purpose of code clarity / comment block documentation
258 * @param array $metadata the array of metadata that will form the result of the getfields function
259 * @param string $fieldname field currently being processed
260 * @param array $fieldSpec metadata for that field
261 * @param array $fieldsToResolve anny field resolutions specifically requested
262 */
263function _civicrm_api3_generic_get_metadata_options(&$metadata, $fieldname, $fieldSpec, $fieldsToResolve){
264 if (array_key_exists('enumValues', $fieldSpec)) {
265 // use of a space after the comma is inconsistent in xml
266 $enumStr = str_replace(', ', ',', $fieldSpec['enumValues']);
267 $metadata[$fieldname]['options'] = explode(',', $enumStr);
268 return;
269 }
270
271 if(empty($fieldSpec['pseudoconstant'])){
272 return ;
273 }
274 elseif(!empty($fieldSpec['FKClassName']) && !in_array($fieldname, $fieldsToResolve)){
275 return;
276 }
277 if(substr($fieldname, -3) == '_id'){
278 $metadata[$fieldname]['api.aliases'][] = substr($fieldname, 0, -3);
279 }
280
281 $pseudoParams = $fieldSpec['pseudoconstant'];
282 $pseudoParams['version'] = 3;
283 $options = civicrm_api('constant', 'get', $pseudoParams);
284 if (is_array(CRM_Utils_Array::value('values', $options))) {
285 $metadata[$fieldname]['options'] = $options['values'];
286 }
287}