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