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