4 * File for the CiviCRM APIv3 API wrapper
6 * @package CiviCRM_APIv3
9 * @copyright CiviCRM LLC (c) 2004-2013
10 * @version $Id: api.php 30486 2010-11-02 16:12:09Z shot $
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
21 function civicrm_api($entity, $action, $params, $extra = NULL) {
22 $apiRequest = array();
23 $apiRequest['entity'] = CRM_Utils_String
::munge($entity);
24 $apiRequest['action'] = CRM_Utils_String
::munge($action);
25 $apiRequest['version'] = civicrm_get_api_version($params);
26 $apiRequest['params'] = $params;
27 $apiRequest['extra'] = $extra;
30 CRM_Utils_API_HTMLInputCoder
::singleton(),
31 CRM_Utils_API_NullOutputCoder
::singleton(),
32 CRM_Utils_API_ReloadOption
::singleton(),
34 CRM_Utils_Hook
::apiWrappers($apiWrappers,$apiRequest);
37 require_once ('api/v3/utils.php');
38 require_once 'api/Exception.php';
39 if (!is_array($params)) {
40 throw new API_Exception('Input variable `params` is not an array', 2000);
42 _civicrm_api3_initialize();
43 $errorScope = CRM_Core_TemporaryErrorScope
::useException();
44 // look up function, file, is_generic
45 $apiRequest +
= _civicrm_api_resolve($apiRequest);
46 if (strtolower($action) == 'create' ||
strtolower($action) == 'delete') {
47 $apiRequest['is_transactional'] = 1;
48 $transaction = new CRM_Core_Transaction();
51 // support multi-lingual requests
52 if ($language = CRM_Utils_Array
::value('option.language', $params)) {
53 _civicrm_api_set_locale($language);
56 _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
58 // we do this before we
59 _civicrm_api3_swap_out_aliases($apiRequest);
60 if (strtolower($action) != 'getfields') {
61 if (!CRM_Utils_Array
::value('id', $apiRequest['params'])) {
62 $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest), $apiRequest['params']);
64 //if 'id' is set then only 'version' will be checked but should still be checked for consistency
65 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest));
68 // For input filtering, process $apiWrappers in forward order
69 foreach ($apiWrappers as $apiWrapper) {
70 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
73 $function = $apiRequest['function'];
74 if ($apiRequest['function'] && $apiRequest['is_generic']) {
75 // Unlike normal API implementations, generic implementations require explicit
76 // knowledge of the entity and action (as well as $params). Bundle up these bits
77 // into a convenient data structure.
78 $result = $function($apiRequest);
80 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
81 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
83 $result = isset($extra) ?
$function($apiRequest['params'], $extra) : $function($apiRequest['params']);
86 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . "," . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
89 // For output filtering, process $apiWrappers in reverse order
90 foreach (array_reverse($apiWrappers) as $apiWrapper) {
91 $result = $apiWrapper->toApiOutput($apiRequest, $result);
94 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
95 if ($result['is_error'] === 0) {
102 if (CRM_Utils_Array
::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
103 return $result['id'];
105 if (CRM_Utils_Array
::value('is_error', $result, 0) == 0) {
106 _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
108 if (function_exists('xdebug_time_index')
109 && CRM_Utils_Array
::value('debug', $apiRequest['params'])
110 // result would not be an array for getvalue
113 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
114 $result['xdebug']['memory'] = xdebug_memory_usage();
115 $result['xdebug']['timeIndex'] = xdebug_time_index();
120 catch(PEAR_Exception
$e) {
121 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
124 $error = $e->getCause();
125 if ($error instanceof DB_Error
) {
126 $data["error_code"] = DB
::errorMessage($error->getCode());
127 $data["sql"] = $error->getDebugInfo();
129 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
130 if(method_exists($e, 'getUserInfo')) {
131 $data['debug_info'] = $error->getUserInfo();
133 if(method_exists($e, 'getExtraData')) {
134 $data['debug_info'] = $data +
$error->getExtraData();
136 $data['trace'] = $e->getTraceAsString();
139 $data['tip'] = "add debug=1 to your API call to have more info about the error";
141 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
142 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
143 $transaction->rollback();
147 catch (API_Exception
$e){
148 if(!isset($apiRequest)){
149 $apiRequest = array();
151 if (CRM_Utils_Array
::value('format.is_success', CRM_Utils_Array
::value('params',$apiRequest)) == 1) {
154 $data = $e->getExtraParams();
155 $data['entity'] = CRM_Utils_Array
::value('entity', $apiRequest);
156 $data['action'] = CRM_Utils_Array
::value('action', $apiRequest);
157 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
158 if (CRM_Utils_Array
::value('debug', CRM_Utils_Array
::value('params',$apiRequest))
159 && empty($data['trace']) // prevent recursion
161 $err['trace'] = $e->getTraceAsString();
163 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
164 $transaction->rollback();
168 catch(Exception
$e) {
169 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
173 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
174 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
175 $err['trace'] = $e->getTraceAsString();
177 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
178 $transaction->rollback();
185 * Look up the implementation for a given API request
187 * @param $apiRequest array with keys:
188 * - entity: string, required
189 * - action: string, required
191 * - version: scalar, required
193 * @return array with keys
194 * - function: callback (mixed)
195 * - is_generic: boolean
197 function _civicrm_api_resolve($apiRequest) {
199 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
200 if (isset($cache[$cachekey])) {
201 return $cache[$cachekey];
204 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
205 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
207 // Determine if there is an entity-specific implementation of the action
208 $stdFunction = civicrm_api_get_function_name($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
209 if (function_exists($stdFunction)) {
210 // someone already loaded the appropriate file
211 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
212 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
213 return $cache[$cachekey];
217 // By convention, the $camelName.php is more likely to contain the function, so test it first
218 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
219 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
221 foreach ($stdFiles as $stdFile) {
222 if (CRM_Utils_File
::isIncludable($stdFile)) {
223 require_once $stdFile;
224 if (function_exists($stdFunction)) {
225 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
226 return $cache[$cachekey];
231 // Determine if there is a generic implementation of the action
232 require_once 'api/v3/Generic.php';
233 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
234 $genericFunction = civicrm_api_get_function_name('generic', $apiRequest['action'], $apiRequest['version']);
235 $genericFiles = array(
236 // By convention, the Generic.php is more likely to contain the function, so test it first
237 'api/v' . $apiRequest['version'] . '/Generic.php',
238 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
240 foreach ($genericFiles as $genericFile) {
241 if (CRM_Utils_File
::isIncludable($genericFile)) {
242 require_once $genericFile;
243 if (function_exists($genericFunction)) {
244 $cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
245 return $cache[$cachekey];
250 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
251 return $cache[$cachekey];
254 * Version 3 wrapper for civicrm_api. Throws exception
255 * @param string $entity type of entities to deal with
256 * @param string $action create, get, delete or some special action name.
257 * @param array $params array to be passed to function
262 function civicrm_api3($entity, $action, $params) {
263 $params['version'] = 3;
264 $result = civicrm_api($entity, $action, $params);
265 if(is_array($result) && !empty($result['is_error'])){
266 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
272 * Load/require all files related to an entity.
274 * This should not normally be called because it's does a file-system scan; it's
275 * only appropriate when introspection is really required (eg for "getActions").
277 * @param string $entity
280 function _civicrm_api_loadEntity($entity, $version = 3) {
282 $apiRequest = array();
283 $apiRequest['entity'] = $entity;
284 $apiRequest['action'] = 'pretty sure it will never exist. Trick to [try to] force resolve to scan everywhere';
285 $apiRequest['version'] = $version;
286 // look up function, file, is_generic
287 $apiRequest = _civicrm_api_resolve($apiRequest);
290 $camelName = _civicrm_api_get_camel_name($entity, $version);
292 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
293 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
294 if (CRM_Utils_File
::isIncludable($stdFile)) {
295 require_once $stdFile;
298 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
299 $loaded_files = array(); // array($relativeFilePath => TRUE)
300 $include_dirs = array_unique(explode(PATH_SEPARATOR
, get_include_path()));
301 foreach ($include_dirs as $include_dir) {
302 $action_dir = implode(DIRECTORY_SEPARATOR
, array($include_dir, 'api', "v${version}", $camelName));
303 if (! is_dir($action_dir)) {
307 $iterator = new DirectoryIterator($action_dir);
308 foreach ($iterator as $fileinfo) {
309 $file = $fileinfo->getFilename();
310 if (array_key_exists($file, $loaded_files)) {
311 continue; // action provided by an earlier item on include_path
314 $parts = explode(".", $file);
315 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file) ) {
316 require_once $action_dir . DIRECTORY_SEPARATOR
. $file;
317 $loaded_files[$file] = TRUE;
327 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
329 if (empty($version)) {
330 $version = civicrm_get_api_version();
333 $entity = _civicrm_api_get_entity_name_from_camel($entity);
334 return 'civicrm_api3' . '_' . $entity . '_' . $action;
338 * We must be sure that every request uses only one version of the API.
340 * @param $desired_version : array or integer
341 * One chance to set the version number.
342 * After that, this version number will be used for the remaining request.
343 * This can either be a number, or an array(.., 'version' => $version, ..).
344 * This allows to directly pass the $params array.
346 function civicrm_get_api_version($desired_version = NULL) {
348 if (is_array($desired_version)) {
349 // someone gave the full $params array.
350 $params = $desired_version;
351 $desired_version = empty($params['version']) ?
NULL : (int) $params['version'];
353 if (isset($desired_version) && is_integer($desired_version)) {
354 $_version = $desired_version;
357 // we will set the default to version 3 as soon as we find that it works.
364 * Check if the result is an error. Note that this function has been retained from
365 * api v2 for convenience but the result is more standardised in v3 and param
366 * 'format.is_success' => 1
367 * will result in a boolean success /fail being returned if that is what you need.
369 * @param array $params (reference ) input parameters
371 * @return boolean true if error, false otherwise
375 function civicrm_error($result) {
376 if (is_array($result)) {
377 return (array_key_exists('is_error', $result) &&
384 function _civicrm_api_get_camel_name($entity, $version = NULL) {
385 if (empty($version)) {
386 $version = civicrm_get_api_version();
389 $fragments = explode('_', $entity);
390 foreach ($fragments as & $fragment) {
391 $fragment = ucfirst($fragment);
393 // Special case: UFGroup, UFJoin, UFMatch, UFField
394 if ($fragments[0] === 'Uf') {
395 $fragments[0] = 'UF';
397 return implode('', $fragments);
401 * Call any nested api calls
403 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
404 $entity = _civicrm_api_get_entity_name_from_camel($entity);
405 if(strtolower($action) == 'getsingle'){
406 // I don't understand the protocol here, but we don't want
407 // $result to be a recursive array
408 // $result['values'][0] = $result;
409 $oldResult = $result;
410 $result = array('values' => array(0 => $oldResult));
412 foreach ($params as $field => $newparams) {
413 if ((is_array($newparams) ||
$newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
415 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
416 if ($newparams === 1) {
417 $newparams = array('version' => $version);
419 // can be api_ or api.
420 $separator = $field[3];
421 if (!($separator == '.' ||
$separator == '_')) {
424 $subAPI = explode($separator, $field);
426 $subaction = empty($subAPI[2]) ?
$action : $subAPI[2];
428 'debug' => CRM_Utils_Array
::value('debug', $params),
430 $subEntity = $subAPI[1];
432 foreach ($result['values'] as $idIndex => $parentAPIValues) {
434 if (strtolower($subEntity) != 'contact') {
435 //contact spits the dummy at activity_id so what else won't it like?
436 //set entity_id & entity table based on the parent's id & entity. e.g for something like
437 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
439 //in this case 'contact_id' will also be set to the parent's id
440 $subParams["entity_id"] = $parentAPIValues['id'];
441 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
442 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
444 if (strtolower($entity) != 'contact' && CRM_Utils_Array
::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
445 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
446 //don't do this for contact as it does some wierd things like returning primary email &
447 //thus limiting the ability to chain email
448 //TODO - this might need the camel treatment
449 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
452 if (CRM_Utils_Array
::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
453 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
455 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
456 if (strtolower($entity) == strtolower($subEntity)) {
457 $subParams['id'] = $result['values'][$idIndex]['id'];
461 $subParams['version'] = $version;
462 if(!empty($params['check_permissions'])){
463 $subParams['check_permissions'] = $params['check_permissions'];
465 $subParams['sequential'] = 1;
466 $subParams['api.has_parent'] = 1;
467 if (array_key_exists(0, $newparams)) {
468 // it is a numerically indexed array - ie. multiple creates
469 foreach ($newparams as $entity => $entityparams) {
470 $subParams = array_merge($subParams, $entityparams);
471 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
472 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
473 if ($result['is_error'] === 1) {
474 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
480 $subParams = array_merge($subParams, $newparams);
481 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
482 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
483 if (!empty($result['is_error'])) {
484 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
490 if(strtolower($action) == 'getsingle'){
491 $result = $result['values'][0];
496 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
497 * 'activity_type_id' => '$value.testfield',
498 'tag_id' => '$value.api.tag.create.id',
499 'tag1_id' => '$value.api.entity.create.0.id'
501 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
504 foreach ($params as $field => $value) {
506 if (is_string($value) && substr($value, 0, 6) == '$value') {
507 $valuesubstitute = substr($value, 7);
509 if (!empty($parentResult[$valuesubstitute])) {
510 $params[$field] = $parentResult[$valuesubstitute];
514 $stringParts = explode($separator, $value);
515 unset($stringParts[0]);
517 $fieldname = array_shift($stringParts);
519 //when our string is an array we will treat it as an array from that . onwards
520 $count = count($stringParts);
522 $fieldname .= "." . array_shift($stringParts);
523 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
524 $arrayLocation = $parentResult[$fieldname];
525 foreach ($stringParts as $key => $value) {
526 $arrayLocation = CRM_Utils_Array
::value($value, $arrayLocation);
528 $params[$field] = $arrayLocation;
530 $count = count($stringParts);
538 * Convert possibly camel name to underscore separated entity name
540 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
541 * @return string $entity entity name in underscore separated format
543 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
545 function _civicrm_api_get_entity_name_from_camel($entity) {
546 if ($entity == strtolower($entity)) {
550 $entity = ltrim(strtolower(str_replace('U_F',
552 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
553 preg_replace('/(?=[A-Z])/', '_$0', $entity)
560 * Having a DAO object find the entity name
561 * @param object $bao DAO being passed in
563 function _civicrm_api_get_entity_name_from_dao($bao){
564 $daoName = str_replace("BAO", "DAO", get_class($bao));
565 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName));
569 * Sets the tsLocale and dbLocale for multi-lingual sites.
570 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
571 * to avoid regressions from refactoring.
573 function _civicrm_api_set_locale($lcMessagesRequest) {
574 // We must validate whether the locale is valid, otherwise setting a bad
575 // dbLocale could probably lead to sql-injection.
576 $domain = new CRM_Core_DAO_Domain();
577 $domain->id
= CRM_Core_Config
::domainID();
580 if ($domain->config_backend
) {
581 $defaults = unserialize($domain->config_backend
);
583 // are we in a multi-language setup?
584 $multiLang = $domain->locales ?
TRUE : FALSE;
587 // on multi-lang sites based on request and civicrm_uf_match
589 $languageLimit = array();
590 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
591 $languageLimit = $defaults['languageLimit'];
594 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
595 $lcMessages = $lcMessagesRequest;
598 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
604 // set suffix for table names - use views if more than one language
606 $dbLocale = $multiLang && $lcMessages ?
"_{$lcMessages}" : '';
608 // FIXME: an ugly hack to fix CRM-4041
610 $tsLocale = $lcMessages;