api4 - Add civicrm_api4() and CRM.api4() entry-points
[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($entity, $action, $params, $extra = NULL) {
23 return \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params, $extra);
24 }
25
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 */
40 function 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
68 /**
69 * Version 3 wrapper for civicrm_api.
70 *
71 * Throws exception.
72 *
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.
79 *
80 * @throws CiviCRM_API3_Exception
81 *
82 * @return array
83 */
84 function civicrm_api3($entity, $action, $params = []) {
85 $params['version'] = 3;
86 $result = \Civi::service('civi_api_kernel')->runSafe($entity, $action, $params);
87 if (is_array($result) && !empty($result['is_error'])) {
88 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
89 }
90 return $result;
91 }
92
93 /**
94 * Call getfields from api wrapper.
95 *
96 * This function ensures that settings that
97 * could alter getfields output (e.g. action for all api & profile_id for
98 * profile api ) are consistently passed in.
99 *
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
103 *
104 * @todo other output modifiers include contact_type
105 *
106 * @param array $apiRequest
107 *
108 * @return array
109 * getfields output
110 */
111 function _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
115 if (!empty($apiRequest['params']['api_action'])) {
116 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
117 // unset($apiRequest['params']['api_action']);
118 }
119 return ['action' => ['api.aliases' => ['api_action']]];
120 }
121 $getFieldsParams = ['action' => $apiRequest['action']];
122 $entity = $apiRequest['entity'];
123 if ($entity == 'Profile' && array_key_exists('profile_id', $apiRequest['params'])) {
124 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
125 }
126 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
127 return $fields['values'];
128 }
129
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 *
136 * @param $result
137 *
138 * @return bool
139 * true if error, false otherwise
140 */
141 function 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
150 /**
151 * Get camel case version of entity name.
152 *
153 * @param string|null $entity
154 *
155 * @return string|null
156 */
157 function _civicrm_api_get_camel_name($entity) {
158 return is_string($entity) ? CRM_Utils_String::convertStringToCamel($entity) : NULL;
159 }
160
161 /**
162 * Swap out any $values vars.
163 *
164 * Ie. the value after $value is swapped for the parent $result
165 * 'activity_type_id' => '$value.testfield',
166 * 'tag_id' => '$value.api.tag.create.id',
167 * 'tag1_id' => '$value.api.entity.create.0.id'
168 *
169 * @param array $params
170 * @param array $parentResult
171 * @param string $separator
172 */
173 function _civicrm_api_replace_variables(&$params, &$parentResult, $separator = '.') {
174 foreach ($params as $field => &$value) {
175 if (substr($field, 0, 4) == 'api.') {
176 // CRM-21246 - Leave nested calls alone.
177 continue;
178 }
179 if (is_string($value) && substr($value, 0, 6) == '$value') {
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);
186 // A null value with an operator will cause an error, so remove it.
187 if ($value[$key] === NULL) {
188 $value = '';
189 }
190 }
191 }
192 }
193
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 */
204 function _civicrm_api_replace_variable($value, $parentResult, $separator) {
205 $valueSubstitute = substr($value, 7);
206
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;
215
216 $fieldname = array_shift($stringParts);
217
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);
226 }
227 $value = $arrayLocation;
228 }
229 $count = count($stringParts);
230 }
231 }
232 return $value;
233 }
234
235 /**
236 * Convert possibly camel name to underscore separated entity name.
237 *
238 * @param string $entity
239 * Entity name in various formats e.g. Contribution, contribution,
240 * OptionValue, option_value, UFJoin, uf_join.
241 *
242 * @return string
243 * Entity name in underscore separated format.
244 */
245 function _civicrm_api_get_entity_name_from_camel($entity) {
246 if (!$entity || $entity === strtolower($entity)) {
247 return $entity;
248 }
249 elseif ($entity == 'PCP') {
250 return 'pcp';
251 }
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 }
261
262 /**
263 * Having a DAO object find the entity name.
264 *
265 * @param object $bao
266 * DAO being passed in.
267 *
268 * @return string
269 */
270 function _civicrm_api_get_entity_name_from_dao($bao) {
271 $daoName = str_replace("BAO", "DAO", get_class($bao));
272 return CRM_Core_DAO_AllCoreTables::getBriefName($daoName);
273 }