d0aa4653e9a7416ae2cf072ced4c2c92db69f6b4
[civicrm-core.git] / api / api.php
1 <?php
2
3 /**
4 * File for the CiviCRM APIv3 API wrapper
5 *
6 * @package CiviCRM_APIv3
7 * @subpackage API
8 *
9 * @copyright CiviCRM LLC (c) 2004-2014
10 * @version $Id: api.php 30486 2010-11-02 16:12:09Z shot $
11 */
12
13 /**
14 * @param string $entity
15 * type of entities to deal with
16 * @param string $action
17 * create, get, delete or some special action name.
18 * @param array $params
19 * array to be passed to function
20 * @param null $extra
21 *
22 * @return array|int
23 */
24 function civicrm_api($entity, $action, $params, $extra = NULL) {
25 return \Civi\Core\Container::singleton()->get('civi_api_kernel')->run($entity, $action, $params, $extra);
26 }
27
28 /**
29 * Look up the implementation for a given API request
30 *
31 * @param $apiRequest array with keys:
32 * - entity: string, required
33 * - action: string, required
34 * - params: array
35 * - version: scalar, required
36 *
37 * @return array with keys
38 * - function: callback (mixed)
39 * - is_generic: boolean
40 */
41 function _civicrm_api_resolve($apiRequest) {
42 static $cache;
43 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
44 if (isset($cache[$cachekey])) {
45 return $cache[$cachekey];
46 }
47
48 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
49 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
50
51 // Determine if there is an entity-specific implementation of the action
52 $stdFunction = civicrm_api_get_function_name($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
53 if (function_exists($stdFunction)) {
54 // someone already loaded the appropriate file
55 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
56 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
57 return $cache[$cachekey];
58 }
59
60 $stdFiles = array(
61 // By convention, the $camelName.php is more likely to contain the function, so test it first
62 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
63 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
64 );
65 foreach ($stdFiles as $stdFile) {
66 if (CRM_Utils_File::isIncludable($stdFile)) {
67 require_once $stdFile;
68 if (function_exists($stdFunction)) {
69 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
70 return $cache[$cachekey];
71 }
72 }
73 }
74
75 // Determine if there is a generic implementation of the action
76 require_once 'api/v3/Generic.php';
77 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
78 $genericFunction = civicrm_api_get_function_name('generic', $apiRequest['action'], $apiRequest['version']);
79 $genericFiles = array(
80 // By convention, the Generic.php is more likely to contain the function, so test it first
81 'api/v' . $apiRequest['version'] . '/Generic.php',
82 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
83 );
84 foreach ($genericFiles as $genericFile) {
85 if (CRM_Utils_File::isIncludable($genericFile)) {
86 require_once $genericFile;
87 if (function_exists($genericFunction)) {
88 $cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
89 return $cache[$cachekey];
90 }
91 }
92 }
93
94 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
95 return $cache[$cachekey];
96 }
97
98 /**
99 * Version 3 wrapper for civicrm_api. Throws exception
100 *
101 * @param string $entity type of entities to deal with
102 * @param string $action create, get, delete or some special action name.
103 * @param array $params array to be passed to function
104 *
105 * @throws CiviCRM_API3_Exception
106 * @return array
107 */
108 function civicrm_api3($entity, $action, $params = array()) {
109 $params['version'] = 3;
110 $result = civicrm_api($entity, $action, $params);
111 if(is_array($result) && !empty($result['is_error'])){
112 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
113 }
114 return $result;
115 }
116
117 /**
118 * Function to call getfields from api wrapper. This function ensures that settings that could alter
119 * getfields output (e.g. action for all api & profile_id for profile api ) are consistently passed in.
120 *
121 * We check whether the api call is 'getfields' because if getfields is being called we return an empty array
122 * as no alias swapping, validation or default filling is done on getfields & we want to avoid a loop
123 *
124 * @todo other output modifiers include contact_type
125 *
126 * @param array $apiRequest
127 * @return getfields output
128 */
129 function _civicrm_api3_api_getfields(&$apiRequest) {
130 if (strtolower($apiRequest['action'] == 'getfields')) {
131 // the main param getfields takes is 'action' - however this param is not compatible with REST
132 // so we accept 'api_action' as an alias of action on getfields
133 if (!empty($apiRequest['params']['api_action'])) {
134 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
135 // unset($apiRequest['params']['api_action']);
136 }
137 return array('action' => array('api.aliases' => array('api_action')));
138 }
139 $getFieldsParams = array('action' => $apiRequest['action']);
140 $entity = $apiRequest['entity'];
141 if($entity == 'profile' && array_key_exists('profile_id', $apiRequest['params'])) {
142 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
143 }
144 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
145 return $fields['values'];
146 }
147
148 /**
149 * Load/require all files related to an entity.
150 *
151 * This should not normally be called because it's does a file-system scan; it's
152 * only appropriate when introspection is really required (eg for "getActions").
153 *
154 * @param string $entity
155 * @param int $version
156 *
157 * @return void
158 */
159 function _civicrm_api_loadEntity($entity, $version = 3) {
160 /*
161 $apiRequest = array();
162 $apiRequest['entity'] = $entity;
163 $apiRequest['action'] = 'pretty sure it will never exist. Trick to [try to] force resolve to scan everywhere';
164 $apiRequest['version'] = $version;
165 // look up function, file, is_generic
166 $apiRequest = _civicrm_api_resolve($apiRequest);
167 */
168
169 $camelName = _civicrm_api_get_camel_name($entity, $version);
170
171 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
172 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
173 if (CRM_Utils_File::isIncludable($stdFile)) {
174 require_once $stdFile;
175 }
176
177 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
178 $loaded_files = array(); // array($relativeFilePath => TRUE)
179 $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
180 foreach ($include_dirs as $include_dir) {
181 $action_dir = implode(DIRECTORY_SEPARATOR, array($include_dir, 'api', "v${version}", $camelName));
182 if (! is_dir($action_dir)) {
183 continue;
184 }
185
186 $iterator = new DirectoryIterator($action_dir);
187 foreach ($iterator as $fileinfo) {
188 $file = $fileinfo->getFilename();
189 if (array_key_exists($file, $loaded_files)) {
190 continue; // action provided by an earlier item on include_path
191 }
192
193 $parts = explode(".", $file);
194 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file) ) {
195 require_once $action_dir . DIRECTORY_SEPARATOR . $file;
196 $loaded_files[$file] = TRUE;
197 }
198 }
199 }
200 }
201
202 /**
203 *
204 * @deprecated
205 */
206 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
207
208 if (empty($version)) {
209 $version = civicrm_get_api_version();
210 }
211
212 $entity = _civicrm_api_get_entity_name_from_camel($entity);
213 return 'civicrm_api3' . '_' . $entity . '_' . $action;
214 }
215
216 /**
217 * We must be sure that every request uses only one version of the API.
218 *
219 * @param $desired_version : array or integer
220 * One chance to set the version number.
221 * After that, this version number will be used for the remaining request.
222 * This can either be a number, or an array(.., 'version' => $version, ..).
223 * This allows to directly pass the $params array.
224 * @return int
225 */
226 function civicrm_get_api_version($desired_version = NULL) {
227
228 if (is_array($desired_version)) {
229 // someone gave the full $params array.
230 $params = $desired_version;
231 $desired_version = empty($params['version']) ? NULL : (int) $params['version'];
232 }
233 if (isset($desired_version) && is_integer($desired_version)) {
234 $_version = $desired_version;
235 }
236 else {
237 // we will set the default to version 3 as soon as we find that it works.
238 $_version = 3;
239 }
240 return $_version;
241 }
242
243 /**
244 * Check if the result is an error. Note that this function has been retained from
245 * api v2 for convenience but the result is more standardised in v3 and param
246 * 'format.is_success' => 1
247 * will result in a boolean success /fail being returned if that is what you need.
248 *
249 * @param $result
250 *
251 * @internal param array $params (reference ) input parameters
252 *
253 * @return boolean true if error, false otherwise
254 * @static void
255 * @access public
256 */
257 function civicrm_error($result) {
258 if (is_array($result)) {
259 return (array_key_exists('is_error', $result) &&
260 $result['is_error']
261 ) ? TRUE : FALSE;
262 }
263 return FALSE;
264 }
265
266 function _civicrm_api_get_camel_name($entity, $version = NULL) {
267 if (empty($version)) {
268 $version = civicrm_get_api_version();
269 }
270
271 $fragments = explode('_', $entity);
272 foreach ($fragments as & $fragment) {
273 $fragment = ucfirst($fragment);
274 }
275 // Special case: UFGroup, UFJoin, UFMatch, UFField
276 if ($fragments[0] === 'Uf') {
277 $fragments[0] = 'UF';
278 }
279 return implode('', $fragments);
280 }
281
282 /**
283 * Call any nested api calls
284 */
285 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
286 $entity = _civicrm_api_get_entity_name_from_camel($entity);
287
288 //we don't need to worry about nested api in the getfields/getoptions actions, so just return immediately
289 if (in_array(strtolower($action), array('getfields', 'getoptions'))) {
290 return;
291 }
292
293 if(strtolower($action) == 'getsingle'){
294 // I don't understand the protocol here, but we don't want
295 // $result to be a recursive array
296 // $result['values'][0] = $result;
297 $oldResult = $result;
298 $result = array('values' => array(0 => $oldResult));
299 }
300 foreach ($params as $field => $newparams) {
301 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
302
303 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
304 if ($newparams === 1) {
305 $newparams = array('version' => $version);
306 }
307 // can be api_ or api.
308 $separator = $field[3];
309 if (!($separator == '.' || $separator == '_')) {
310 continue;
311 }
312 $subAPI = explode($separator, $field);
313
314 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
315 $subParams = array(
316 'debug' => CRM_Utils_Array::value('debug', $params),
317 );
318 $subEntity = $subAPI[1];
319
320 foreach ($result['values'] as $idIndex => $parentAPIValues) {
321
322 if (strtolower($subEntity) != 'contact') {
323 //contact spits the dummy at activity_id so what else won't it like?
324 //set entity_id & entity table based on the parent's id & entity. e.g for something like
325 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
326 //the parent call.
327 //in this case 'contact_id' will also be set to the parent's id
328 $subParams["entity_id"] = $parentAPIValues['id'];
329 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
330 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
331 }
332 if (strtolower($entity) != 'contact' && CRM_Utils_Array::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
333 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
334 //don't do this for contact as it does some wierd things like returning primary email &
335 //thus limiting the ability to chain email
336 //TODO - this might need the camel treatment
337 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
338 }
339
340 if (CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
341 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
342 }
343 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
344 if (strtolower($entity) == strtolower($subEntity)) {
345 $subParams['id'] = $result['values'][$idIndex]['id'];
346 }
347
348
349 $subParams['version'] = $version;
350 if(!empty($params['check_permissions'])){
351 $subParams['check_permissions'] = $params['check_permissions'];
352 }
353 $subParams['sequential'] = 1;
354 $subParams['api.has_parent'] = 1;
355 if (array_key_exists(0, $newparams)) {
356 $genericParams = $subParams;
357 // it is a numerically indexed array - ie. multiple creates
358 foreach ($newparams as $entityparams) {
359 $subParams = array_merge($genericParams, $entityparams);
360 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
361 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
362 if ($result['is_error'] === 1) {
363 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
364 }
365 }
366 }
367 else {
368
369 $subParams = array_merge($subParams, $newparams);
370 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
371 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
372 if (!empty($result['is_error'])) {
373 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
374 }
375 }
376 }
377 }
378 }
379 if(strtolower($action) == 'getsingle'){
380 $result = $result['values'][0];
381 }
382 }
383
384 /**
385 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
386 * 'activity_type_id' => '$value.testfield',
387 'tag_id' => '$value.api.tag.create.id',
388 'tag1_id' => '$value.api.entity.create.0.id'
389 */
390 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
391
392
393 foreach ($params as $field => $value) {
394
395 if (is_string($value) && substr($value, 0, 6) == '$value') {
396 $valuesubstitute = substr($value, 7);
397
398 if (!empty($parentResult[$valuesubstitute])) {
399 $params[$field] = $parentResult[$valuesubstitute];
400 }
401 else {
402
403 $stringParts = explode($separator, $value);
404 unset($stringParts[0]);
405
406 $fieldname = array_shift($stringParts);
407
408 //when our string is an array we will treat it as an array from that . onwards
409 $count = count($stringParts);
410 while ($count > 0) {
411 $fieldname .= "." . array_shift($stringParts);
412 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
413 $arrayLocation = $parentResult[$fieldname];
414 foreach ($stringParts as $key => $value) {
415 $arrayLocation = CRM_Utils_Array::value($value, $arrayLocation);
416 }
417 $params[$field] = $arrayLocation;
418 }
419 $count = count($stringParts);
420 }
421 }
422 }
423 }
424 }
425
426 /**
427 * Convert possibly camel name to underscore separated entity name
428 *
429 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
430 * @return string $entity entity name in underscore separated format
431 *
432 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
433 */
434 function _civicrm_api_get_entity_name_from_camel($entity) {
435 if ($entity == strtolower($entity)) {
436 return $entity;
437 }
438 else {
439 $entity = ltrim(strtolower(str_replace('U_F',
440 'uf',
441 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
442 preg_replace('/(?=[A-Z])/', '_$0', $entity)
443 )), '_');
444 }
445 return $entity;
446 }
447
448 /**
449 * Having a DAO object find the entity name
450 * @param object $bao DAO being passed in
451 * @return string
452 */
453 function _civicrm_api_get_entity_name_from_dao($bao){
454 $daoName = str_replace("BAO", "DAO", get_class($bao));
455 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables::getBriefName($daoName));
456 }
457
458 /**
459 * Sets the tsLocale and dbLocale for multi-lingual sites.
460 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
461 * to avoid regressions from refactoring.
462 */
463 function _civicrm_api_set_locale($lcMessagesRequest) {
464 // We must validate whether the locale is valid, otherwise setting a bad
465 // dbLocale could probably lead to sql-injection.
466 $domain = new CRM_Core_DAO_Domain();
467 $domain->id = CRM_Core_Config::domainID();
468 $domain->find(TRUE);
469
470 if ($domain->config_backend) {
471 $defaults = unserialize($domain->config_backend);
472
473 // are we in a multi-language setup?
474 $multiLang = $domain->locales ? TRUE : FALSE;
475 $lcMessages = NULL;
476
477 // on multi-lang sites based on request and civicrm_uf_match
478 if ($multiLang) {
479 $languageLimit = array();
480 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
481 $languageLimit = $defaults['languageLimit'];
482 }
483
484 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
485 $lcMessages = $lcMessagesRequest;
486 }
487 else {
488 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
489 }
490 }
491
492 global $dbLocale;
493
494 // set suffix for table names - use views if more than one language
495 if ($lcMessages) {
496 $dbLocale = $multiLang && $lcMessages ? "_{$lcMessages}" : '';
497
498 // FIXME: an ugly hack to fix CRM-4041
499 global $tsLocale;
500 $tsLocale = $lcMessages;
501 }
502 }
503 }