Support custom fields CRM-12464
[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 if(!empty($apiRequest['params']['fieldname'])){
27 CRM_Utils_PseudoConstant::flushConstant($apiRequest['params']['fieldname']);
28 }
29 if(!empty($apiRequest['params']['option_group_id'])){
30 $optionGroupName = civicrm_api('option_group', 'getvalue', array('version' => 3, 'id' => $apiRequest['params']['option_group_id'], 'return' => 'name') );
31 if(is_string($optionGroupName)){
32 CRM_Utils_PseudoConstant::flushConstant(_civicrm_api_get_camel_name($optionGroupName));
33 }
34 }
35 }
36 $entity = _civicrm_api_get_camel_name($apiRequest['entity']);
37 $lcase_entity = _civicrm_api_get_entity_name_from_camel($entity);
38 $subentity = CRM_Utils_Array::value('contact_type', $apiRequest['params']);
39 $action = strtolower(CRM_Utils_Array::value('action', $apiRequest['params']));
40 $apiOptions = CRM_Utils_Array::value('options', $apiRequest['params'], array());
41 if ($action == 'getvalue' || $action == 'getvalue' || $action == 'getcount') {
42 $action = 'get';
43 }
44
45 if (empty($action)) {
46 $action='get';
47 }
48 // determines whether to use unique field names - seem comment block above
49 $unique = TRUE;
50 if (isset($results[$entity . $subentity]) && CRM_Utils_Array::value($action, $results[$entity])
51 && empty($apiOptions)) {
52 return $results[$entity . $subentity][$action];
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 case 'create':
60 case 'update':
61 case 'replace':
62 $unique = FALSE;
63 case 'get':
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('title' => 'Unique Identifier',
86 'api.required' => 1,
87 'api.aliases' => array($lcase_entity . '_id'),
88 ));
89 break;
90
91 case 'getoptions':
92 $metadata = array(
93 'field' => array('title' => 'Field to retrieve options for',
94 'api.required' => 1,
95 ));
96 break;
97 default:
98 // oddballs are on their own
99 $metadata = array();
100 }
101
102 // find any supplemental information
103 $hypApiRequest = array('entity' => $apiRequest['entity'], 'action' => $action, 'version' => $apiRequest['version']);
104 $hypApiRequest += _civicrm_api_resolve($hypApiRequest);
105 $helper = '_' . $hypApiRequest['function'] . '_spec';
106 if (function_exists($helper)) {
107 // alter
108 $helper($metadata);
109 }
110
111 $fieldsToResolve = CRM_Utils_Array::value('get_options', $apiOptions, array());
112
113 foreach ($metadata as $fieldname => $fieldSpec) {
114 _civicrm_api3_generic_get_metadata_options($metadata, $fieldname, $fieldSpec, $fieldsToResolve);
115 }
116
117 $results[$entity][$action] = civicrm_api3_create_success($metadata, $apiRequest['params'], NULL, 'getfields');
118 return $results[$entity][$action];
119 }
120
121 /**
122 * API return function to reformat results as count
123 *
124 * @param array $apiRequest api request as an array. Keys are
125 *
126 * @return integer count of results
127 */
128 function civicrm_api3_generic_getcount($apiRequest) {
129 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
130 return $result['count'];
131 }
132
133 /**
134 * API return function to reformat results as single result
135 *
136 * @param array $apiRequest api request as an array. Keys are
137 *
138 * @return integer count of results
139 */
140 function civicrm_api3_generic_getsingle($apiRequest) {
141 // so the first entity is always result['values'][0]
142 $apiRequest['params']['sequential'] = 1;
143 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
144 if ($result['is_error'] !== 0) {
145 return $result;
146 }
147 if ($result['count'] === 1) {
148 return $result['values'][0];
149 }
150 if ($result['count'] !== 1) {
151 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
152 }
153 return civicrm_api3_create_error("Undefined behavior");
154 }
155
156 /**
157 * API return function to reformat results as single value
158 *
159 * @param array $apiRequest api request as an array. Keys are
160 *
161 * @return integer count of results
162 */
163 function civicrm_api3_generic_getvalue($apiRequest) {
164 $apiRequest['params']['sequential'] = 1;
165 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
166 if ($result['is_error'] !== 0) {
167 return $result;
168 }
169 if ($result['count'] !== 1) {
170 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
171 return $result;
172 }
173
174 // we only take "return=" as valid options
175 if (CRM_Utils_Array::value('return', $apiRequest['params'])) {
176 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
177 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
178 }
179
180 return $result['values'][0][$apiRequest['params']['return']];
181 }
182
183 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
184 }
185
186 /**
187 * API wrapper for replace function
188 *
189 * @param array $apiRequest api request as an array. Keys are
190 *
191 * @return integer count of results
192 */
193 function civicrm_api3_generic_replace($apiRequest) {
194 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
195 }
196
197 /**
198 * API wrapper for getoptions function
199 *
200 * @param array $apiRequest api request as an array.
201 *
202 * @return array of results
203 */
204 function civicrm_api3_generic_getoptions($apiRequest) {
205 $daoName = _civicrm_api3_get_DAO($apiRequest['entity']);
206 $options = $daoName::buildOptions($apiRequest['params']['field']);
207 if ($options === FALSE) {
208 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' either doesn't exist or has no associated option list.");
209 }
210 return civicrm_api3_create_success($options);
211 }
212
213 /**
214 * Function fills the 'options' array on the metadata returned by getfields if
215 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
216 * (this is passed in as the $fieldsToResolve array)
217 * 2) the field is a pseudoconstant and is NOT an FK
218 * - the reason for this is that checking / transformation is done on pseudoconstants but
219 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
220 * @todo - if may be we should define a 'resolve' key on the psuedoconstant for when these rules are not fine enough
221 * 3) if there is an 'enum' then it is split up into the relevant options
222 *
223 * This function is only split out for the purpose of code clarity / comment block documentation
224 * @param array $metadata the array of metadata that will form the result of the getfields function
225 * @param string $fieldname field currently being processed
226 * @param array $fieldSpec metadata for that field
227 * @param array $fieldsToResolve anny field resolutions specifically requested
228 */
229 function _civicrm_api3_generic_get_metadata_options(&$metadata, $fieldname, $fieldSpec, $fieldsToResolve){
230 if (array_key_exists('enumValues', $fieldSpec)) {
231 // use of a space after the comma is inconsistent in xml
232 $enumStr = str_replace(', ', ',', $fieldSpec['enumValues']);
233 $metadata[$fieldname]['options'] = explode(',', $enumStr);
234 return;
235 }
236
237 if(empty($fieldSpec['pseudoconstant'])){
238 return ;
239 }
240 elseif(!empty($fieldSpec['FKClassName']) && !in_array($fieldname, $fieldsToResolve)){
241 return;
242 }
243 if(substr($fieldname, -3) == '_id'){
244 $metadata[$fieldname]['api.aliases'][] = substr($fieldname, 0, -3);
245 }
246
247 $pseudoParams = $fieldSpec['pseudoconstant'];
248 $pseudoParams['version'] = 3;
249 $options = civicrm_api('constant', 'get', $pseudoParams);
250 if (is_array(CRM_Utils_Array::value('values', $options))) {
251 $metadata[$fieldname]['options'] = $options['values'];
252 }
253 }