fix error to throw Exception
[civicrm-core.git] / api / api.php
CommitLineData
6a488035
TO
1<?php
2
3/**
4 * File for the CiviCRM APIv3 API wrapper
5 *
6 * @package CiviCRM_APIv3
7 * @subpackage API
8 *
9 * @copyright CiviCRM LLC (c) 2004-2013
10 * @version $Id: api.php 30486 2010-11-02 16:12:09Z shot $
11 */
12
11e09c59 13/**
6a488035
TO
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
20 */
21function civicrm_api($entity, $action, $params, $extra = NULL) {
5270c026
XD
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;
28
a9396478
TO
29 $apiWrappers = array(
30 CRM_Utils_API_HTMLInputCoder::singleton(),
0e4d4398 31 CRM_Utils_API_NullOutputCoder::singleton(),
ac830223 32 CRM_Utils_API_ReloadOption::singleton(),
c8463688 33 CRM_Utils_API_MatchOption::singleton(),
a9396478 34 );
5270c026
XD
35 CRM_Utils_Hook::apiWrappers($apiWrappers,$apiRequest);
36
6a488035
TO
37 try {
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);
42 }
43 _civicrm_api3_initialize();
44 $errorScope = CRM_Core_TemporaryErrorScope::useException();
6a488035
TO
45 // look up function, file, is_generic
46 $apiRequest += _civicrm_api_resolve($apiRequest);
db1791f7 47 if (strtolower($action) == 'create' || strtolower($action) == 'delete' || strtolower($action) == 'submit') {
6a488035
TO
48 $apiRequest['is_transactional'] = 1;
49 $transaction = new CRM_Core_Transaction();
50 }
51
91cd40ea
ML
52 // support multi-lingual requests
53 if ($language = CRM_Utils_Array::value('option.language', $params)) {
54 _civicrm_api_set_locale($language);
55 }
56
6a488035 57 _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
94359f7e 58 $fields = _civicrm_api3_api_getfields($apiRequest);
6a488035 59 // we do this before we
94359f7e 60 _civicrm_api3_swap_out_aliases($apiRequest, $fields);
6a488035 61 if (strtolower($action) != 'getfields') {
9ec90e57 62 if (!CRM_Utils_Array::value('id', $apiRequest['params'])) {
94359f7e 63 $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']);
6a488035
TO
64 }
65 //if 'id' is set then only 'version' will be checked but should still be checked for consistency
94359f7e 66 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields));
6a488035
TO
67 }
68
a9396478 69 // For input filtering, process $apiWrappers in forward order
6a488035
TO
70 foreach ($apiWrappers as $apiWrapper) {
71 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
72 }
73
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);
80 }
81 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
94359f7e 82 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
6a488035
TO
83
84 $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
85 }
86 else {
87 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . "," . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
88 }
89
a9396478
TO
90 // For output filtering, process $apiWrappers in reverse order
91 foreach (array_reverse($apiWrappers) as $apiWrapper) {
6a488035
TO
92 $result = $apiWrapper->toApiOutput($apiRequest, $result);
93 }
94
95 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
96 if ($result['is_error'] === 0) {
97 return 1;
98 }
99 else {
100 return 0;
101 }
102 }
103 if (CRM_Utils_Array::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
104 return $result['id'];
105 }
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']);
108 }
109 if (function_exists('xdebug_time_index')
110 && CRM_Utils_Array::value('debug', $apiRequest['params'])
111 // result would not be an array for getvalue
112 && is_array($result)
113 ) {
114 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
115 $result['xdebug']['memory'] = xdebug_memory_usage();
116 $result['xdebug']['timeIndex'] = xdebug_time_index();
117 }
118
119 return $result;
120 }
121 catch(PEAR_Exception $e) {
122 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
123 return 0;
124 }
c56bd790
XD
125 $error = $e->getCause();
126 if ($error instanceof DB_Error) {
127 $data["error_code"] = DB::errorMessage($error->getCode());
128 $data["sql"] = $error->getDebugInfo();
129 }
6a488035 130 if (CRM_Utils_Array::value('debug', $apiRequest['params'])) {
9aeec998 131 if(method_exists($e, 'getUserInfo')) {
132 $data['debug_info'] = $error->getUserInfo();
133 }
134 if(method_exists($e, 'getExtraData')) {
135 $data['debug_info'] = $data + $error->getExtraData();
136 }
6a488035
TO
137 $data['trace'] = $e->getTraceAsString();
138 }
139 else{
140 $data['tip'] = "add debug=1 to your API call to have more info about the error";
141 }
142 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
143 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
144 $transaction->rollback();
145 }
146 return $err;
147 }
148 catch (API_Exception $e){
149 if(!isset($apiRequest)){
150 $apiRequest = array();
151 }
152 if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params',$apiRequest)) == 1) {
153 return 0;
154 }
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
161 ) {
162 $err['trace'] = $e->getTraceAsString();
163 }
164 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
165 $transaction->rollback();
166 }
167 return $err;
168 }
169 catch(Exception $e) {
170 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
171 return 0;
172 }
173 $data = array();
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();
177 }
178 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
179 $transaction->rollback();
180 }
181 return $err;
182 }
183}
184
185/**
186 * Look up the implementation for a given API request
187 *
188 * @param $apiRequest array with keys:
189 * - entity: string, required
190 * - action: string, required
191 * - params: array
192 * - version: scalar, required
193 *
194 * @return array with keys
195 * - function: callback (mixed)
196 * - is_generic: boolean
197 */
198function _civicrm_api_resolve($apiRequest) {
199 static $cache;
200 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
201 if (isset($cache[$cachekey])) {
202 return $cache[$cachekey];
203 }
204
205 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
206 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
207
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];
215 }
216
217 $stdFiles = array(
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',
221 );
222 foreach ($stdFiles as $stdFile) {
6a488035
TO
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];
228 }
229 }
230 }
231
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',
240 );
241 foreach ($genericFiles as $genericFile) {
6a488035
TO
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];
247 }
248 }
249 }
250
251 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
252 return $cache[$cachekey];
253}
6b359437 254/**
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
259 *
260 * @return array
261 *
262 */
c4ac4df4 263function civicrm_api3($entity, $action, $params) {
6b359437 264 $params['version'] = 3;
265 $result = civicrm_api($entity, $action, $params);
d661281d 266 if(is_array($result) && !empty($result['is_error'])){
6b359437 267 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
268 }
c4ac4df4 269 return $result;
6b359437 270}
6a488035 271
94359f7e 272/**
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.
275 *
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
278 *
279 * @todo other output modifiers include contact_type
280 *
281 * @param array $apiRequest
282 * @return getfields output
283 */
284function _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']);
291 }
292 return array('action' => array('api_aliases' => array('action')));
293 }
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'];
298 }
299 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
300 return $fields['values'];
301}
6a488035
TO
302/**
303 * Load/require all files related to an entity.
304 *
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").
307 *
308 * @param string $entity
309 * @return void
310 */
311function _civicrm_api_loadEntity($entity, $version = 3) {
312 /*
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);
319 */
320
321 $camelName = _civicrm_api_get_camel_name($entity, $version);
322
323 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
6a488035
TO
324 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
325 if (CRM_Utils_File::isIncludable($stdFile)) {
326 require_once $stdFile;
327 }
328
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)) {
335 continue;
336 }
337
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
343 }
344
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;
349 }
350 }
351 }
352}
353
354/**
355 *
356 * @deprecated
357 */
358function civicrm_api_get_function_name($entity, $action, $version = NULL) {
359
360 if (empty($version)) {
361 $version = civicrm_get_api_version();
362 }
363
364 $entity = _civicrm_api_get_entity_name_from_camel($entity);
365 return 'civicrm_api3' . '_' . $entity . '_' . $action;
366}
367
368/**
369 * We must be sure that every request uses only one version of the API.
370 *
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.
376 */
377function civicrm_get_api_version($desired_version = NULL) {
378
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'];
383 }
384 if (isset($desired_version) && is_integer($desired_version)) {
385 $_version = $desired_version;
386 }
387 else {
388 // we will set the default to version 3 as soon as we find that it works.
389 $_version = 3;
390 }
391 return $_version;
392}
393
394/**
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.
399 *
400 * @param array $params (reference ) input parameters
401 *
402 * @return boolean true if error, false otherwise
403 * @static void
404 * @access public
405 */
406function civicrm_error($result) {
407 if (is_array($result)) {
408 return (array_key_exists('is_error', $result) &&
409 $result['is_error']
410 ) ? TRUE : FALSE;
411 }
412 return FALSE;
413}
414
415function _civicrm_api_get_camel_name($entity, $version = NULL) {
6a488035
TO
416 if (empty($version)) {
417 $version = civicrm_get_api_version();
418 }
419
6a488035
TO
420 $fragments = explode('_', $entity);
421 foreach ($fragments as & $fragment) {
422 $fragment = ucfirst($fragment);
423 }
424 // Special case: UFGroup, UFJoin, UFMatch, UFField
425 if ($fragments[0] === 'Uf') {
426 $fragments[0] = 'UF';
427 }
428 return implode('', $fragments);
429}
430
11e09c59 431/**
6a488035
TO
432 * Call any nested api calls
433 */
434function _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));
442 }
443 foreach ($params as $field => $newparams) {
444 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
445
446 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
447 if ($newparams === 1) {
448 $newparams = array('version' => $version);
449 }
450 // can be api_ or api.
451 $separator = $field[3];
452 if (!($separator == '.' || $separator == '_')) {
453 continue;
454 }
455 $subAPI = explode($separator, $field);
456
457 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
458 $subParams = array(
459 'debug' => CRM_Utils_Array::value('debug', $params),
460 );
461 $subEntity = $subAPI[1];
462
463 foreach ($result['values'] as $idIndex => $parentAPIValues) {
464
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
469 //the parent call.
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'];
474 }
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"];
481 }
482
483 if (CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
484 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
485 }
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'];
489 }
490
491
492 $subParams['version'] = $version;
493 if(!empty($params['check_permissions'])){
494 $subParams['check_permissions'] = $params['check_permissions'];
495 }
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']);
506 }
507 }
508 }
509 else {
510
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']);
516 }
517 }
518 }
519 }
520 }
521 if(strtolower($action) == 'getsingle'){
522 $result = $result['values'][0];
523 }
524}
525
11e09c59 526/**
6a488035
TO
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'
531 */
532function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
533
534
535 foreach ($params as $field => $value) {
536
537 if (is_string($value) && substr($value, 0, 6) == '$value') {
538 $valuesubstitute = substr($value, 7);
539
540 if (!empty($parentResult[$valuesubstitute])) {
541 $params[$field] = $parentResult[$valuesubstitute];
542 }
543 else {
544
545 $stringParts = explode($separator, $value);
546 unset($stringParts[0]);
547
548 $fieldname = array_shift($stringParts);
549
550 //when our string is an array we will treat it as an array from that . onwards
551 $count = count($stringParts);
552 while ($count > 0) {
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);
558 }
559 $params[$field] = $arrayLocation;
560 }
561 $count = count($stringParts);
562 }
563 }
564 }
565 }
566}
567
11e09c59 568/**
6a488035
TO
569 * Convert possibly camel name to underscore separated entity name
570 *
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
47e6af81
CW
573 *
574 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
6a488035
TO
575 */
576function _civicrm_api_get_entity_name_from_camel($entity) {
577 if ($entity == strtolower($entity)) {
578 return $entity;
579 }
580 else {
581 $entity = ltrim(strtolower(str_replace('U_F',
582 'uf',
583 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
584 preg_replace('/(?=[A-Z])/', '_$0', $entity)
585 )), '_');
586 }
587 return $entity;
588}
11e09c59
TO
589
590/**
6a488035
TO
591 * Having a DAO object find the entity name
592 * @param object $bao DAO being passed in
593 */
594function _civicrm_api_get_entity_name_from_dao($bao){
595 $daoName = str_replace("BAO", "DAO", get_class($bao));
edc091f1 596 return _civicrm_api_get_entity_name_from_camel(CRM_Core_DAO_AllCoreTables::getBriefName($daoName));
6a488035
TO
597}
598
91cd40ea
ML
599/**
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.
603 */
604function _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();
609 $domain->find(TRUE);
610
611 if ($domain->config_backend) {
612 $defaults = unserialize($domain->config_backend);
613
614 // are we in a multi-language setup?
615 $multiLang = $domain->locales ? TRUE : FALSE;
616 $lcMessages = NULL;
617
618 // on multi-lang sites based on request and civicrm_uf_match
619 if ($multiLang) {
620 $languageLimit = array();
621 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
622 $languageLimit = $defaults['languageLimit'];
623 }
624
625 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
626 $lcMessages = $lcMessagesRequest;
627 }
628 else {
629 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
630 }
631 }
632
633 global $dbLocale;
634
635 // set suffix for table names - use views if more than one language
636 if ($lcMessages) {
637 $dbLocale = $multiLang && $lcMessages ? "_{$lcMessages}" : '';
638
639 // FIXME: an ugly hack to fix CRM-4041
640 global $tsLocale;
641 $tsLocale = $lcMessages;
642 }
643 }
644}