SearchKit - normalize search display column keys
[civicrm-core.git] / api / api.php
1 <?php
2
3 /**
4 * @file CiviCRM APIv3 API wrapper.
5 *
6 * @package CiviCRM_APIv3
7 */
8
9 /**
10 * CiviCRM API wrapper function.
11 *
12 * @param string $entity
13 * type of entities to deal with
14 * @param string $action
15 * create, get, delete or some special action name.
16 * @param array $params
17 * array to be passed to function
18 *
19 * @return array|int
20 */
21 function civicrm_api(string $entity, string $action, array $params) {
22 return \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
23 }
24
25 /**
26 * CiviCRM API version 4.
27 *
28 * This API (Application Programming Interface) is used to access and manage data in CiviCRM.
29 *
30 * APIv4 is the latest stable version.
31 *
32 * @see https://docs.civicrm.org/dev/en/latest/api/v4/usage/
33 *
34 * @param string $entity Name of the CiviCRM entity to access.
35 * All entity names are capitalized CamelCase, e.g. `ContributionPage`.
36 * Most entities correspond to a database table (e.g. `Contact` is the table `civicrm_contact`).
37 * For a complete list of available entities, call `civicrm_api4('Entity', 'get');`
38 *
39 * @param string $action The "verb" of the api call.
40 * For a complete list of actions for a given entity (e.g. `Contact`), call `civicrm_api4('Contact', 'getActions');`
41 *
42 * @param array $params An array of API input keyed by parameter name.
43 * The easiest way to discover all available parameters is to visit the API Explorer on your CiviCRM site.
44 * The API Explorer is listed in the CiviCRM menu under Support -> Developer.
45 *
46 * @param string|int|array $index Controls the Result array format.
47 * By default the api Result contains a non-associative array of data. Passing an $index tells the api to
48 * automatically reformat the array, depending on the variable type passed:
49 * - **Integer:** return a single result array;
50 * e.g. `$index = 0` will return the first result, 1 will return the second, and -1 will return the last.
51 * - **String:** index the results by a field value;
52 * e.g. `$index = "name"` will return an associative array with the field 'name' as keys.
53 * - **Non-associative array:** return a single value from each result;
54 * e.g. `$index = ['title']` will return a non-associative array of strings - the 'title' field from each result.
55 * - **Associative array:** a combination of the previous two modes;
56 * e.g. `$index = ['name' => 'title']` will return an array of strings - the 'title' field keyed by the 'name' field.
57 *
58 * @return \Civi\Api4\Generic\Result
59 * @throws \API_Exception
60 * @throws \Civi\API\Exception\NotImplementedException
61 */
62 function civicrm_api4(string $entity, string $action, array $params = [], $index = NULL) {
63 $indexField = $index && is_string($index) && !CRM_Utils_Rule::integer($index) ? $index : NULL;
64 $removeIndexField = FALSE;
65
66 // If index field is not part of the select query, we add it here and remove it below
67 if ($indexField && !empty($params['select']) && is_array($params['select']) && !\Civi\Api4\Utils\SelectUtil::isFieldSelected($indexField, $params['select'])) {
68 $params['select'][] = $indexField;
69 $removeIndexField = TRUE;
70 }
71 $apiCall = \Civi\API\Request::create($entity, $action, ['version' => 4] + $params);
72
73 if ($index && is_array($index)) {
74 $indexCol = reset($index);
75 $indexField = key($index);
76 if (property_exists($apiCall, 'select')) {
77 $apiCall->setSelect([$indexCol]);
78 if ($indexField && $indexField != $indexCol) {
79 $apiCall->addSelect($indexField);
80 }
81 }
82 }
83
84 $result = $apiCall->execute();
85
86 // Index results by key
87 if ($indexField) {
88 $result->indexBy($indexField);
89 if ($removeIndexField) {
90 foreach ($result as $key => $value) {
91 unset($result[$key][$indexField]);
92 }
93 }
94 }
95 // Return result at index
96 elseif (CRM_Utils_Rule::integer($index)) {
97 $item = $result->itemAt($index);
98 if (is_null($item)) {
99 throw new \API_Exception("Index $index not found in api results");
100 }
101 // Attempt to return a Result object if item is array, otherwise just return the item
102 if (!is_array($item)) {
103 return $item;
104 }
105 $result->exchangeArray($item);
106 }
107 if (!empty($indexCol)) {
108 $result->exchangeArray($result->column($indexCol));
109 }
110 return $result;
111 }
112
113 /**
114 * Version 3 wrapper for civicrm_api.
115 *
116 * Throws exception.
117 *
118 * @param string $entity
119 * Type of entities to deal with.
120 * @param string $action
121 * Create, get, delete or some special action name.
122 * @param array $params
123 * Array to be passed to function.
124 *
125 * @throws CiviCRM_API3_Exception
126 *
127 * @return array
128 */
129 function civicrm_api3(string $entity, string $action, array $params = []) {
130 $params['version'] = 3;
131 $result = \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
132 if (is_array($result) && !empty($result['is_error'])) {
133 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
134 }
135 return $result;
136 }
137
138 /**
139 * Call getfields from api wrapper.
140 *
141 * This function ensures that settings that
142 * could alter getfields output (e.g. action for all api & profile_id for
143 * profile api ) are consistently passed in.
144 *
145 * We check whether the api call is 'getfields' because if getfields is
146 * being called we return an empty array as no alias swapping, validation or
147 * default filling is done on getfields & we want to avoid a loop
148 *
149 * @todo other output modifiers include contact_type
150 *
151 * @param array $apiRequest
152 *
153 * @return array
154 * getfields output
155 */
156 function _civicrm_api3_api_getfields(&$apiRequest) {
157 if (strtolower($apiRequest['action'] == 'getfields')) {
158 // the main param getfields takes is 'action' - however this param is not compatible with REST
159 // so we accept 'api_action' as an alias of action on getfields
160 if (!empty($apiRequest['params']['api_action'])) {
161 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
162 // unset($apiRequest['params']['api_action']);
163 }
164 return ['action' => ['api.aliases' => ['api_action']]];
165 }
166 $getFieldsParams = ['action' => $apiRequest['action']];
167 $entity = $apiRequest['entity'];
168 if ($entity == 'Profile' && array_key_exists('profile_id', $apiRequest['params'])) {
169 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
170 }
171 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
172 return $fields['values'];
173 }
174
175 /**
176 * Check if the result is an error. Note that this function has been retained from
177 * api v2 for convenience but the result is more standardised in v3 and param
178 * 'format.is_success' => 1
179 * will result in a boolean success /fail being returned if that is what you need.
180 *
181 * @param $result
182 *
183 * @return bool
184 * true if error, false otherwise
185 */
186 function civicrm_error($result) {
187 return is_array($result) && !empty($result['is_error']);
188 }
189
190 /**
191 * Get camel case version of entity name.
192 *
193 * @param string|null $entity
194 *
195 * @return string|null
196 */
197 function _civicrm_api_get_camel_name($entity) {
198 return is_string($entity) ? \Civi\API\Request::normalizeEntityName($entity) : NULL;
199 }
200
201 /**
202 * Swap out any $values vars.
203 *
204 * Ie. the value after $value is swapped for the parent $result
205 * 'activity_type_id' => '$value.testfield',
206 * 'tag_id' => '$value.api.tag.create.id',
207 * 'tag1_id' => '$value.api.entity.create.0.id'
208 *
209 * @param array $params
210 * @param array $parentResult
211 * @param string $separator
212 */
213 function _civicrm_api_replace_variables(&$params, &$parentResult, $separator = '.') {
214 foreach ($params as $field => &$value) {
215 if (substr($field, 0, 4) == 'api.') {
216 // CRM-21246 - Leave nested calls alone.
217 continue;
218 }
219 if (is_string($value) && substr($value, 0, 6) == '$value') {
220 $value = _civicrm_api_replace_variable($value, $parentResult, $separator);
221 }
222 // Handle the operator syntax: array('OP' => $val)
223 elseif (is_array($value) && is_string(reset($value)) && substr(reset($value), 0, 6) == '$value') {
224 $key = key($value);
225 $value[$key] = _civicrm_api_replace_variable($value[$key], $parentResult, $separator);
226 // A null value with an operator will cause an error, so remove it.
227 if ($value[$key] === NULL) {
228 $value = '';
229 }
230 }
231 }
232 }
233
234 /**
235 * Swap out a $value.foo variable with the value from parent api results.
236 *
237 * Called by _civicrm_api_replace_variables to do the substitution.
238 *
239 * @param string $value
240 * @param array $parentResult
241 * @param string $separator
242 * @return mixed|null
243 */
244 function _civicrm_api_replace_variable($value, $parentResult, $separator) {
245 $valueSubstitute = substr($value, 7);
246
247 if (!empty($parentResult[$valueSubstitute])) {
248 return $parentResult[$valueSubstitute];
249 }
250 else {
251 $stringParts = explode($separator, $value);
252 unset($stringParts[0]);
253 // CRM-16168 If we have failed to swap it out we should unset it rather than leave the placeholder.
254 $value = NULL;
255
256 $fieldname = array_shift($stringParts);
257
258 //when our string is an array we will treat it as an array from that . onwards
259 $count = count($stringParts);
260 while ($count > 0) {
261 $fieldname .= "." . array_shift($stringParts);
262 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
263 $arrayLocation = $parentResult[$fieldname];
264 foreach ($stringParts as $key => $innerValue) {
265 $arrayLocation = $arrayLocation[$innerValue] ?? NULL;
266 }
267 $value = $arrayLocation;
268 }
269 $count = count($stringParts);
270 }
271 }
272 return $value;
273 }
274
275 /**
276 * Convert possibly camel name to underscore separated entity name.
277 *
278 * @param string $entity
279 * Entity name in various formats e.g. Contribution, contribution,
280 * OptionValue, option_value, UFJoin, uf_join.
281 *
282 * @return string
283 * Entity name in underscore separated format.
284 *
285 * @deprecated
286 */
287 function _civicrm_api_get_entity_name_from_camel($entity) {
288 if (!$entity) {
289 // @todo - this should not be called when empty.
290 return '';
291 }
292 return CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($entity);
293 }
294
295 /**
296 * Having a DAO object find the entity name.
297 *
298 * @param CRM_Core_DAO $bao
299 * DAO being passed in.
300 *
301 * @return string
302 */
303 function _civicrm_api_get_entity_name_from_dao($bao) {
304 return CRM_Core_DAO_AllCoreTables::getBriefName(get_class($bao));
305 }