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 $apiRequest['is_transactional'] = 1;
52 $transaction = new CRM_Core_Transaction();
55 // support multi-lingual requests
56 if ($language = CRM_Utils_Array
::value('option.language', $params)) {
57 _civicrm_api_set_locale($language);
60 _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
61 $fields = _civicrm_api3_api_getfields($apiRequest);
62 // we do this before we
63 _civicrm_api3_swap_out_aliases($apiRequest, $fields);
64 if (strtolower($action) != 'getfields') {
65 if (!CRM_Utils_Array
::value('id', $apiRequest['params'])) {
66 $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']);
68 //if 'id' is set then only 'version' will be checked but should still be checked for consistency
69 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields));
72 // For input filtering, process $apiWrappers in forward order
73 foreach ($apiWrappers as $apiWrapper) {
74 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
77 $function = $apiRequest['function'];
78 if ($apiRequest['function'] && $apiRequest['is_generic']) {
79 // Unlike normal API implementations, generic implementations require explicit
80 // knowledge of the entity and action (as well as $params). Bundle up these bits
81 // into a convenient data structure.
82 $result = $function($apiRequest);
84 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
85 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
87 $result = isset($extra) ?
$function($apiRequest['params'], $extra) : $function($apiRequest['params']);
90 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
93 // For output filtering, process $apiWrappers in reverse order
94 foreach (array_reverse($apiWrappers) as $apiWrapper) {
95 $result = $apiWrapper->toApiOutput($apiRequest, $result);
98 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
99 if ($result['is_error'] === 0) {
106 if (CRM_Utils_Array
::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
107 return $result['id'];
109 if (CRM_Utils_Array
::value('is_error', $result, 0) == 0) {
110 _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
112 if (function_exists('xdebug_time_index')
113 && CRM_Utils_Array
::value('debug', $apiRequest['params'])
114 // result would not be an array for getvalue
117 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
118 $result['xdebug']['memory'] = xdebug_memory_usage();
119 $result['xdebug']['timeIndex'] = xdebug_time_index();
124 catch(PEAR_Exception
$e) {
125 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
128 $error = $e->getCause();
129 if ($error instanceof DB_Error
) {
130 $data["error_code"] = DB
::errorMessage($error->getCode());
131 $data["sql"] = $error->getDebugInfo();
133 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
134 if(method_exists($e, 'getUserInfo')) {
135 $data['debug_info'] = $error->getUserInfo();
137 if(method_exists($e, 'getExtraData')) {
138 $data['debug_info'] = $data +
$error->getExtraData();
140 $data['trace'] = $e->getTraceAsString();
143 $data['tip'] = "add debug=1 to your API call to have more info about the error";
145 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
146 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
147 $transaction->rollback();
151 catch (API_Exception
$e){
152 if(!isset($apiRequest)){
153 $apiRequest = array();
155 if (CRM_Utils_Array
::value('format.is_success', CRM_Utils_Array
::value('params',$apiRequest)) == 1) {
158 $data = $e->getExtraParams();
159 $data['entity'] = CRM_Utils_Array
::value('entity', $apiRequest);
160 $data['action'] = CRM_Utils_Array
::value('action', $apiRequest);
161 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
162 if (CRM_Utils_Array
::value('debug', CRM_Utils_Array
::value('params',$apiRequest))
163 && empty($data['trace']) // prevent recursion
165 $err['trace'] = $e->getTraceAsString();
167 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
168 $transaction->rollback();
172 catch(Exception
$e) {
173 if (CRM_Utils_Array
::value('format.is_success', $apiRequest['params']) == 1) {
177 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
178 if (CRM_Utils_Array
::value('debug', $apiRequest['params'])) {
179 $err['trace'] = $e->getTraceAsString();
181 if (CRM_Utils_Array
::value('is_transactional', $apiRequest)) {
182 $transaction->rollback();
189 * Look up the implementation for a given API request
191 * @param $apiRequest array with keys:
192 * - entity: string, required
193 * - action: string, required
195 * - version: scalar, required
197 * @return array with keys
198 * - function: callback (mixed)
199 * - is_generic: boolean
201 function _civicrm_api_resolve($apiRequest) {
203 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
204 if (isset($cache[$cachekey])) {
205 return $cache[$cachekey];
208 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
209 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
211 // Determine if there is an entity-specific implementation of the action
212 $stdFunction = civicrm_api_get_function_name($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
213 if (function_exists($stdFunction)) {
214 // someone already loaded the appropriate file
215 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
216 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
217 return $cache[$cachekey];
221 // By convention, the $camelName.php is more likely to contain the function, so test it first
222 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
223 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
225 foreach ($stdFiles as $stdFile) {
226 if (CRM_Utils_File
::isIncludable($stdFile)) {
227 require_once $stdFile;
228 if (function_exists($stdFunction)) {
229 $cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
230 return $cache[$cachekey];
235 // Determine if there is a generic implementation of the action
236 require_once 'api/v3/Generic.php';
237 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
238 $genericFunction = civicrm_api_get_function_name('generic', $apiRequest['action'], $apiRequest['version']);
239 $genericFiles = array(
240 // By convention, the Generic.php is more likely to contain the function, so test it first
241 'api/v' . $apiRequest['version'] . '/Generic.php',
242 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
244 foreach ($genericFiles as $genericFile) {
245 if (CRM_Utils_File
::isIncludable($genericFile)) {
246 require_once $genericFile;
247 if (function_exists($genericFunction)) {
248 $cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
249 return $cache[$cachekey];
254 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
255 return $cache[$cachekey];
259 * Version 3 wrapper for civicrm_api. Throws exception
261 * @param string $entity type of entities to deal with
262 * @param string $action create, get, delete or some special action name.
263 * @param array $params array to be passed to function
265 * @throws CiviCRM_API3_Exception
268 function civicrm_api3($entity, $action, $params = array()) {
269 $params['version'] = 3;
270 $result = civicrm_api($entity, $action, $params);
271 if(is_array($result) && !empty($result['is_error'])){
272 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
278 * Function to call getfields from api wrapper. This function ensures that settings that could alter
279 * getfields output (e.g. action for all api & profile_id for profile api ) are consistently passed in.
281 * We check whether the api call is 'getfields' because if getfields is being called we return an empty array
282 * as no alias swapping, validation or default filling is done on getfields & we want to avoid a loop
284 * @todo other output modifiers include contact_type
286 * @param array $apiRequest
287 * @return getfields output
289 function _civicrm_api3_api_getfields(&$apiRequest) {
290 if (strtolower($apiRequest['action'] == 'getfields')) {
291 // the main param getfields takes is 'action' - however this param is not compatible with REST
292 // so we accept 'api_action' as an alias of action on getfields
293 if (CRM_Utils_Array
::value('api_action', $apiRequest['params'])) {
294 // $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
295 // unset($apiRequest['params']['api_action']);
297 return array('action' => array('api.aliases' => array('api_action')));
299 $getFieldsParams = array('action' => $apiRequest['action']);
300 $entity = $apiRequest['entity'];
301 if($entity == 'profile' && array_key_exists('profile_id', $apiRequest['params'])) {
302 $getFieldsParams['profile_id'] = $apiRequest['params']['profile_id'];
304 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
305 return $fields['values'];
309 * Load/require all files related to an entity.
311 * This should not normally be called because it's does a file-system scan; it's
312 * only appropriate when introspection is really required (eg for "getActions").
314 * @param string $entity
315 * @param int $version
319 function _civicrm_api_loadEntity($entity, $version = 3) {
321 $apiRequest = array();
322 $apiRequest['entity'] = $entity;
323 $apiRequest['action'] = 'pretty sure it will never exist. Trick to [try to] force resolve to scan everywhere';
324 $apiRequest['version'] = $version;
325 // look up function, file, is_generic
326 $apiRequest = _civicrm_api_resolve($apiRequest);
329 $camelName = _civicrm_api_get_camel_name($entity, $version);
331 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
332 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
333 if (CRM_Utils_File
::isIncludable($stdFile)) {
334 require_once $stdFile;
337 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
338 $loaded_files = array(); // array($relativeFilePath => TRUE)
339 $include_dirs = array_unique(explode(PATH_SEPARATOR
, get_include_path()));
340 foreach ($include_dirs as $include_dir) {
341 $action_dir = implode(DIRECTORY_SEPARATOR
, array($include_dir, 'api', "v${version}", $camelName));
342 if (! is_dir($action_dir)) {
346 $iterator = new DirectoryIterator($action_dir);
347 foreach ($iterator as $fileinfo) {
348 $file = $fileinfo->getFilename();
349 if (array_key_exists($file, $loaded_files)) {
350 continue; // action provided by an earlier item on include_path
353 $parts = explode(".", $file);
354 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file) ) {
355 require_once $action_dir . DIRECTORY_SEPARATOR
. $file;
356 $loaded_files[$file] = TRUE;
366 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
368 if (empty($version)) {
369 $version = civicrm_get_api_version();
372 $entity = _civicrm_api_get_entity_name_from_camel($entity);
373 return 'civicrm_api3' . '_' . $entity . '_' . $action;
377 * We must be sure that every request uses only one version of the API.
379 * @param $desired_version : array or integer
380 * One chance to set the version number.
381 * After that, this version number will be used for the remaining request.
382 * This can either be a number, or an array(.., 'version' => $version, ..).
383 * This allows to directly pass the $params array.
386 function civicrm_get_api_version($desired_version = NULL) {
388 if (is_array($desired_version)) {
389 // someone gave the full $params array.
390 $params = $desired_version;
391 $desired_version = empty($params['version']) ?
NULL : (int) $params['version'];
393 if (isset($desired_version) && is_integer($desired_version)) {
394 $_version = $desired_version;
397 // we will set the default to version 3 as soon as we find that it works.
404 * Check if the result is an error. Note that this function has been retained from
405 * api v2 for convenience but the result is more standardised in v3 and param
406 * 'format.is_success' => 1
407 * will result in a boolean success /fail being returned if that is what you need.
411 * @internal param array $params (reference ) input parameters
413 * @return boolean true if error, false otherwise
417 function civicrm_error($result) {
418 if (is_array($result)) {
419 return (array_key_exists('is_error', $result) &&
426 function _civicrm_api_get_camel_name($entity, $version = NULL) {
427 if (empty($version)) {
428 $version = civicrm_get_api_version();
431 $fragments = explode('_', $entity);
432 foreach ($fragments as & $fragment) {
433 $fragment = ucfirst($fragment);
435 // Special case: UFGroup, UFJoin, UFMatch, UFField
436 if ($fragments[0] === 'Uf') {
437 $fragments[0] = 'UF';
439 return implode('', $fragments);
443 * Call any nested api calls
445 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
446 $entity = _civicrm_api_get_entity_name_from_camel($entity);
448 //we don't need to worry about nested api in the getfields/getoptions actions, so just return immediately
449 if (in_array(strtolower($action), array('getfields', 'getoptions'))) {
453 if(strtolower($action) == 'getsingle'){
454 // I don't understand the protocol here, but we don't want
455 // $result to be a recursive array
456 // $result['values'][0] = $result;
457 $oldResult = $result;
458 $result = array('values' => array(0 => $oldResult));
460 foreach ($params as $field => $newparams) {
461 if ((is_array($newparams) ||
$newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
463 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
464 if ($newparams === 1) {
465 $newparams = array('version' => $version);
467 // can be api_ or api.
468 $separator = $field[3];
469 if (!($separator == '.' ||
$separator == '_')) {
472 $subAPI = explode($separator, $field);
474 $subaction = empty($subAPI[2]) ?
$action : $subAPI[2];
476 'debug' => CRM_Utils_Array
::value('debug', $params),
478 $subEntity = $subAPI[1];
480 foreach ($result['values'] as $idIndex => $parentAPIValues) {
482 if (strtolower($subEntity) != 'contact') {
483 //contact spits the dummy at activity_id so what else won't it like?
484 //set entity_id & entity table based on the parent's id & entity. e.g for something like
485 //note if the parent call is contact 'entity_table' will be set to 'contact' & 'id' to the contact id from
487 //in this case 'contact_id' will also be set to the parent's id
488 $subParams["entity_id"] = $parentAPIValues['id'];
489 $subParams['entity_table'] = 'civicrm_' . _civicrm_api_get_entity_name_from_camel($entity);
490 $subParams[strtolower($entity) . "_id"] = $parentAPIValues['id'];
492 if (strtolower($entity) != 'contact' && CRM_Utils_Array
::value(strtolower($subEntity . "_id"), $parentAPIValues)) {
493 //e.g. if event_id is in the values returned & subentity is event then pass in event_id as 'id'
494 //don't do this for contact as it does some wierd things like returning primary email &
495 //thus limiting the ability to chain email
496 //TODO - this might need the camel treatment
497 $subParams['id'] = $parentAPIValues[$subEntity . "_id"];
500 if (CRM_Utils_Array
::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
501 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
503 // if we are dealing with the same entity pass 'id' through (useful for get + delete for example)
504 if (strtolower($entity) == strtolower($subEntity)) {
505 $subParams['id'] = $result['values'][$idIndex]['id'];
509 $subParams['version'] = $version;
510 if(!empty($params['check_permissions'])){
511 $subParams['check_permissions'] = $params['check_permissions'];
513 $subParams['sequential'] = 1;
514 $subParams['api.has_parent'] = 1;
515 if (array_key_exists(0, $newparams)) {
516 $genericParams = $subParams;
517 // it is a numerically indexed array - ie. multiple creates
518 foreach ($newparams as $entityparams) {
519 $subParams = array_merge($genericParams, $entityparams);
520 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
521 $result['values'][$result['id']][$field][] = civicrm_api($subEntity, $subaction, $subParams);
522 if ($result['is_error'] === 1) {
523 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
529 $subParams = array_merge($subParams, $newparams);
530 _civicrm_api_replace_variables($subAPI[1], $subaction, $subParams, $result['values'][$idIndex], $separator);
531 $result['values'][$idIndex][$field] = civicrm_api($subEntity, $subaction, $subParams);
532 if (!empty($result['is_error'])) {
533 throw new Exception($subEntity . ' ' . $subaction . 'call failed with' . $result['error_message']);
539 if(strtolower($action) == 'getsingle'){
540 $result = $result['values'][0];
545 * Swap out any $values vars - ie. the value after $value is swapped for the parent $result
546 * 'activity_type_id' => '$value.testfield',
547 'tag_id' => '$value.api.tag.create.id',
548 'tag1_id' => '$value.api.entity.create.0.id'
550 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
553 foreach ($params as $field => $value) {
555 if (is_string($value) && substr($value, 0, 6) == '$value') {
556 $valuesubstitute = substr($value, 7);
558 if (!empty($parentResult[$valuesubstitute])) {
559 $params[$field] = $parentResult[$valuesubstitute];
563 $stringParts = explode($separator, $value);
564 unset($stringParts[0]);
566 $fieldname = array_shift($stringParts);
568 //when our string is an array we will treat it as an array from that . onwards
569 $count = count($stringParts);
571 $fieldname .= "." . array_shift($stringParts);
572 if (array_key_exists($fieldname, $parentResult) && is_array($parentResult[$fieldname])) {
573 $arrayLocation = $parentResult[$fieldname];
574 foreach ($stringParts as $key => $value) {
575 $arrayLocation = CRM_Utils_Array
::value($value, $arrayLocation);
577 $params[$field] = $arrayLocation;
579 $count = count($stringParts);
587 * Convert possibly camel name to underscore separated entity name
589 * @param string $entity entity name in various formats e.g. Contribution, contribution, OptionValue, option_value, UFJoin, uf_join
590 * @return string $entity entity name in underscore separated format
592 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
594 function _civicrm_api_get_entity_name_from_camel($entity) {
595 if ($entity == strtolower($entity)) {
599 $entity = ltrim(strtolower(str_replace('U_F',
601 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
602 preg_replace('/(?=[A-Z])/', '_$0', $entity)
609 * Having a DAO object find the entity name
610 * @param object $bao DAO being passed in
613 function _civicrm_api_get_entity_name_from_dao($bao){
614 $daoName = str_replace("BAO", "DAO", get_class($bao));
615 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName));
619 * Sets the tsLocale and dbLocale for multi-lingual sites.
620 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
621 * to avoid regressions from refactoring.
623 function _civicrm_api_set_locale($lcMessagesRequest) {
624 // We must validate whether the locale is valid, otherwise setting a bad
625 // dbLocale could probably lead to sql-injection.
626 $domain = new CRM_Core_DAO_Domain();
627 $domain->id
= CRM_Core_Config
::domainID();
630 if ($domain->config_backend
) {
631 $defaults = unserialize($domain->config_backend
);
633 // are we in a multi-language setup?
634 $multiLang = $domain->locales ?
TRUE : FALSE;
637 // on multi-lang sites based on request and civicrm_uf_match
639 $languageLimit = array();
640 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
641 $languageLimit = $defaults['languageLimit'];
644 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
645 $lcMessages = $lcMessagesRequest;
648 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
654 // set suffix for table names - use views if more than one language
656 $dbLocale = $multiLang && $lcMessages ?
"_{$lcMessages}" : '';
658 // FIXME: an ugly hack to fix CRM-4041
660 $tsLocale = $lcMessages;