Merge pull request #2521 from kurund/CRM-14181
[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 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
63 if (empty($metadata['id'])){
64 // if id is not set we will set it eg. 'id' from 'case_id', case_id will be an alias
65 if(!empty($metadata[strtolower($apiRequest['entity']) . '_id'])) {
66 $metadata['id'] = $metadata[$lcase_entity . '_id'];
67 unset($metadata[$lcase_entity . '_id']);
68 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
69 }
70 }
71 else{
72 // really the preference would be to set the unique name in the xml
73 // question is which is a less risky fix this close to a release - setting in xml for the known failure
74 // (note) or setting for all api where fields is returning 'id' & we want to accept 'note_id' @ the api layer
75 // nb we don't officially accept note_id anyway - rationale here is more about centralising a now-tested
76 // inconsistency
77 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
78 }
79 break;
80
81 case 'delete':
82 $metadata = array(
83 'id' => array('title' => 'Unique Identifier',
84 'api.required' => 1,
85 'api.aliases' => array($lcase_entity . '_id'),
86 'type' => CRM_Utils_Type::T_INT,
87 ));
88 break;
89
90 case 'getoptions':
91 $metadata = array(
92 'field' => array(
93 'title' => 'Field to retrieve options for',
94 'api.required' => 1,
95 ),
96 'context' => array(
97 'title' => 'Context string',
98 ),
99 );
100 break;
101 default:
102 // oddballs are on their own
103 $metadata = array();
104 }
105
106 // find any supplemental information
107 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
108 $hypApiRequest += _civicrm_api_resolve($hypApiRequest);
109 $helper = '_' . $hypApiRequest['function'] . '_spec';
110 if (function_exists($helper)) {
111 // alter
112 $helper($metadata, $apiRequest);
113 }
114
115 $fieldsToResolve = (array) CRM_Utils_Array::value('get_options', $apiOptions, array());
116
117 foreach ($metadata as $fieldname => $fieldSpec) {
118 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest['entity'], $fieldname, $fieldSpec, $fieldsToResolve);
119 }
120
121 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], NULL, 'getfields');
122 return $results[$entity][$action][$sequential];
123 }
124
125 /**
126 * API return function to reformat results as count
127 *
128 * @param array $apiRequest api request as an array. Keys are
129 *
130 * @return integer count of results
131 */
132 function civicrm_api3_generic_getcount($apiRequest) {
133 $apiRequest['params']['options']['is_count'] = TRUE;
134 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
135 if(is_numeric (CRM_Utils_Array::value('values', $result))) {
136 return (int) $result['values'];
137 }
138 if(!isset($result['count'])) {
139 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
140 }
141 return $result['count'];
142 }
143
144 /**
145 * API return function to reformat results as single result
146 *
147 * @param array $apiRequest api request as an array. Keys are
148 *
149 * @return integer count of results
150 */
151 function civicrm_api3_generic_getsingle($apiRequest) {
152 // so the first entity is always result['values'][0]
153 $apiRequest['params']['sequential'] = 1;
154 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
155 if ($result['is_error'] !== 0) {
156 return $result;
157 }
158 if ($result['count'] === 1) {
159 return $result['values'][0];
160 }
161 if ($result['count'] !== 1) {
162 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
163 }
164 return civicrm_api3_create_error("Undefined behavior");
165 }
166
167 /**
168 * API return function to reformat results as single value
169 *
170 * @param array $apiRequest api request as an array. Keys are
171 *
172 * @return integer count of results
173 */
174 function civicrm_api3_generic_getvalue($apiRequest) {
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 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
182 return $result;
183 }
184
185 // we only take "return=" as valid options
186 if (!empty($apiRequest['params']['return'])) {
187 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
188 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
189 }
190
191 return $result['values'][0][$apiRequest['params']['return']];
192 }
193
194 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
195 }
196
197 /**
198 * API wrapper for replace function
199 *
200 * @param array $apiRequest api request as an array. Keys are
201 *
202 * @return integer count of results
203 */
204 function civicrm_api3_generic_replace($apiRequest) {
205 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
206 }
207
208 /**
209 * API wrapper for getoptions function
210 *
211 * @param array $apiRequest api request as an array.
212 *
213 * @return array of results
214 */
215 function civicrm_api3_generic_getoptions($apiRequest) {
216 // Resolve aliases
217 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
218 if (!$fieldName) {
219 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
220 }
221 // Validate 'context' from params
222 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
223 CRM_Core_DAO::buildOptionsContext($context);
224 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
225
226 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
227 $options = $output = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
228 if ($options === FALSE) {
229 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
230 }
231 // Support 'sequential' output as a non-associative array
232 if (!empty($apiRequest['params']['sequential'])) {
233 $output = array();
234 foreach ($options as $key => $val) {
235 $output[] = array('key' => $key, 'value' => $val);
236 }
237 }
238 return civicrm_api3_create_success($output, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
239 }
240
241 /**
242 * Function fills the 'options' array on the metadata returned by getfields if
243 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
244 * (this is passed in as the $fieldsToResolve array)
245 * 2) the field is a pseudoconstant and is NOT an FK
246 * - the reason for this is that checking / transformation is done on pseudoconstants but
247 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
248 * @todo - if may be we should define a 'resolve' key on the psuedoconstant for when these rules are not fine enough
249 *
250 * This function is only split out for the purpose of code clarity / comment block documentation
251 * @param array $metadata the array of metadata that will form the result of the getfields function
252 * @param string $fieldname field currently being processed
253 * @param array $fieldSpec metadata for that field
254 * @param array $fieldsToResolve anny field resolutions specifically requested
255 */
256 function _civicrm_api3_generic_get_metadata_options(&$metadata, $entity, $fieldname, $fieldSpec, $fieldsToResolve){
257 if (empty($fieldSpec['pseudoconstant'])) {
258 return;
259 }
260
261 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
262 return;
263 }
264
265 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldname));
266 if (is_array(CRM_Utils_Array::value('values', $options))) {
267 $metadata[$fieldname]['options'] = $options['values'];
268 }
269 }