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