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
24 function civicrm_api($entity, $action, $params, $extra = NULL) {
25 $apiRequest = array();
26 $apiRequest['entity'] = CRM_Utils_String
::munge($entity);
27 $apiRequest['action'] = CRM_Utils_String
::munge($action);
28 $apiRequest['version'] = civicrm_get_api_version($params);
29 $apiRequest['params'] = $params;
30 $apiRequest['extra'] = $extra;
33 CRM_Utils_API_HTMLInputCoder
::singleton(),
34 CRM_Utils_API_NullOutputCoder
::singleton(),
35 CRM_Utils_API_ReloadOption
::singleton(),
36 CRM_Utils_API_MatchOption
::singleton(),
38 CRM_Utils_Hook
::apiWrappers($apiWrappers,$apiRequest);
41 require_once ('api/v3/utils.php');
42 require_once 'api/Exception.php';
43 if (!is_array($params)) {
44 throw new API_Exception('Input variable `params` is not an array', 2000);
46 _civicrm_api3_initialize();
47 $errorScope = CRM_Core_TemporaryErrorScope
::useException();
48 // look up function, file, is_generic
49 $apiRequest +
= _civicrm_api_resolve($apiRequest);
50 if ((strtolower($action) == 'create' ||
strtolower($action) == 'delete' ||
strtolower($action) == 'submit')
51 && (!isset($params['is_transactional']) ||
$params['is_transactional'])) {
52 $apiRequest['is_transactional'] = 1;
53 $transaction = new CRM_Core_Transaction();
56 // support multi-lingual requests
57 if ($language = CRM_Utils_Array
::value('option.language', $params)) {
58 _civicrm_api_set_locale($language);
61 _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
62 $fields = _civicrm_api3_api_getfields($apiRequest);
63 // we do this before we
64 _civicrm_api3_swap_out_aliases($apiRequest, $fields);
65 if (strtolower($action) != 'getfields') {
66 if (!CRM_Utils_Array
::value('id', $apiRequest['params'])) {
67 $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']);
69 //if 'id' is set then only 'version' will be checked but should still be checked for consistency
70 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields));
73 // For input filtering, process $apiWrappers in forward order
74 foreach ($apiWrappers as $apiWrapper) {
75 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
78 $function = $apiRequest['function'];
79 if ($apiRequest['function'] && $apiRequest['is_generic']) {
80 // Unlike normal API implementations, generic implementations require explicit
81 // knowledge of the entity and action (as well as $params). Bundle up these bits
82 // into a convenient data structure.
83 $result = $function($apiRequest);
85 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
86 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
88 $result = isset($extra) ?
$function($apiRequest['params'], $extra) : $function($apiRequest['params']);
91 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
94 // For output filtering, process $apiWrappers in reverse order
95 foreach (array_reverse($apiWrappers) as $apiWrapper) {
96 $result = $apiWrapper->toApiOutput($apiRequest, $result);
99 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
100 if ($result['is_error'] === 0) {
107 if (CRM_Utils_Array
::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
108 return $result['id'];
110 if (CRM_Utils_Array
::value('is_error', $result, 0) == 0) {
111 _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
113 if (function_exists('xdebug_time_index')
114 && CRM_Utils_Array
::value('debug', $apiRequest['params'])
115 // result would not be an array for getvalue
118 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
119 $result['xdebug']['memory'] = xdebug_memory_usage();
120 $result['xdebug']['timeIndex'] = xdebug_time_index();
125 catch(PEAR_Exception
$e) {
126 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
129 $error = $e->getCause();
130 if ($error instanceof DB_Error
) {
131 $data["error_code"] = DB
::errorMessage($error->getCode());
132 $data["sql"] = $error->getDebugInfo();
134 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
135 if(method_exists($e, 'getUserInfo')) {
136 $data['debug_info'] = $error->getUserInfo();
138 if(method_exists($e, 'getExtraData')) {
139 $data['debug_info'] = $data +
$error->getExtraData();
141 $data['trace'] = $e->getTraceAsString();
144 $data['tip'] = "add debug=1 to your API call to have more info about the error";
146 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
147 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
148 $transaction->rollback();
152 catch (API_Exception
$e){
153 if(!isset($apiRequest)){
154 $apiRequest = array();
156 if (CRM_Utils_Array
::value('format.is_success', CRM_Utils_Array
::value('params',$apiRequest)) == 1) {
159 $data = $e->getExtraParams();
160 $data['entity'] = CRM_Utils_Array
::value('entity', $apiRequest);
161 $data['action'] = CRM_Utils_Array
::value('action', $apiRequest);
162 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
163 if (CRM_Utils_Array
::value('debug', CRM_Utils_Array
::value('params',$apiRequest))
164 && empty($data['trace']) // prevent recursion
166 $err['trace'] = $e->getTraceAsString();
168 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
169 $transaction->rollback();
173 catch(Exception
$e) {
174 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
178 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
179 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
180 $err['trace'] = $e->getTraceAsString();
182 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
183 $transaction->rollback();
190 * Look up the implementation for a given API request
192 * @param $apiRequest array with keys:
193 * - entity: string, required
194 * - action: string, required
196 * - version: scalar, required
198 * @return array with keys
199 * - function: callback (mixed)
200 * - is_generic: boolean
202 function _civicrm_api_resolve($apiRequest) {
204 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
205 if (isset($cache[$cachekey])) {
206 return $cache[$cachekey];
209 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
210 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
212 // Determine if there is an entity-specific implementation of the action
213 $stdFunction = civicrm_api_get_function_name($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
214 if (function_exists($stdFunction)) {
215 // someone already loaded the appropriate file
216 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
217 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
218 return $cache[$cachekey];
222 // By convention, the $camelName.php is more likely to contain the function, so test it first
223 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
224 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
226 foreach ($stdFiles as $stdFile) {
227 if (CRM_Utils_File
::isIncludable($stdFile)) {
228 require_once $stdFile;
229 if (function_exists($stdFunction)) {
230 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
231 return $cache[$cachekey];
236 // Determine if there is a generic implementation of the action
237 require_once 'api/v3/Generic.php';
238 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
239 $genericFunction = civicrm_api_get_function_name('generic', $apiRequest['action'], $apiRequest['version']);
240 $genericFiles = array(
241 // By convention, the Generic.php is more likely to contain the function, so test it first
242 'api/v' . $apiRequest['version'] . '/Generic.php',
243 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
245 foreach ($genericFiles as $genericFile) {
246 if (CRM_Utils_File
::isIncludable($genericFile)) {
247 require_once $genericFile;
248 if (function_exists($genericFunction)) {
249 $cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
250 return $cache[$cachekey];
255 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
256 return $cache[$cachekey];
260 * Version 3 wrapper for civicrm_api. Throws exception
262 * @param string $entity type of entities to deal with
263 * @param string $action create, get, delete or some special action name.
264 * @param array $params array to be passed to function
266 * @throws CiviCRM_API3_Exception
269 function civicrm_api3($entity, $action, $params = array()) {
270 $params['version'] = 3;
271 $result = civicrm_api($entity, $action, $params);
272 if(is_array($result) && !empty($result['is_error'])){
273 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
279 * Function to call getfields from api wrapper. This function ensures that settings that could alter
280 * getfields output (e.g. action for all api & profile_id for profile api ) are consistently passed in.
282 * We check whether the api call is 'getfields' because if getfields is being called we return an empty array
283 * as no alias swapping, validation or default filling is done on getfields & we want to avoid a loop
285 * @todo other output modifiers include contact_type
287 * @param array $apiRequest
288 * @return getfields output
290 function _civicrm_api3_api_getfields(&$apiRequest) {
291 if (strtolower($apiRequest['action'] == 'getfields')) {
292 // the main param getfields takes is 'action' - however this param is not compatible with REST
293 // so we accept 'api_action' as an alias of action on getfields
294 if (CRM_Utils_Array
::value('api_action', $apiRequest['params'])) {
295 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
296 // unset($apiRequest['params']['api_action']);
298 return array('action' => array('api.aliases' => array('api_action')));
300 $getFieldsParams = array('action' => $apiRequest['action']);
301 $entity = $apiRequest['entity'];
302 if($entity == 'profile' && array_key_exists('profile_id', $apiRequest['params'])) {
303 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
305 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
306 return $fields['values'];
310 * Load/require all files related to an entity.
312 * This should not normally be called because it's does a file-system scan; it's
313 * only appropriate when introspection is really required (eg for "getActions").
315 * @param string $entity
316 * @param int $version
320 function _civicrm_api_loadEntity($entity, $version = 3) {
322 $apiRequest = array();
323 $apiRequest['entity'] = $entity;
324 $apiRequest['action'] = 'pretty sure it will never exist. Trick to [try to] force resolve to scan everywhere';
325 $apiRequest['version'] = $version;
326 // look up function, file, is_generic
327 $apiRequest = _civicrm_api_resolve($apiRequest);
330 $camelName = _civicrm_api_get_camel_name($entity, $version);
332 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
333 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
334 if (CRM_Utils_File
::isIncludable($stdFile)) {
335 require_once $stdFile;
338 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
339 $loaded_files = array(); // array($relativeFilePath => TRUE)
340 $include_dirs = array_unique(explode(PATH_SEPARATOR
, get_include_path()));
341 foreach ($include_dirs as $include_dir) {
342 $action_dir = implode(DIRECTORY_SEPARATOR
, array($include_dir, 'api', "v${version}", $camelName));
343 if (! is_dir($action_dir)) {
347 $iterator = new DirectoryIterator($action_dir);
348 foreach ($iterator as $fileinfo) {
349 $file = $fileinfo->getFilename();
350 if (array_key_exists($file, $loaded_files)) {
351 continue; // action provided by an earlier item on include_path
354 $parts = explode(".", $file);
355 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file) ) {
356 require_once $action_dir . DIRECTORY_SEPARATOR
. $file;
357 $loaded_files[$file] = TRUE;
367 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
369 if (empty($version)) {
370 $version = civicrm_get_api_version();
373 $entity = _civicrm_api_get_entity_name_from_camel($entity);
374 return 'civicrm_api3' . '_' . $entity . '_' . $action;
378 * We must be sure that every request uses only one version of the API.
380 * @param $desired_version : array or integer
381 * One chance to set the version number.
382 * After that, this version number will be used for the remaining request.
383 * This can either be a number, or an array(.., 'version' => $version, ..).
384 * This allows to directly pass the $params array.
387 function civicrm_get_api_version($desired_version = NULL) {
389 if (is_array($desired_version)) {
390 // someone gave the full $params array.
391 $params = $desired_version;
392 $desired_version = empty($params['version']) ?
NULL : (int) $params['version'];
394 if (isset($desired_version) && is_integer($desired_version)) {
395 $_version = $desired_version;
398 // we will set the default to version 3 as soon as we find that it works.
405 * Check if the result is an error. Note that this function has been retained from
406 * api v2 for convenience but the result is more standardised in v3 and param
407 * 'format.is_success' => 1
408 * will result in a boolean success /fail being returned if that is what you need.
412 * @internal param array $params (reference ) input parameters
414 * @return boolean true if error, false otherwise
418 function civicrm_error($result) {
419 if (is_array($result)) {
420 return (array_key_exists('is_error', $result) &&
427 function _civicrm_api_get_camel_name($entity, $version = NULL) {
428 if (empty($version)) {
429 $version = civicrm_get_api_version();
432 $fragments = explode('_', $entity);
433 foreach ($fragments as & $fragment) {
434 $fragment = ucfirst($fragment);
436 // Special case: UFGroup, UFJoin, UFMatch, UFField
437 if ($fragments[0] === 'Uf') {
438 $fragments[0] = 'UF';
440 return implode('', $fragments);
444 * Call any nested api calls
446 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
447 $entity = _civicrm_api_get_entity_name_from_camel($entity);
449 //we don't need to worry about nested api in the getfields/getoptions actions, so just return immediately
450 if (in_array(strtolower($action), array('getfields', 'getoptions'))) {
454 if(strtolower($action) == 'getsingle'){
455 // I don't understand the protocol here, but we don't want
456 // $result to be a recursive array
457 // $result['values'][0] = $result;
458 $oldResult = $result;
459 $result = array('values' => array(0 => $oldResult));
461 foreach ($params as $field => $newparams) {
462 if ((is_array($newparams) ||
$newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
464 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
465 if ($newparams === 1) {
466 $newparams = array('version' => $version);
468 // can be api_ or api.
469 $separator = $field[3];
470 if (!($separator == '.' ||
$separator == '_')) {
473 $subAPI = explode($separator, $field);
475 $subaction = empty($subAPI[2]) ?
$action : $subAPI[2];
477 'debug' => CRM_Utils_Array
::value('debug', $params),
479 $subEntity = $subAPI[1];
481 foreach ($result['values'] as $idIndex => $parentAPIValues) {
483 if (strtolower($subEntity) != 'contact') {
484 //contact spits the dummy at activity_id so what else won't it like?
485 //set entity_id & entity table based on the parent's id & entity. e.g for something like
486 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
488 //in this case 'contact_id' will also be set to the parent's id
489 $subParams["entity_id"] = $parentAPIValues['id'];
490 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
491 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
493 if (strtolower($entity) != 'contact' && CRM_Utils_Array
::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
494 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
495 //don't do this for contact as it does some wierd things like returning primary email &
496 //thus limiting the ability to chain email
497 //TODO - this might need the camel treatment
498 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
501 if (CRM_Utils_Array
::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
502 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
504 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
505 if (strtolower($entity) == strtolower($subEntity)) {
506 $subParams['id'] = $result['values'][$idIndex]['id'];
510 $subParams['version'] = $version;
511 if(!empty($params['check_permissions'])){
512 $subParams['check_permissions'] = $params['check_permissions'];
514 $subParams['sequential'] = 1;
515 $subParams['api.has_parent'] = 1;
516 if (array_key_exists(0, $newparams)) {
517 $genericParams = $subParams;
518 // it is a numerically indexed array - ie. multiple creates
519 foreach ($newparams as $entityparams) {
520 $subParams = array_merge($genericParams, $entityparams);
521 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
522 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
523 if ($result['is_error'] === 1) {
524 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
530 $subParams = array_merge($subParams, $newparams);
531 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
532 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
533 if (!empty($result['is_error'])) {
534 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
540 if(strtolower($action) == 'getsingle'){
541 $result = $result['values'][0];
546 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
547 * 'activity_type_id' => '$value.testfield',
548 'tag_id' => '$value.api.tag.create.id',
549 'tag1_id' => '$value.api.entity.create.0.id'
551 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
554 foreach ($params as $field => $value) {
556 if (is_string($value) && substr($value, 0, 6) == '$value') {
557 $valuesubstitute = substr($value, 7);
559 if (!empty($parentResult[$valuesubstitute])) {
560 $params[$field] = $parentResult[$valuesubstitute];
564 $stringParts = explode($separator, $value);
565 unset($stringParts[0]);
567 $fieldname = array_shift($stringParts);
569 //when our string is an array we will treat it as an array from that . onwards
570 $count = count($stringParts);
572 $fieldname .= "." . array_shift($stringParts);
573 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
574 $arrayLocation = $parentResult[$fieldname];
575 foreach ($stringParts as $key => $value) {
576 $arrayLocation = CRM_Utils_Array
::value($value, $arrayLocation);
578 $params[$field] = $arrayLocation;
580 $count = count($stringParts);
588 * Convert possibly camel name to underscore separated entity name
590 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
591 * @return string $entity entity name in underscore separated format
593 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
595 function _civicrm_api_get_entity_name_from_camel($entity) {
596 if ($entity == strtolower($entity)) {
600 $entity = ltrim(strtolower(str_replace('U_F',
602 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
603 preg_replace('/(?=[A-Z])/', '_$0', $entity)
610 * Having a DAO object find the entity name
611 * @param object $bao DAO being passed in
614 function _civicrm_api_get_entity_name_from_dao($bao){
615 $daoName = str_replace("BAO", "DAO", get_class($bao));
616 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName));
620 * Sets the tsLocale and dbLocale for multi-lingual sites.
621 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
622 * to avoid regressions from refactoring.
624 function _civicrm_api_set_locale($lcMessagesRequest) {
625 // We must validate whether the locale is valid, otherwise setting a bad
626 // dbLocale could probably lead to sql-injection.
627 $domain = new CRM_Core_DAO_Domain();
628 $domain->id
= CRM_Core_Config
::domainID();
631 if ($domain->config_backend
) {
632 $defaults = unserialize($domain->config_backend
);
634 // are we in a multi-language setup?
635 $multiLang = $domain->locales ?
TRUE : FALSE;
638 // on multi-lang sites based on request and civicrm_uf_match
640 $languageLimit = array();
641 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
642 $languageLimit = $defaults['languageLimit'];
645 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
646 $lcMessages = $lcMessagesRequest;
649 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
655 // set suffix for table names - use views if more than one language
657 $dbLocale = $multiLang && $lcMessages ?
"_{$lcMessages}" : '';
659 // FIXME: an ugly hack to fix CRM-4041
661 $tsLocale = $lcMessages;