Merge pull request #3490 from civicrm/CRM-14842
[civicrm-core.git] / api / api.php
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
13 /**
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 * @param null $extra
21 *
22 * @return array|int
23 */
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;
31
32 $apiWrappers = array(
33 CRM_Utils_API_HTMLInputCoder::singleton(),
34 CRM_Utils_API_NullOutputCoder::singleton(),
35 CRM_Utils_API_ReloadOption::singleton(),
36 CRM_Utils_API_MatchOption::singleton(),
37 );
38 CRM_Utils_Hook::apiWrappers($apiWrappers,$apiRequest);
39
40 try {
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);
45 }
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();
54 }
55
56 // support multi-lingual requests
57 if ($language = CRM_Utils_Array::value('option.language', $params)) {
58 _civicrm_api_set_locale($language);
59 }
60
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']);
68 }
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));
71 }
72
73 // For input filtering, process $apiWrappers in forward order
74 foreach ($apiWrappers as $apiWrapper) {
75 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
76 }
77
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);
84 }
85 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
86 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
87
88 $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
89 }
90 else {
91 return civicrm_api3_create_error("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
92 }
93
94 // For output filtering, process $apiWrappers in reverse order
95 foreach (array_reverse($apiWrappers) as $apiWrapper) {
96 $result = $apiWrapper->toApiOutput($apiRequest, $result);
97 }
98
99 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
100 if ($result['is_error'] === 0) {
101 return 1;
102 }
103 else {
104 return 0;
105 }
106 }
107 if (CRM_Utils_Array::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
108 return $result['id'];
109 }
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']);
112 }
113 if (function_exists('xdebug_time_index')
114 && CRM_Utils_Array::value('debug', $apiRequest['params'])
115 // result would not be an array for getvalue
116 && is_array($result)
117 ) {
118 $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
119 $result['xdebug']['memory'] = xdebug_memory_usage();
120 $result['xdebug']['timeIndex'] = xdebug_time_index();
121 }
122
123 return $result;
124 }
125 catch(PEAR_Exception $e) {
126 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
127 return 0;
128 }
129 $error = $e->getCause();
130 if ($error instanceof DB_Error) {
131 $data["error_code"] = DB::errorMessage($error->getCode());
132 $data["sql"] = $error->getDebugInfo();
133 }
134 if (CRM_Utils_Array::value('debug', $apiRequest['params'])) {
135 if(method_exists($e, 'getUserInfo')) {
136 $data['debug_info'] = $error->getUserInfo();
137 }
138 if(method_exists($e, 'getExtraData')) {
139 $data['debug_info'] = $data + $error->getExtraData();
140 }
141 $data['trace'] = $e->getTraceAsString();
142 }
143 else{
144 $data['tip'] = "add debug=1 to your API call to have more info about the error";
145 }
146 $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
147 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
148 $transaction->rollback();
149 }
150 return $err;
151 }
152 catch (API_Exception $e){
153 if(!isset($apiRequest)){
154 $apiRequest = array();
155 }
156 if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params',$apiRequest)) == 1) {
157 return 0;
158 }
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
165 ) {
166 $err['trace'] = $e->getTraceAsString();
167 }
168 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
169 $transaction->rollback();
170 }
171 return $err;
172 }
173 catch(Exception $e) {
174 if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
175 return 0;
176 }
177 $data = array();
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();
181 }
182 if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
183 $transaction->rollback();
184 }
185 return $err;
186 }
187 }
188
189 /**
190 * Look up the implementation for a given API request
191 *
192 * @param $apiRequest array with keys:
193 * - entity: string, required
194 * - action: string, required
195 * - params: array
196 * - version: scalar, required
197 *
198 * @return array with keys
199 * - function: callback (mixed)
200 * - is_generic: boolean
201 */
202 function _civicrm_api_resolve($apiRequest) {
203 static $cache;
204 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
205 if (isset($cache[$cachekey])) {
206 return $cache[$cachekey];
207 }
208
209 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
210 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
211
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];
219 }
220
221 $stdFiles = array(
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',
225 );
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];
232 }
233 }
234 }
235
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',
244 );
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];
251 }
252 }
253 }
254
255 $cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
256 return $cache[$cachekey];
257 }
258
259 /**
260 * Version 3 wrapper for civicrm_api. Throws exception
261 *
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
265 *
266 * @throws CiviCRM_API3_Exception
267 * @return array
268 */
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);
274 }
275 return $result;
276 }
277
278 /**
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.
281 *
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
284 *
285 * @todo other output modifiers include contact_type
286 *
287 * @param array $apiRequest
288 * @return getfields output
289 */
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']);
297 }
298 return array('action' => array('api.aliases' => array('api_action')));
299 }
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'];
304 }
305 $fields = civicrm_api3($entity, 'getfields', $getFieldsParams);
306 return $fields['values'];
307 }
308
309 /**
310 * Load/require all files related to an entity.
311 *
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").
314 *
315 * @param string $entity
316 * @param int $version
317 *
318 * @return void
319 */
320 function _civicrm_api_loadEntity($entity, $version = 3) {
321 /*
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);
328 */
329
330 $camelName = _civicrm_api_get_camel_name($entity, $version);
331
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;
336 }
337
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)) {
344 continue;
345 }
346
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
352 }
353
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;
358 }
359 }
360 }
361 }
362
363 /**
364 *
365 * @deprecated
366 */
367 function civicrm_api_get_function_name($entity, $action, $version = NULL) {
368
369 if (empty($version)) {
370 $version = civicrm_get_api_version();
371 }
372
373 $entity = _civicrm_api_get_entity_name_from_camel($entity);
374 return 'civicrm_api3' . '_' . $entity . '_' . $action;
375 }
376
377 /**
378 * We must be sure that every request uses only one version of the API.
379 *
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.
385 * @return int
386 */
387 function civicrm_get_api_version($desired_version = NULL) {
388
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'];
393 }
394 if (isset($desired_version) && is_integer($desired_version)) {
395 $_version = $desired_version;
396 }
397 else {
398 // we will set the default to version 3 as soon as we find that it works.
399 $_version = 3;
400 }
401 return $_version;
402 }
403
404 /**
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.
409 *
410 * @param $result
411 *
412 * @internal param array $params (reference ) input parameters
413 *
414 * @return boolean true if error, false otherwise
415 * @static void
416 * @access public
417 */
418 function civicrm_error($result) {
419 if (is_array($result)) {
420 return (array_key_exists('is_error', $result) &&
421 $result['is_error']
422 ) ? TRUE : FALSE;
423 }
424 return FALSE;
425 }
426
427 function _civicrm_api_get_camel_name($entity, $version = NULL) {
428 if (empty($version)) {
429 $version = civicrm_get_api_version();
430 }
431
432 $fragments = explode('_', $entity);
433 foreach ($fragments as & $fragment) {
434 $fragment = ucfirst($fragment);
435 }
436 // Special case: UFGroup, UFJoin, UFMatch, UFField
437 if ($fragments[0] === 'Uf') {
438 $fragments[0] = 'UF';
439 }
440 return implode('', $fragments);
441 }
442
443 /**
444 * Call any nested api calls
445 */
446 function _civicrm_api_call_nested_api(&$params, &$result, $action, $entity, $version) {
447 $entity = _civicrm_api_get_entity_name_from_camel($entity);
448
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'))) {
451 return;
452 }
453
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));
460 }
461 foreach ($params as $field => $newparams) {
462 if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
463
464 // 'api.participant.delete' => 1 is a valid options - handle 1 instead of an array
465 if ($newparams === 1) {
466 $newparams = array('version' => $version);
467 }
468 // can be api_ or api.
469 $separator = $field[3];
470 if (!($separator == '.' || $separator == '_')) {
471 continue;
472 }
473 $subAPI = explode($separator, $field);
474
475 $subaction = empty($subAPI[2]) ? $action : $subAPI[2];
476 $subParams = array(
477 'debug' => CRM_Utils_Array::value('debug', $params),
478 );
479 $subEntity = $subAPI[1];
480
481 foreach ($result['values'] as $idIndex => $parentAPIValues) {
482
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
487 //the parent call.
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'];
492 }
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"];
499 }
500
501 if (CRM_Utils_Array::value('entity_table', $result['values'][$idIndex]) == $subEntity) {
502 $subParams['id'] = $result['values'][$idIndex]['entity_id'];
503 }
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'];
507 }
508
509
510 $subParams['version'] = $version;
511 if(!empty($params['check_permissions'])){
512 $subParams['check_permissions'] = $params['check_permissions'];
513 }
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']);
525 }
526 }
527 }
528 else {
529
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']);
535 }
536 }
537 }
538 }
539 }
540 if(strtolower($action) == 'getsingle'){
541 $result = $result['values'][0];
542 }
543 }
544
545 /**
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'
550 */
551 function _civicrm_api_replace_variables($entity, $action, &$params, &$parentResult, $separator = '.') {
552
553
554 foreach ($params as $field => $value) {
555
556 if (is_string($value) && substr($value, 0, 6) == '$value') {
557 $valuesubstitute = substr($value, 7);
558
559 if (!empty($parentResult[$valuesubstitute])) {
560 $params[$field] = $parentResult[$valuesubstitute];
561 }
562 else {
563
564 $stringParts = explode($separator, $value);
565 unset($stringParts[0]);
566
567 $fieldname = array_shift($stringParts);
568
569 //when our string is an array we will treat it as an array from that . onwards
570 $count = count($stringParts);
571 while ($count > 0) {
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);
577 }
578 $params[$field] = $arrayLocation;
579 }
580 $count = count($stringParts);
581 }
582 }
583 }
584 }
585 }
586
587 /**
588 * Convert possibly camel name to underscore separated entity name
589 *
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
592 *
593 * FIXME: Why isn't this called first thing in civicrm_api wrapper?
594 */
595 function _civicrm_api_get_entity_name_from_camel($entity) {
596 if ($entity == strtolower($entity)) {
597 return $entity;
598 }
599 else {
600 $entity = ltrim(strtolower(str_replace('U_F',
601 'uf',
602 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
603 preg_replace('/(?=[A-Z])/', '_$0', $entity)
604 )), '_');
605 }
606 return $entity;
607 }
608
609 /**
610 * Having a DAO object find the entity name
611 * @param object $bao DAO being passed in
612 * @return string
613 */
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));
617 }
618
619 /**
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.
623 */
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();
629 $domain->find(TRUE);
630
631 if ($domain->config_backend) {
632 $defaults = unserialize($domain->config_backend);
633
634 // are we in a multi-language setup?
635 $multiLang = $domain->locales ? TRUE : FALSE;
636 $lcMessages = NULL;
637
638 // on multi-lang sites based on request and civicrm_uf_match
639 if ($multiLang) {
640 $languageLimit = array();
641 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
642 $languageLimit = $defaults['languageLimit'];
643 }
644
645 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
646 $lcMessages = $lcMessagesRequest;
647 }
648 else {
649 throw new API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
650 }
651 }
652
653 global $dbLocale;
654
655 // set suffix for table names - use views if more than one language
656 if ($lcMessages) {
657 $dbLocale = $multiLang && $lcMessages ? "_{$lcMessages}" : '';
658
659 // FIXME: an ugly hack to fix CRM-4041
660 global $tsLocale;
661 $tsLocale = $lcMessages;
662 }
663 }
664 }