Update contributor-key.yml
[civicrm-core.git] / api / api.php
CommitLineData
6a488035
TO
1<?php
2
3/**
b081365f 4 * @file CiviCRM APIv3 API wrapper.
6a488035
TO
5 *
6 * @package CiviCRM_APIv3
6a488035
TO
7 */
8
11e09c59 9/**
9d32e6f7
EM
10 * CiviCRM API wrapper function.
11 *
6a488035
TO
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
8904518f 18 *
19 * @return array|int
6a488035 20 */
f27ab61d
CW
21function civicrm_api(string $entity, string $action, array $params) {
22 return \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
6a488035
TO
23}
24
f0b90b06 25/**
0493ec47 26 * CiviCRM API version 4.
f0b90b06 27 *
9cea3619
CW
28 * This API (Application Programming Interface) is used to access and manage data in CiviCRM.
29 *
30 * APIv4 is the latest stable version.
31 *
0493ec47 32 * @see https://docs.civicrm.org/dev/en/latest/api/v4/usage/
9cea3619
CW
33 *
34 * @param string $entity Name of the CiviCRM entity to access.
136ca5bb
CW
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');`
9cea3619
CW
38 *
39 * @param string $action The "verb" of the api call.
136ca5bb 40 * For a complete list of actions for a given entity (e.g. `Contact`), call `civicrm_api4('Contact', 'getActions');`
9cea3619
CW
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:
136ca5bb
CW
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.
f0b90b06
C
57 *
58 * @return \Civi\Api4\Generic\Result
59 * @throws \API_Exception
60 * @throws \Civi\API\Exception\NotImplementedException
61 */
0b0b329b 62function civicrm_api4(string $entity, string $action, array $params = [], $index = NULL) {
56d00639
CW
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
39e0f675 67 if ($indexField && !empty($params['select']) && is_array($params['select']) && !\Civi\Api4\Utils\SelectUtil::isFieldSelected($indexField, $params['select'])) {
56d00639
CW
68 $params['select'][] = $indexField;
69 $removeIndexField = TRUE;
70 }
3a8dc228 71 $apiCall = \Civi\API\Request::create($entity, $action, ['version' => 4] + $params);
4a7dc83a
CW
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
f0b90b06
C
84 $result = $apiCall->execute();
85
86 // Index results by key
56d00639
CW
87 if ($indexField) {
88 $result->indexBy($indexField);
89 if ($removeIndexField) {
90 foreach ($result as $key => $value) {
91 unset($result[$key][$indexField]);
92 }
93 }
f0b90b06
C
94 }
95 // Return result at index
56d00639 96 elseif (CRM_Utils_Rule::integer($index)) {
f0b90b06
C
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);
f0b90b06 106 }
4a7dc83a
CW
107 if (!empty($indexCol)) {
108 $result->exchangeArray($result->column($indexCol));
109 }
f0b90b06
C
110 return $result;
111}
112
6b359437 113/**
9d32e6f7
EM
114 * Version 3 wrapper for civicrm_api.
115 *
116 * Throws exception.
8904518f 117 *
cf470720
TO
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.
6b359437 124 *
8904518f 125 * @throws CiviCRM_API3_Exception
301906ab 126 *
6b359437 127 * @return array
6b359437 128 */
0b0b329b 129function civicrm_api3(string $entity, string $action, array $params = []) {
6b359437 130 $params['version'] = 3;
7b810209 131 $result = \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
9b873358 132 if (is_array($result) && !empty($result['is_error'])) {
6b359437 133 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
134 }
c4ac4df4 135 return $result;
6b359437 136}
6a488035 137
94359f7e 138/**
dc64d047
EM
139 * Call getfields from api wrapper.
140 *
141 * This function ensures that settings that
7cdbcb16
TO
142 * could alter getfields output (e.g. action for all api & profile_id for
143 * profile api ) are consistently passed in.
94359f7e 144 *
7cdbcb16
TO
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
94359f7e 148 *
149 * @todo other output modifiers include contact_type
150 *
151 * @param array $apiRequest
dc64d047 152 *
a6c01b45 153 * @return array
e94b9071 154 * getfields output
94359f7e 155 */
156function _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
a7488080 160 if (!empty($apiRequest['params']['api_action'])) {
35671d00
TO
161 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
162 // unset($apiRequest['params']['api_action']);
94359f7e 163 }
cf8f0fff 164 return ['action' => ['api.aliases' => ['api_action']]];
94359f7e 165 }
cf8f0fff 166 $getFieldsParams = ['action' => $apiRequest['action']];
94359f7e 167 $entity = $apiRequest['entity'];
1644b908 168 if ($entity == 'Profile' && array_key_exists('profile_id', $apiRequest['params'])) {
94359f7e 169 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
170 }
171 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
172 return $fields['values'];
173}
8904518f 174
6a488035
TO
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 *
8904518f 181 * @param $result
182 *
5c766a0b 183 * @return bool
e94b9071 184 * true if error, false otherwise
6a488035
TO
185 */
186function civicrm_error($result) {
187 if (is_array($result)) {
188 return (array_key_exists('is_error', $result) &&
189 $result['is_error']
190 ) ? TRUE : FALSE;
191 }
192 return FALSE;
193}
194
aa1b1481 195/**
a828d7b8 196 * Get camel case version of entity name.
22242c87 197 *
4846df91 198 * @param string|null $entity
aa1b1481 199 *
4846df91 200 * @return string|null
aa1b1481 201 */
dc913073 202function _civicrm_api_get_camel_name($entity) {
4846df91 203 return is_string($entity) ? CRM_Utils_String::convertStringToCamel($entity) : NULL;
6a488035
TO
204}
205
11e09c59 206/**
22242c87
EM
207 * Swap out any $values vars.
208 *
209 * Ie. the value after $value is swapped for the parent $result
6a488035 210 * 'activity_type_id' => '$value.testfield',
e94b9071
CW
211 * 'tag_id' => '$value.api.tag.create.id',
212 * 'tag1_id' => '$value.api.entity.create.0.id'
d424ffde 213 *
e94b9071
CW
214 * @param array $params
215 * @param array $parentResult
216 * @param string $separator
6a488035 217 */
845d6d75 218function _civicrm_api_replace_variables(&$params, &$parentResult, $separator = '.') {
10befc1f 219 foreach ($params as $field => &$value) {
62780af8
JV
220 if (substr($field, 0, 4) == 'api.') {
221 // CRM-21246 - Leave nested calls alone.
222 continue;
223 }
6a488035 224 if (is_string($value) && substr($value, 0, 6) == '$value') {
10befc1f
CW
225 $value = _civicrm_api_replace_variable($value, $parentResult, $separator);
226 }
227 // Handle the operator syntax: array('OP' => $val)
228 elseif (is_array($value) && is_string(reset($value)) && substr(reset($value), 0, 6) == '$value') {
229 $key = key($value);
230 $value[$key] = _civicrm_api_replace_variable($value[$key], $parentResult, $separator);
640aec1d
CW
231 // A null value with an operator will cause an error, so remove it.
232 if ($value[$key] === NULL) {
233 $value = '';
234 }
10befc1f
CW
235 }
236 }
237}
6a488035 238
10befc1f
CW
239/**
240 * Swap out a $value.foo variable with the value from parent api results.
241 *
242 * Called by _civicrm_api_replace_variables to do the substitution.
243 *
244 * @param string $value
245 * @param array $parentResult
246 * @param string $separator
247 * @return mixed|null
248 */
249function _civicrm_api_replace_variable($value, $parentResult, $separator) {
250 $valueSubstitute = substr($value, 7);
6a488035 251
10befc1f
CW
252 if (!empty($parentResult[$valueSubstitute])) {
253 return $parentResult[$valueSubstitute];
254 }
255 else {
256 $stringParts = explode($separator, $value);
257 unset($stringParts[0]);
258 // CRM-16168 If we have failed to swap it out we should unset it rather than leave the placeholder.
259 $value = NULL;
6a488035 260
10befc1f 261 $fieldname = array_shift($stringParts);
6a488035 262
10befc1f
CW
263 //when our string is an array we will treat it as an array from that . onwards
264 $count = count($stringParts);
265 while ($count > 0) {
266 $fieldname .= "." . array_shift($stringParts);
267 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
268 $arrayLocation = $parentResult[$fieldname];
269 foreach ($stringParts as $key => $innerValue) {
270 $arrayLocation = CRM_Utils_Array::value($innerValue, $arrayLocation);
6a488035 271 }
10befc1f 272 $value = $arrayLocation;
6a488035 273 }
10befc1f 274 $count = count($stringParts);
6a488035
TO
275 }
276 }
10befc1f 277 return $value;
6a488035
TO
278}
279
11e09c59 280/**
dc64d047 281 * Convert possibly camel name to underscore separated entity name.
6a488035 282 *
cf470720 283 * @param string $entity
7cdbcb16
TO
284 * Entity name in various formats e.g. Contribution, contribution,
285 * OptionValue, option_value, UFJoin, uf_join.
dc64d047 286 *
a6c01b45 287 * @return string
7cdbcb16 288 * Entity name in underscore separated format.
6a488035
TO
289 */
290function _civicrm_api_get_entity_name_from_camel($entity) {
1644b908 291 if (!$entity || $entity === strtolower($entity)) {
6a488035
TO
292 return $entity;
293 }
a861c4f5
SL
294 elseif ($entity == 'PCP') {
295 return 'pcp';
296 }
6a488035
TO
297 else {
298 $entity = ltrim(strtolower(str_replace('U_F',
299 'uf',
300 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
301 preg_replace('/(?=[A-Z])/', '_$0', $entity)
302 )), '_');
303 }
304 return $entity;
305}
11e09c59
TO
306
307/**
dc64d047
EM
308 * Having a DAO object find the entity name.
309 *
cf470720
TO
310 * @param object $bao
311 * DAO being passed in.
dc64d047 312 *
5d3523d9 313 * @return string
6a488035 314 */
9b873358 315function _civicrm_api_get_entity_name_from_dao($bao) {
6a488035 316 $daoName = str_replace("BAO", "DAO", get_class($bao));
4846df91 317 return CRM_Core_DAO_AllCoreTables::getBriefName($daoName);
6a488035 318}