Merge pull request #16499 from pradpnayak/caseAuditReport
[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 * - **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.
58 *
59 * @return \Civi\Api4\Generic\Result
60 * @throws \API_Exception
61 * @throws \Civi\API\Exception\NotImplementedException
62 */
63 function civicrm_api4(string $entity, string $action, array $params = [], $index = NULL) {
64 $apiCall = \Civi\Api4\Utils\ActionUtil::getAction($entity, $action);
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
69 if ($indexField && !empty($params['select']) && is_array($params['select']) && !\Civi\Api4\Utils\SelectUtil::isFieldSelected($indexField, $params['select'])) {
70 $params['select'][] = $indexField;
71 $removeIndexField = TRUE;
72 }
73 foreach ($params as $name => $param) {
74 $setter = 'set' . ucfirst($name);
75 $apiCall->$setter($param);
76 }
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
89 $result = $apiCall->execute();
90
91 // Index results by key
92 if ($indexField) {
93 $result->indexBy($indexField);
94 if ($removeIndexField) {
95 foreach ($result as $key => $value) {
96 unset($result[$key][$indexField]);
97 }
98 }
99 }
100 // Return result at index
101 elseif (CRM_Utils_Rule::integer($index)) {
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);
111 }
112 if (!empty($indexCol)) {
113 $result->exchangeArray($result->column($indexCol));
114 }
115 return $result;
116 }
117
118 /**
119 * Version 3 wrapper for civicrm_api.
120 *
121 * Throws exception.
122 *
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.
129 *
130 * @throws CiviCRM_API3_Exception
131 *
132 * @return array
133 */
134 function civicrm_api3(string $entity, string $action, array $params = []) {
135 $params['version'] = 3;
136 $result = \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
137 if (is_array($result) && !empty($result['is_error'])) {
138 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
139 }
140 return $result;
141 }
142
143 /**
144 * Call getfields from api wrapper.
145 *
146 * This function ensures that settings that
147 * could alter getfields output (e.g. action for all api & profile_id for
148 * profile api ) are consistently passed in.
149 *
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
153 *
154 * @todo other output modifiers include contact_type
155 *
156 * @param array $apiRequest
157 *
158 * @return array
159 * getfields output
160 */
161 function _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
165 if (!empty($apiRequest['params']['api_action'])) {
166 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
167 // unset($apiRequest['params']['api_action']);
168 }
169 return ['action' => ['api.aliases' => ['api_action']]];
170 }
171 $getFieldsParams = ['action' => $apiRequest['action']];
172 $entity = $apiRequest['entity'];
173 if ($entity == 'Profile' && array_key_exists('profile_id', $apiRequest['params'])) {
174 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
175 }
176 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
177 return $fields['values'];
178 }
179
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 *
186 * @param $result
187 *
188 * @return bool
189 * true if error, false otherwise
190 */
191 function 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
200 /**
201 * Get camel case version of entity name.
202 *
203 * @param string|null $entity
204 *
205 * @return string|null
206 */
207 function _civicrm_api_get_camel_name($entity) {
208 return is_string($entity) ? CRM_Utils_String::convertStringToCamel($entity) : NULL;
209 }
210
211 /**
212 * Swap out any $values vars.
213 *
214 * Ie. the value after $value is swapped for the parent $result
215 * 'activity_type_id' => '$value.testfield',
216 * 'tag_id' => '$value.api.tag.create.id',
217 * 'tag1_id' => '$value.api.entity.create.0.id'
218 *
219 * @param array $params
220 * @param array $parentResult
221 * @param string $separator
222 */
223 function _civicrm_api_replace_variables(&$params, &$parentResult, $separator = '.') {
224 foreach ($params as $field => &$value) {
225 if (substr($field, 0, 4) == 'api.') {
226 // CRM-21246 - Leave nested calls alone.
227 continue;
228 }
229 if (is_string($value) && substr($value, 0, 6) == '$value') {
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);
236 // A null value with an operator will cause an error, so remove it.
237 if ($value[$key] === NULL) {
238 $value = '';
239 }
240 }
241 }
242 }
243
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 */
254 function _civicrm_api_replace_variable($value, $parentResult, $separator) {
255 $valueSubstitute = substr($value, 7);
256
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;
265
266 $fieldname = array_shift($stringParts);
267
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);
276 }
277 $value = $arrayLocation;
278 }
279 $count = count($stringParts);
280 }
281 }
282 return $value;
283 }
284
285 /**
286 * Convert possibly camel name to underscore separated entity name.
287 *
288 * @param string $entity
289 * Entity name in various formats e.g. Contribution, contribution,
290 * OptionValue, option_value, UFJoin, uf_join.
291 *
292 * @return string
293 * Entity name in underscore separated format.
294 */
295 function _civicrm_api_get_entity_name_from_camel($entity) {
296 if (!$entity || $entity === strtolower($entity)) {
297 return $entity;
298 }
299 elseif ($entity == 'PCP') {
300 return 'pcp';
301 }
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 }
311
312 /**
313 * Having a DAO object find the entity name.
314 *
315 * @param object $bao
316 * DAO being passed in.
317 *
318 * @return string
319 */
320 function _civicrm_api_get_entity_name_from_dao($bao) {
321 $daoName = str_replace("BAO", "DAO", get_class($bao));
322 return CRM_Core_DAO_AllCoreTables::getBriefName($daoName);
323 }