Merge pull request #3284 from eileenmcnaughton/comments
[civicrm-core.git] / api / v3 / Generic.php
CommitLineData
6a488035 1<?php
6a488035
TO
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 */
21function 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
37547b77 26 CRM_Core_PseudoConstant::flush();
6a488035
TO
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']));
ceccbc35 41 $sequential = empty($apiRequest['params']) ? 0 : 1;
6a488035 42 $apiOptions = CRM_Utils_Array::value('options', $apiRequest['params'], array());
54df0f0c 43 if (!$action || $action == 'getvalue' || $action == 'getcount') {
6a488035
TO
44 $action = 'get';
45 }
6a488035
TO
46 // determines whether to use unique field names - seem comment block above
47 $unique = TRUE;
ceccbc35 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];
6a488035
TO
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']);
f2b53f26 56 return civicrm_api3_create_success($values, $apiRequest['params'], $entity, 'getfields');
6a488035
TO
57 case 'create':
58 case 'update':
59 case 'replace':
60 $unique = FALSE;
61 case 'get':
2b6e1174
CW
62 case 'getsingle':
63 case 'getcount':
6a488035 64 $metadata = _civicrm_api_get_fields($apiRequest['entity'], $unique, $apiRequest['params']);
9ec90e57 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
6a488035 79 $metadata['id']['api.aliases'] = array($lcase_entity . '_id');
6a488035
TO
80 }
81 break;
82
83 case 'delete':
84 $metadata = array(
3a8e9315
CW
85 'id' => array(
86 'title' => $entity . ' ID',
87 'name' => 'id',
6a488035
TO
88 'api.required' => 1,
89 'api.aliases' => array($lcase_entity . '_id'),
b2402735 90 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
91 ));
92 break;
93
94 case 'getoptions':
95 $metadata = array(
786ad6e1 96 'field' => array(
3a8e9315
CW
97 'name' => 'field',
98 'title' => 'Field name',
786ad6e1
CW
99 'api.required' => 1,
100 ),
101 'context' => array(
3a8e9315
CW
102 'name' => 'context',
103 'title' => 'Context',
786ad6e1
CW
104 ),
105 );
6a488035
TO
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']);
c65db512
TO
114 try {
115 list ($apiProvider, $hypApiRequest) = \Civi\Core\Container::singleton()->get('civi_api_kernel')->resolve($hypApiRequest);
116 $helper = '_' . $hypApiRequest['function'] . '_spec';
117 } catch (\Civi\API\Exception\NotImplementedException $e) {
118 $helper = NULL;
119 }
6a488035
TO
120 if (function_exists($helper)) {
121 // alter
6a386447 122 $helper($metadata, $apiRequest);
6a488035
TO
123 }
124
a4c5e9a3 125 $fieldsToResolve = (array) CRM_Utils_Array::value('get_options', $apiOptions, array());
6a488035
TO
126
127 foreach ($metadata as $fieldname => $fieldSpec) {
ddaac11c 128 _civicrm_api3_generic_get_metadata_options($metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve);
6a488035
TO
129 }
130
ceccbc35 131 $results[$entity][$action][$sequential] = civicrm_api3_create_success($metadata, $apiRequest['params'], NULL, 'getfields');
132 return $results[$entity][$action][$sequential];
6a488035
TO
133}
134
135/**
136 * API return function to reformat results as count
137 *
138 * @param array $apiRequest api request as an array. Keys are
139 *
77b97be7 140 * @throws API_Exception
6a488035
TO
141 * @return integer count of results
142 */
143function civicrm_api3_generic_getcount($apiRequest) {
972322c5 144 $apiRequest['params']['options']['is_count'] = TRUE;
6a488035 145 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
972322c5 146 if(is_numeric (CRM_Utils_Array::value('values', $result))) {
147 return (int) $result['values'];
148 }
8335b10a 149 if(!isset($result['count'])) {
150 throw new API_Exception(ts('Unexpected result from getcount') . print_r($result, TRUE));
151 }
6a488035
TO
152 return $result['count'];
153}
154
155/**
156 * API return function to reformat results as single result
157 *
158 * @param array $apiRequest api request as an array. Keys are
159 *
160 * @return integer count of results
161 */
162function civicrm_api3_generic_getsingle($apiRequest) {
163 // so the first entity is always result['values'][0]
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 return $result['values'][0];
171 }
172 if ($result['count'] !== 1) {
173 return civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
174 }
175 return civicrm_api3_create_error("Undefined behavior");
176}
177
178/**
179 * API return function to reformat results as single value
180 *
181 * @param array $apiRequest api request as an array. Keys are
182 *
183 * @return integer count of results
184 */
185function civicrm_api3_generic_getvalue($apiRequest) {
186 $apiRequest['params']['sequential'] = 1;
187 $result = civicrm_api($apiRequest['entity'], 'get', $apiRequest['params']);
188 if ($result['is_error'] !== 0) {
189 return $result;
190 }
191 if ($result['count'] !== 1) {
192 $result = civicrm_api3_create_error("Expected one " . $apiRequest['entity'] . " but found " . $result['count'], array('count' => $result['count']));
193 return $result;
194 }
195
196 // we only take "return=" as valid options
a7488080 197 if (!empty($apiRequest['params']['return'])) {
6a488035
TO
198 if (!isset($result['values'][0][$apiRequest['params']['return']])) {
199 return civicrm_api3_create_error("field " . $apiRequest['params']['return'] . " unset or not existing", array('invalid_field' => $apiRequest['params']['return']));
200 }
201
202 return $result['values'][0][$apiRequest['params']['return']];
203 }
204
205 return civicrm_api3_create_error("missing param return=field you want to read the value of", array('error_type' => 'mandatory_missing', 'missing_param' => 'return'));
206}
207
208/**
209 * API wrapper for replace function
210 *
211 * @param array $apiRequest api request as an array. Keys are
212 *
213 * @return integer count of results
214 */
215function civicrm_api3_generic_replace($apiRequest) {
216 return _civicrm_api3_generic_replace($apiRequest['entity'], $apiRequest['params']);
217}
218
219/**
220 * API wrapper for getoptions function
221 *
ee2b1c1c 222 * @param array $apiRequest api request as an array.
6a488035
TO
223 *
224 * @return array of results
225 */
226function civicrm_api3_generic_getoptions($apiRequest) {
70f7ba9e
CW
227 // Resolve aliases
228 $fieldName = _civicrm_api3_api_resolve_alias($apiRequest['entity'], $apiRequest['params']['field']);
229 if (!$fieldName) {
230 return civicrm_api3_create_error("The field '{$apiRequest['params']['field']}' doesn't exist.");
231 }
a4a33486 232 // Validate 'context' from params
786ad6e1
CW
233 $context = CRM_Utils_Array::value('context', $apiRequest['params']);
234 CRM_Core_DAO::buildOptionsContext($context);
a3d8b390 235 unset($apiRequest['params']['context'], $apiRequest['params']['field']);
70f7ba9e 236
786ad6e1 237 $baoName = _civicrm_api3_get_BAO($apiRequest['entity']);
15a1171a 238 $options = $output = $baoName::buildOptions($fieldName, $context, $apiRequest['params']);
ee2b1c1c 239 if ($options === FALSE) {
70f7ba9e 240 return civicrm_api3_create_error("The field '{$fieldName}' has no associated option list.");
6a488035 241 }
15a1171a
CW
242 // Support 'sequential' output as a non-associative array
243 if (!empty($apiRequest['params']['sequential'])) {
244 $output = array();
245 foreach ($options as $key => $val) {
246 $output[] = array('key' => $key, 'value' => $val);
247 }
248 }
54df0f0c 249 return civicrm_api3_create_success($output, $apiRequest['params'], $apiRequest['entity'], 'getoptions');
6a488035
TO
250}
251
11e09c59 252/**
6a488035
TO
253 * Function fills the 'options' array on the metadata returned by getfields if
254 * 1) the param option 'get_options' is defined - e.g. $params['options']['get_options'] => array('custom_1)
255 * (this is passed in as the $fieldsToResolve array)
256 * 2) the field is a pseudoconstant and is NOT an FK
257 * - the reason for this is that checking / transformation is done on pseudoconstants but
258 * - if the field is an FK then mysql will enforce the data quality (& we have handling on failure)
259 * @todo - if may be we should define a 'resolve' key on the psuedoconstant for when these rules are not fine enough
6a488035
TO
260 *
261 * This function is only split out for the purpose of code clarity / comment block documentation
77b97be7 262 *
6a488035 263 * @param array $metadata the array of metadata that will form the result of the getfields function
77b97be7 264 * @param $apiRequest
6a488035
TO
265 * @param string $fieldname field currently being processed
266 * @param array $fieldSpec metadata for that field
267 * @param array $fieldsToResolve anny field resolutions specifically requested
268 */
ddaac11c 269function _civicrm_api3_generic_get_metadata_options(&$metadata, $apiRequest, $fieldname, $fieldSpec, $fieldsToResolve){
3a8e9315 270 if (empty($fieldSpec['pseudoconstant']) && empty($fieldSpec['option_group_id'])) {
6a488035
TO
271 return;
272 }
273
ed8abbbb 274 if (!empty($metadata[$fieldname]['options']) || (!in_array($fieldname, $fieldsToResolve) && !in_array('all', $fieldsToResolve))) {
70f7ba9e
CW
275 return;
276 }
277
ddaac11c 278 $options = civicrm_api($apiRequest['entity'], 'getoptions', array('version' => 3, 'field' => $fieldname, 'sequential' => !empty($apiRequest['params']['sequential'])));
6a488035
TO
279 if (is_array(CRM_Utils_Array::value('values', $options))) {
280 $metadata[$fieldname]['options'] = $options['values'];
281 }
282}