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(),
33 CRM_Utils_API_MatchOption
::singleton(),
35 CRM_Utils_Hook
::apiWrappers($apiWrappers,$apiRequest);
38 require_once ('api/v3/utils.php');
39 require_once 'api/Exception.php';
40 if (!is_array($params)) {
41 throw new API_Exception('Input variable `params` is not an array', 2000);
43 _civicrm_api3_initialize();
44 $errorScope = CRM_Core_TemporaryErrorScope
::useException();
45 // look up function, file, is_generic
46 $apiRequest +
= _civicrm_api_resolve($apiRequest);
47 if (strtolower($action) == 'create' ||
strtolower($action) == 'delete' ||
strtolower($action) == 'submit') {
48 $apiRequest['is_transactional'] = 1;
49 $transaction = new CRM_Core_Transaction();
52 // support multi-lingual requests
53 if ($language = CRM_Utils_Array
::value('option.language', $params)) {
54 _civicrm_api_set_locale($language);
57 _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
58 $fields = _civicrm_api3_api_getfields($apiRequest);
59 // we do this before we
60 _civicrm_api3_swap_out_aliases($apiRequest, $fields);
61 if (strtolower($action) != 'getfields') {
62 if (!CRM_Utils_Array
::value('id', $apiRequest['params'])) {
63 $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']);
65 //if 'id' is set then only 'version' will be checked but should still be checked for consistency
66 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields));
69 // For input filtering, process $apiWrappers in forward order
70 foreach ($apiWrappers as $apiWrapper) {
71 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
74 $function = $apiRequest['function'];
75 if ($apiRequest['function'] && $apiRequest['is_generic']) {
76 // Unlike normal API implementations, generic implementations require explicit
77 // knowledge of the entity and action (as well as $params). Bundle up these bits
78 // into a convenient data structure.
79 $result = $function($apiRequest);
81 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
82 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
84 $result = isset($extra) ?
$function($apiRequest['params'], $extra) : $function($apiRequest['params']);
87 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . "," . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
90 // For output filtering, process $apiWrappers in reverse order
91 foreach (array_reverse($apiWrappers) as $apiWrapper) {
92 $result = $apiWrapper->toApiOutput($apiRequest, $result);
95 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
96 if ($result['is_error'] === 0) {
103 if (CRM_Utils_Array
::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
104 return $result['id'];
106 if (CRM_Utils_Array
::value('is_error', $result, 0) == 0) {
107 _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
109 if (function_exists('xdebug_time_index')
110 && CRM_Utils_Array
::value('debug', $apiRequest['params'])
111 // result would not be an array for getvalue
114 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
115 $result['xdebug']['memory'] = xdebug_memory_usage();
116 $result['xdebug']['timeIndex'] = xdebug_time_index();
121 catch(PEAR_Exception
$e) {
122 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
125 $error = $e->getCause();
126 if ($error instanceof DB_Error
) {
127 $data["error_code"] = DB
::errorMessage($error->getCode());
128 $data["sql"] = $error->getDebugInfo();
130 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
131 if(method_exists($e, 'getUserInfo')) {
132 $data['debug_info'] = $error->getUserInfo();
134 if(method_exists($e, 'getExtraData')) {
135 $data['debug_info'] = $data +
$error->getExtraData();
137 $data['trace'] = $e->getTraceAsString();
140 $data['tip'] = "add debug=1 to your API call to have more info about the error";
142 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
143 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
144 $transaction->rollback();
148 catch (API_Exception
$e){
149 if(!isset($apiRequest)){
150 $apiRequest = array();
152 if (CRM_Utils_Array
::value('format.is_success', CRM_Utils_Array
::value('params',$apiRequest)) == 1) {
155 $data = $e->getExtraParams();
156 $data['entity'] = CRM_Utils_Array
::value('entity', $apiRequest);
157 $data['action'] = CRM_Utils_Array
::value('action', $apiRequest);
158 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
159 if (CRM_Utils_Array
::value('debug', CRM_Utils_Array
::value('params',$apiRequest))
160 && empty($data['trace']) // prevent recursion
162 $err['trace'] = $e->getTraceAsString();
164 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
165 $transaction->rollback();
169 catch(Exception
$e) {
170 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
174 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
175 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
176 $err['trace'] = $e->getTraceAsString();
178 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
179 $transaction->rollback();
186 * Look up the implementation for a given API request
188 * @param $apiRequest array with keys:
189 * - entity: string, required
190 * - action: string, required
192 * - version: scalar, required
194 * @return array with keys
195 * - function: callback (mixed)
196 * - is_generic: boolean
198 function _civicrm_api_resolve($apiRequest) {
200 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
201 if (isset($cache[$cachekey])) {
202 return $cache[$cachekey];
205 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
206 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
208 // Determine if there is an entity-specific implementation of the action
209 $stdFunction = civicrm_api_get_function_name($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
210 if (function_exists($stdFunction)) {
211 // someone already loaded the appropriate file
212 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
213 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
214 return $cache[$cachekey];
218 // By convention, the $camelName.php is more likely to contain the function, so test it first
219 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
220 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
222 foreach ($stdFiles as $stdFile) {
223 if (CRM_Utils_File
::isIncludable($stdFile)) {
224 require_once $stdFile;
225 if (function_exists($stdFunction)) {
226 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
227 return $cache[$cachekey];
232 // Determine if there is a generic implementation of the action
233 require_once 'api/v3/Generic.php';
234 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
235 $genericFunction = civicrm_api_get_function_name('generic', $apiRequest['action'], $apiRequest['version']);
236 $genericFiles = array(
237 // By convention, the Generic.php is more likely to contain the function, so test it first
238 'api/v' . $apiRequest['version'] . '/Generic.php',
239 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
241 foreach ($genericFiles as $genericFile) {
242 if (CRM_Utils_File
::isIncludable($genericFile)) {
243 require_once $genericFile;
244 if (function_exists($genericFunction)) {
245 $cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
246 return $cache[$cachekey];
251 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
252 return $cache[$cachekey];
255 * Version 3 wrapper for civicrm_api. Throws exception
256 * @param string $entity type of entities to deal with
257 * @param string $action create, get, delete or some special action name.
258 * @param array $params array to be passed to function
263 function civicrm_api3($entity, $action, $params) {
264 $params['version'] = 3;
265 $result = civicrm_api($entity, $action, $params);
266 if(is_array($result) && !empty($result['is_error'])){
267 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
273 * Function to call getfields from api wrapper. This function ensures that settings that could alter
274 * getfields output (e.g. action for all api & profile_id for profile api ) are consistently passed in.
276 * We check whether the api call is 'getfields' because if getfields is being called we return an empty array
277 * as no alias swapping, validation or default filling is done on getfields & we want to avoid a loop
279 * @todo other output modifiers include contact_type
281 * @param array $apiRequest
282 * @return getfields output
284 function _civicrm_api3_api_getfields(&$apiRequest) {
285 if (strtolower($apiRequest['action'] == 'getfields')) {
286 // the main param getfields takes is 'action' - however this param is not compatible with REST
287 // so we accept 'api_action' as an alias of action on getfields
288 if (CRM_Utils_Array
::value('api_action', $apiRequest['params'])) {
289 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
290 // unset($apiRequest['params']['api_action']);
292 return array('action' => array('api_aliases' => array('action')));
294 $getFieldsParams = array('action' => $apiRequest['action']);
295 $entity = $apiRequest['entity'];
296 if($entity == 'profile' && array_key_exists('profile_id', $apiRequest['params'])) {
297 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
299 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
300 return $fields['values'];
303 * Load/require all files related to an entity.
305 * This should not normally be called because it's does a file-system scan; it's
306 * only appropriate when introspection is really required (eg for "getActions").
308 * @param string $entity
311 function _civicrm_api_loadEntity($entity, $version = 3) {
313 $apiRequest = array();
314 $apiRequest['entity'] = $entity;
315 $apiRequest['action'] = 'pretty sure it will never exist. Trick to [try to] force resolve to scan everywhere';
316 $apiRequest['version'] = $version;
317 // look up function, file, is_generic
318 $apiRequest = _civicrm_api_resolve($apiRequest);
321 $camelName = _civicrm_api_get_camel_name($entity, $version);
323 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
324 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
325 if (CRM_Utils_File
::isIncludable($stdFile)) {
326 require_once $stdFile;
329 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
330 $loaded_files = array(); // array($relativeFilePath => TRUE)
331 $include_dirs = array_unique(explode(PATH_SEPARATOR
, get_include_path()));
332 foreach ($include_dirs as $include_dir) {
333 $action_dir = implode(DIRECTORY_SEPARATOR
, array($include_dir, 'api', "v${version}", $camelName));
334 if (! is_dir($action_dir)) {
338 $iterator = new DirectoryIterator($action_dir);
339 foreach ($iterator as $fileinfo) {
340 $file = $fileinfo->getFilename();
341 if (array_key_exists($file, $loaded_files)) {
342 continue; // action provided by an earlier item on include_path
345 $parts = explode(".", $file);
346 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file) ) {
347 require_once $action_dir . DIRECTORY_SEPARATOR
. $file;
348 $loaded_files[$file] = TRUE;
358 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
360 if (empty($version)) {
361 $version = civicrm_get_api_version();
364 $entity = _civicrm_api_get_entity_name_from_camel($entity);
365 return 'civicrm_api3' . '_' . $entity . '_' . $action;
369 * We must be sure that every request uses only one version of the API.
371 * @param $desired_version : array or integer
372 * One chance to set the version number.
373 * After that, this version number will be used for the remaining request.
374 * This can either be a number, or an array(.., 'version' => $version, ..).
375 * This allows to directly pass the $params array.
377 function civicrm_get_api_version($desired_version = NULL) {
379 if (is_array($desired_version)) {
380 // someone gave the full $params array.
381 $params = $desired_version;
382 $desired_version = empty($params['version']) ?
NULL : (int) $params['version'];
384 if (isset($desired_version) && is_integer($desired_version)) {
385 $_version = $desired_version;
388 // we will set the default to version 3 as soon as we find that it works.
395 * Check if the result is an error. Note that this function has been retained from
396 * api v2 for convenience but the result is more standardised in v3 and param
397 * 'format.is_success' => 1
398 * will result in a boolean success /fail being returned if that is what you need.
400 * @param array $params (reference ) input parameters
402 * @return boolean true if error, false otherwise
406 function civicrm_error($result) {
407 if (is_array($result)) {
408 return (array_key_exists('is_error', $result) &&
415 function _civicrm_api_get_camel_name($entity, $version = NULL) {
416 if (empty($version)) {
417 $version = civicrm_get_api_version();
420 $fragments = explode('_', $entity);
421 foreach ($fragments as & $fragment) {
422 $fragment = ucfirst($fragment);
424 // Special case: UFGroup, UFJoin, UFMatch, UFField
425 if ($fragments[0] === 'Uf') {
426 $fragments[0] = 'UF';
428 return implode('', $fragments);
432 * Call any nested api calls
434 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
435 $entity = _civicrm_api_get_entity_name_from_camel($entity);
436 if(strtolower($action) == 'getsingle'){
437 // I don't understand the protocol here, but we don't want
438 // $result to be a recursive array
439 // $result['values'][0] = $result;
440 $oldResult = $result;
441 $result = array('values' => array(0 => $oldResult));
443 foreach ($params as $field => $newparams) {
444 if ((is_array($newparams) ||
$newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
446 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
447 if ($newparams === 1) {
448 $newparams = array('version' => $version);
450 // can be api_ or api.
451 $separator = $field[3];
452 if (!($separator == '.' ||
$separator == '_')) {
455 $subAPI = explode($separator, $field);
457 $subaction = empty($subAPI[2]) ?
$action : $subAPI[2];
459 'debug' => CRM_Utils_Array
::value('debug', $params),
461 $subEntity = $subAPI[1];
463 foreach ($result['values'] as $idIndex => $parentAPIValues) {
465 if (strtolower($subEntity) != 'contact') {
466 //contact spits the dummy at activity_id so what else won't it like?
467 //set entity_id & entity table based on the parent's id & entity. e.g for something like
468 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
470 //in this case 'contact_id' will also be set to the parent's id
471 $subParams["entity_id"] = $parentAPIValues['id'];
472 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
473 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
475 if (strtolower($entity) != 'contact' && CRM_Utils_Array
::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
476 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
477 //don't do this for contact as it does some wierd things like returning primary email &
478 //thus limiting the ability to chain email
479 //TODO - this might need the camel treatment
480 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
483 if (CRM_Utils_Array
::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
484 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
486 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
487 if (strtolower($entity) == strtolower($subEntity)) {
488 $subParams['id'] = $result['values'][$idIndex]['id'];
492 $subParams['version'] = $version;
493 if(!empty($params['check_permissions'])){
494 $subParams['check_permissions'] = $params['check_permissions'];
496 $subParams['sequential'] = 1;
497 $subParams['api.has_parent'] = 1;
498 if (array_key_exists(0, $newparams)) {
499 // it is a numerically indexed array - ie. multiple creates
500 foreach ($newparams as $entity => $entityparams) {
501 $subParams = array_merge($subParams, $entityparams);
502 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
503 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
504 if ($result['is_error'] === 1) {
505 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
511 $subParams = array_merge($subParams, $newparams);
512 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
513 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
514 if (!empty($result['is_error'])) {
515 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
521 if(strtolower($action) == 'getsingle'){
522 $result = $result['values'][0];
527 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
528 * 'activity_type_id' => '$value.testfield',
529 'tag_id' => '$value.api.tag.create.id',
530 'tag1_id' => '$value.api.entity.create.0.id'
532 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
535 foreach ($params as $field => $value) {
537 if (is_string($value) && substr($value, 0, 6) == '$value') {
538 $valuesubstitute = substr($value, 7);
540 if (!empty($parentResult[$valuesubstitute])) {
541 $params[$field] = $parentResult[$valuesubstitute];
545 $stringParts = explode($separator, $value);
546 unset($stringParts[0]);
548 $fieldname = array_shift($stringParts);
550 //when our string is an array we will treat it as an array from that . onwards
551 $count = count($stringParts);
553 $fieldname .= "." . array_shift($stringParts);
554 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
555 $arrayLocation = $parentResult[$fieldname];
556 foreach ($stringParts as $key => $value) {
557 $arrayLocation = CRM_Utils_Array
::value($value, $arrayLocation);
559 $params[$field] = $arrayLocation;
561 $count = count($stringParts);
569 * Convert possibly camel name to underscore separated entity name
571 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
572 * @return string $entity entity name in underscore separated format
574 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
576 function _civicrm_api_get_entity_name_from_camel($entity) {
577 if ($entity == strtolower($entity)) {
581 $entity = ltrim(strtolower(str_replace('U_F',
583 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
584 preg_replace('/(?=[A-Z])/', '_$0', $entity)
591 * Having a DAO object find the entity name
592 * @param object $bao DAO being passed in
594 function _civicrm_api_get_entity_name_from_dao($bao){
595 $daoName = str_replace("BAO", "DAO", get_class($bao));
596 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName));
600 * Sets the tsLocale and dbLocale for multi-lingual sites.
601 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
602 * to avoid regressions from refactoring.
604 function _civicrm_api_set_locale($lcMessagesRequest) {
605 // We must validate whether the locale is valid, otherwise setting a bad
606 // dbLocale could probably lead to sql-injection.
607 $domain = new CRM_Core_DAO_Domain();
608 $domain->id
= CRM_Core_Config
::domainID();
611 if ($domain->config_backend
) {
612 $defaults = unserialize($domain->config_backend
);
614 // are we in a multi-language setup?
615 $multiLang = $domain->locales ?
TRUE : FALSE;
618 // on multi-lang sites based on request and civicrm_uf_match
620 $languageLimit = array();
621 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
622 $languageLimit = $defaults['languageLimit'];
625 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
626 $lcMessages = $lcMessagesRequest;
629 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
635 // set suffix for table names - use views if more than one language
637 $dbLocale = $multiLang && $lcMessages ?
"_{$lcMessages}" : '';
639 // FIXME: an ugly hack to fix CRM-4041
641 $tsLocale = $lcMessages;