4 * File for the CiviCRM APIv3 API wrapper
6 * @package CiviCRM_APIv3
9 * @copyright CiviCRM LLC (c) 2004-2014
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 return \Civi\Core\Container
::singleton()->get('civi_api_kernel')->run($entity, $action, $params, $extra);
29 * Look up the implementation for a given API request
31 * @param $apiRequest array with keys:
32 * - entity: string, required
33 * - action: string, required
35 * - version: scalar, required
37 * @return array with keys
38 * - function: callback (mixed)
39 * - is_generic: boolean
41 function _civicrm_api_resolve($apiRequest) {
43 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
44 if (isset($cache[$cachekey])) {
45 return $cache[$cachekey];
48 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
49 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
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];
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',
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];
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',
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];
94 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
95 return $cache[$cachekey];
99 * Version 3 wrapper for civicrm_api. Throws exception
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
105 * @throws CiviCRM_API3_Exception
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);
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.
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
124 * @todo other output modifiers include contact_type
126 * @param array $apiRequest
127 * @return getfields output
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']);
137 return array('action' => array('api.aliases' => array('api_action')));
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'];
144 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
145 return $fields['values'];
149 * Load/require all files related to an entity.
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").
154 * @param string $entity
155 * @param int $version
159 function _civicrm_api_loadEntity($entity, $version = 3) {
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);
169 $camelName = _civicrm_api_get_camel_name($entity, $version);
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;
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)) {
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
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;
206 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
208 if (empty($version)) {
209 $version = civicrm_get_api_version();
212 $entity = _civicrm_api_get_entity_name_from_camel($entity);
213 return 'civicrm_api3' . '_' . $entity . '_' . $action;
217 * We must be sure that every request uses only one version of the API.
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.
226 function civicrm_get_api_version($desired_version = NULL) {
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'];
233 if (isset($desired_version) && is_integer($desired_version)) {
234 $_version = $desired_version;
237 // we will set the default to version 3 as soon as we find that it works.
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.
251 * @internal param array $params (reference ) input parameters
253 * @return boolean true if error, false otherwise
257 function civicrm_error($result) {
258 if (is_array($result)) {
259 return (array_key_exists('is_error', $result) &&
266 function _civicrm_api_get_camel_name($entity, $version = NULL) {
267 if (empty($version)) {
268 $version = civicrm_get_api_version();
271 $fragments = explode('_', $entity);
272 foreach ($fragments as & $fragment) {
273 $fragment = ucfirst($fragment);
275 // Special case: UFGroup, UFJoin, UFMatch, UFField
276 if ($fragments[0] === 'Uf') {
277 $fragments[0] = 'UF';
279 return implode('', $fragments);
283 * Call any nested api calls
285 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
286 $entity = _civicrm_api_get_entity_name_from_camel($entity);
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'))) {
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));
300 foreach ($params as $field => $newparams) {
301 if ((is_array($newparams) ||
$newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
303 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
304 if ($newparams === 1) {
305 $newparams = array('version' => $version);
307 // can be api_ or api.
308 $separator = $field[3];
309 if (!($separator == '.' ||
$separator == '_')) {
312 $subAPI = explode($separator, $field);
314 $subaction = empty($subAPI[2]) ?
$action : $subAPI[2];
316 'debug' => CRM_Utils_Array
::value('debug', $params),
318 $subEntity = $subAPI[1];
320 foreach ($result['values'] as $idIndex => $parentAPIValues) {
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
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'];
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"];
340 if (CRM_Utils_Array
::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
341 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
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'];
349 $subParams['version'] = $version;
350 if(!empty($params['check_permissions'])){
351 $subParams['check_permissions'] = $params['check_permissions'];
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']);
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']);
379 if(strtolower($action) == 'getsingle'){
380 $result = $result['values'][0];
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'
390 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
393 foreach ($params as $field => $value) {
395 if (is_string($value) && substr($value, 0, 6) == '$value') {
396 $valuesubstitute = substr($value, 7);
398 if (!empty($parentResult[$valuesubstitute])) {
399 $params[$field] = $parentResult[$valuesubstitute];
403 $stringParts = explode($separator, $value);
404 unset($stringParts[0]);
406 $fieldname = array_shift($stringParts);
408 //when our string is an array we will treat it as an array from that . onwards
409 $count = count($stringParts);
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);
417 $params[$field] = $arrayLocation;
419 $count = count($stringParts);
427 * Convert possibly camel name to underscore separated entity name
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
432 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
434 function _civicrm_api_get_entity_name_from_camel($entity) {
435 if ($entity == strtolower($entity)) {
439 $entity = ltrim(strtolower(str_replace('U_F',
441 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
442 preg_replace('/(?=[A-Z])/', '_$0', $entity)
449 * Having a DAO object find the entity name
450 * @param object $bao DAO being passed in
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));
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.
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();
470 if ($domain->config_backend
) {
471 $defaults = unserialize($domain->config_backend
);
473 // are we in a multi-language setup?
474 $multiLang = $domain->locales ?
TRUE : FALSE;
477 // on multi-lang sites based on request and civicrm_uf_match
479 $languageLimit = array();
480 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
481 $languageLimit = $defaults['languageLimit'];
484 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
485 $lcMessages = $lcMessagesRequest;
488 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
494 // set suffix for table names - use views if more than one language
496 $dbLocale = $multiLang && $lcMessages ?
"_{$lcMessages}" : '';
498 // FIXME: an ugly hack to fix CRM-4041
500 $tsLocale = $lcMessages;