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