224846279f99f02f2c089255cdbf9966b95b508e
[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 = NULL, 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 *
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.
55 *
56 * @return \Civi\Api4\Generic\Result
57 * @throws \API_Exception
58 * @throws \Civi\API\Exception\NotImplementedException
59 */
60 function civicrm_api4(string $entity, string $action, array $params = [], $index = NULL) {
61 $apiCall = \Civi\Api4\Utils\ActionUtil::getAction($entity, $action);
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
66 if ($indexField && !empty($params['select']) && is_array($params['select']) && !\Civi\Api4\Utils\SelectUtil::isFieldSelected($indexField, $params['select'])) {
67 $params['select'][] = $indexField;
68 $removeIndexField = TRUE;
69 }
70 foreach ($params as $name => $param) {
71 $setter = 'set' . ucfirst($name);
72 $apiCall->$setter($param);
73 }
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
86 $result = $apiCall->execute();
87
88 // Index results by key
89 if ($indexField) {
90 $result->indexBy($indexField);
91 if ($removeIndexField) {
92 foreach ($result as $key => $value) {
93 unset($result[$key][$indexField]);
94 }
95 }
96 }
97 // Return result at index
98 elseif (CRM_Utils_Rule::integer($index)) {
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);
108 }
109 if (!empty($indexCol)) {
110 $result->exchangeArray($result->column($indexCol));
111 }
112 return $result;
113 }
114
115 /**
116 * Version 3 wrapper for civicrm_api.
117 *
118 * Throws exception.
119 *
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.
126 *
127 * @throws CiviCRM_API3_Exception
128 *
129 * @return array
130 */
131 function civicrm_api3(string $entity, string $action, array $params = []) {
132 $params['version'] = 3;
133 $result = \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
134 if (is_array($result) && !empty($result['is_error'])) {
135 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
136 }
137 return $result;
138 }
139
140 /**
141 * Call getfields from api wrapper.
142 *
143 * This function ensures that settings that
144 * could alter getfields output (e.g. action for all api & profile_id for
145 * profile api ) are consistently passed in.
146 *
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
150 *
151 * @todo other output modifiers include contact_type
152 *
153 * @param array $apiRequest
154 *
155 * @return array
156 * getfields output
157 */
158 function _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
162 if (!empty($apiRequest['params']['api_action'])) {
163 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
164 // unset($apiRequest['params']['api_action']);
165 }
166 return ['action' => ['api.aliases' => ['api_action']]];
167 }
168 $getFieldsParams = ['action' => $apiRequest['action']];
169 $entity = $apiRequest['entity'];
170 if ($entity == 'Profile' && array_key_exists('profile_id', $apiRequest['params'])) {
171 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
172 }
173 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
174 return $fields['values'];
175 }
176
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 *
183 * @param $result
184 *
185 * @return bool
186 * true if error, false otherwise
187 */
188 function 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
197 /**
198 * Get camel case version of entity name.
199 *
200 * @param string|null $entity
201 *
202 * @return string|null
203 */
204 function _civicrm_api_get_camel_name($entity) {
205 return is_string($entity) ? CRM_Utils_String::convertStringToCamel($entity) : NULL;
206 }
207
208 /**
209 * Swap out any $values vars.
210 *
211 * Ie. the value after $value is swapped for the parent $result
212 * 'activity_type_id' => '$value.testfield',
213 * 'tag_id' => '$value.api.tag.create.id',
214 * 'tag1_id' => '$value.api.entity.create.0.id'
215 *
216 * @param array $params
217 * @param array $parentResult
218 * @param string $separator
219 */
220 function _civicrm_api_replace_variables(&$params, &$parentResult, $separator = '.') {
221 foreach ($params as $field => &$value) {
222 if (substr($field, 0, 4) == 'api.') {
223 // CRM-21246 - Leave nested calls alone.
224 continue;
225 }
226 if (is_string($value) && substr($value, 0, 6) == '$value') {
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);
233 // A null value with an operator will cause an error, so remove it.
234 if ($value[$key] === NULL) {
235 $value = '';
236 }
237 }
238 }
239 }
240
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 */
251 function _civicrm_api_replace_variable($value, $parentResult, $separator) {
252 $valueSubstitute = substr($value, 7);
253
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;
262
263 $fieldname = array_shift($stringParts);
264
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);
273 }
274 $value = $arrayLocation;
275 }
276 $count = count($stringParts);
277 }
278 }
279 return $value;
280 }
281
282 /**
283 * Convert possibly camel name to underscore separated entity name.
284 *
285 * @param string $entity
286 * Entity name in various formats e.g. Contribution, contribution,
287 * OptionValue, option_value, UFJoin, uf_join.
288 *
289 * @return string
290 * Entity name in underscore separated format.
291 */
292 function _civicrm_api_get_entity_name_from_camel($entity) {
293 if (!$entity || $entity === strtolower($entity)) {
294 return $entity;
295 }
296 elseif ($entity == 'PCP') {
297 return 'pcp';
298 }
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 }
308
309 /**
310 * Having a DAO object find the entity name.
311 *
312 * @param object $bao
313 * DAO being passed in.
314 *
315 * @return string
316 */
317 function _civicrm_api_get_entity_name_from_dao($bao) {
318 $daoName = str_replace("BAO", "DAO", get_class($bao));
319 return CRM_Core_DAO_AllCoreTables::getBriefName($daoName);
320 }