4 * @file CiviCRM APIv3 API wrapper.
6 * @package CiviCRM_APIv3
10 * CiviCRM API wrapper function.
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
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);
27 * CiviCRM API version 4.
29 * This API (Application Programming Interface) is used to access and manage data in CiviCRM.
31 * APIv4 is the latest stable version.
33 * @see https://docs.civicrm.org/dev/en/latest/api/v4/usage/
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');
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');
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.
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:
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.
56 * @return \Civi\Api4\Generic\Result
57 * @throws \API_Exception
58 * @throws \Civi\API\Exception\NotImplementedException
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;
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;
70 foreach ($params as $name => $param) {
71 $setter = 'set' . ucfirst($name);
72 $apiCall->$setter($param);
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);
86 $result = $apiCall->execute();
88 // Index results by key
90 $result->indexBy($indexField);
91 if ($removeIndexField) {
92 foreach ($result as $key => $value) {
93 unset($result[$key][$indexField]);
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");
103 // Attempt to return a Result object if item is array, otherwise just return the item
104 if (!is_array($item)) {
107 $result->exchangeArray($item);
109 if (!empty($indexCol)) {
110 $result->exchangeArray($result->column($indexCol));
116 * Version 3 wrapper for civicrm_api.
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.
127 * @throws CiviCRM_API3_Exception
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);
141 * Call getfields from api wrapper.
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.
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
151 * @todo other output modifiers include contact_type
153 * @param array $apiRequest
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']);
166 return ['action' => ['api.aliases' => ['api_action']]];
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'];
173 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
174 return $fields['values'];
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.
186 * true if error, false otherwise
188 function civicrm_error($result) {
189 if (is_array($result)) {
190 return (array_key_exists('is_error', $result) &&
198 * Get camel case version of entity name.
200 * @param string|null $entity
202 * @return string|null
204 function _civicrm_api_get_camel_name($entity) {
205 return is_string($entity) ? CRM_Utils_String
::convertStringToCamel($entity) : NULL;
209 * Swap out any $values vars.
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'
216 * @param array $params
217 * @param array $parentResult
218 * @param string $separator
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.
226 if (is_string($value) && substr($value, 0, 6) == '$value') {
227 $value = _civicrm_api_replace_variable($value, $parentResult, $separator);
229 // Handle the operator syntax: array('OP' => $val)
230 elseif (is_array($value) && is_string(reset($value)) && substr(reset($value), 0, 6) == '$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) {
242 * Swap out a $value.foo variable with the value from parent api results.
244 * Called by _civicrm_api_replace_variables to do the substitution.
246 * @param string $value
247 * @param array $parentResult
248 * @param string $separator
251 function _civicrm_api_replace_variable($value, $parentResult, $separator) {
252 $valueSubstitute = substr($value, 7);
254 if (!empty($parentResult[$valueSubstitute])) {
255 return $parentResult[$valueSubstitute];
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.
263 $fieldname = array_shift($stringParts);
265 //when our string is an array we will treat it as an array from that . onwards
266 $count = count($stringParts);
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);
274 $value = $arrayLocation;
276 $count = count($stringParts);
283 * Convert possibly camel name to underscore separated entity name.
285 * @param string $entity
286 * Entity name in various formats e.g. Contribution, contribution,
287 * OptionValue, option_value, UFJoin, uf_join.
290 * Entity name in underscore separated format.
292 function _civicrm_api_get_entity_name_from_camel($entity) {
293 if (!$entity ||
$entity === strtolower($entity)) {
296 elseif ($entity == 'PCP') {
300 $entity = ltrim(strtolower(str_replace('U_F',
302 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
303 preg_replace('/(?=[A-Z])/', '_$0', $entity)
310 * Having a DAO object find the entity name.
313 * DAO being passed in.
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);