Merge pull request #22689 from colemanw/removeCiviMailVar
[civicrm-core.git] / CRM / Core / I18n.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_I18n {
18
19 /**
20 * Constants for communication preferences.
21 *
22 * @var string
23 */
24 const NONE = 'none', AUTO = 'auto';
25
26 /**
27 * @var callable|null
28 * A callback function which handles SQL string encoding.
29 * Set NULL to use the default, CRM_Core_DAO::escapeString().
30 * This is used by `ts(..., [escape=>sql])`.
31 *
32 * This option is not intended for general consumption. It is only intended
33 * for certain pre-boot/pre-install contexts.
34 *
35 * You might ask, "Why on Earth does string-translation have an opinion on
36 * SQL escaping?" Good question!
37 */
38 public static $SQL_ESCAPER = NULL;
39
40 /**
41 * Escape a string if a mode is specified, otherwise return string unmodified.
42 *
43 * @param string $text
44 * @param string $mode
45 * @return string
46 */
47 protected static function escape($text, $mode) {
48 switch ($mode) {
49 case 'sql':
50 if (self::$SQL_ESCAPER == NULL) {
51 return CRM_Core_DAO::escapeString($text);
52 }
53 else {
54 return call_user_func(self::$SQL_ESCAPER, $text);
55 }
56
57 case 'js':
58 return substr(json_encode($text, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), 1, -1);
59 }
60 return $text;
61 }
62
63 /**
64 * A PHP-gettext instance for string translation;
65 * should stay null if the strings are not to be translated (en_US).
66 * @var object
67 */
68 private $_phpgettext = NULL;
69
70 /**
71 * Whether we are using native gettext or not.
72 * @var bool
73 */
74 private $_nativegettext = FALSE;
75
76 /**
77 * Gettext cache for extension domains/streamers, depending on if native or phpgettext.
78 * - native gettext: we cache the value for textdomain()
79 * - phpgettext: we cache the file streamer.
80 * @var array
81 */
82 private $_extensioncache = [];
83
84 /**
85 * @var string
86 */
87 private $locale;
88
89 /**
90 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
91 *
92 * @param string $locale
93 * the base of this certain object's existence.
94 *
95 * @return \CRM_Core_I18n
96 */
97 public function __construct($locale) {
98 $this->locale = $locale;
99 if ($locale != '' and $locale != 'en_US') {
100 if (defined('CIVICRM_GETTEXT_NATIVE') && CIVICRM_GETTEXT_NATIVE && function_exists('gettext')) {
101 // Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
102
103 $this->_nativegettext = TRUE;
104 $this->setNativeGettextLocale($locale);
105 return;
106 }
107
108 // Otherwise, use PHP-gettext
109 $this->setPhpGettextLocale($locale);
110 }
111 }
112
113 /**
114 * Returns whether gettext is running natively or using PHP-Gettext.
115 *
116 * @return bool
117 * True if gettext is native
118 */
119 public function isNative() {
120 return $this->_nativegettext;
121 }
122
123 /**
124 * Set native locale for getText.
125 *
126 * @param string $locale
127 */
128 protected function setNativeGettextLocale($locale) {
129
130 $locale .= '.utf8';
131 putenv("LANG=$locale");
132
133 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
134 setlocale(LC_TIME, $locale);
135 setlocale(LC_MESSAGES, $locale);
136 setlocale(LC_CTYPE, $locale);
137
138 bindtextdomain('civicrm', CRM_Core_I18n::getResourceDir());
139 bind_textdomain_codeset('civicrm', 'UTF-8');
140 textdomain('civicrm');
141
142 $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
143 $this->_extensioncache['civicrm'] = 'civicrm';
144
145 }
146
147 /**
148 * Set getText locale.
149 *
150 * @param string $locale
151 */
152 protected function setPhpGettextLocale($locale) {
153
154 // we support both the old file hierarchy format and the new:
155 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
156 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
157 require_once 'PHPgettext/streams.php';
158 require_once 'PHPgettext/gettext.php';
159
160 $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
161
162 if (!file_exists($mo_file)) {
163 // fallback to pre-4.5 mode
164 $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'civicrm.mo';
165 }
166
167 $streamer = new FileReader($mo_file);
168 $this->_phpgettext = new gettext_reader($streamer);
169 $this->_extensioncache['civicrm'] = $this->_phpgettext;
170
171 }
172
173 /**
174 * Return languages available in this instance of CiviCRM.
175 *
176 * @param bool $justEnabled
177 * whether to return all languages or just the enabled ones.
178 *
179 * @return array
180 * Array of code/language name mappings
181 */
182 public static function languages($justEnabled = FALSE) {
183 static $all = NULL;
184 static $enabled = NULL;
185
186 if (!$all) {
187 // Use `getValues`, not `buildOptions` to bypass hook_civicrm_fieldOptions. See core#1132.
188 CRM_Core_OptionValue::getValues(['name' => 'languages'], $optionValues, 'weight', TRUE);
189 $all = array_column($optionValues, 'label', 'name');
190
191 // FIXME: How is this not duplicative of the lines above?
192 // get labels
193 $rows = [];
194 $labels = [];
195 CRM_Core_OptionValue::getValues(['name' => 'languages'], $rows);
196 foreach ($rows as $id => $row) {
197 $labels[$row['name']] = $row['label'];
198 }
199
200 // check which ones are available; add them to $all if not there already
201 $codes = [];
202 if (is_dir(CRM_Core_I18n::getResourceDir()) && $dir = opendir(CRM_Core_I18n::getResourceDir())) {
203 while ($filename = readdir($dir)) {
204 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
205 $codes[] = $filename;
206 if (!isset($all[$filename])) {
207 $all[$filename] = $labels[$filename] ?? "($filename)";
208 }
209 }
210 }
211 closedir($dir);
212 }
213
214 // drop the unavailable languages (except en_US)
215 foreach (array_keys($all) as $code) {
216 if ($code == 'en_US') {
217 continue;
218 }
219 if (!in_array($code, $codes)) {
220 unset($all[$code]);
221 }
222 }
223
224 asort($all);
225 }
226
227 if ($enabled === NULL) {
228 $languageLimit = Civi::settings()->get('languageLimit');
229 $enabled = [];
230 if ($languageLimit) {
231 foreach ($all as $code => $name) {
232 if (array_key_exists($code, $languageLimit)) {
233 $enabled[$code] = $name;
234 }
235 }
236 }
237 }
238
239 return $justEnabled ? $enabled : $all;
240 }
241
242 /**
243 * Get the options available for format locale.
244 *
245 * Note the pseudoconstant can't be used as the key is the name not the value.
246 *
247 * @return array
248 */
249 public static function getFormatLocales(): array {
250 $values = CRM_Core_OptionValue::getValues(['name' => 'languages'], $optionValues, 'label', TRUE);
251 $return = [];
252 $return[NULL] = ts('Inherit from language');
253 foreach ($values as $value) {
254 $return[$value['name']] = $value['label'];
255 }
256 // Sorry not sorry.
257 // Hacking in for now since the is probably the most important use-case for
258 // money formatting in an English speaking non-US locale based on any reasonable
259 // metric.
260 $return['en_NZ'] = ts('English (New Zealand)');
261 return $return;
262 }
263
264 /**
265 * Return the available UI languages
266 * @return array|string
267 * array(string languageCode => string languageName) if !$justCodes
268 */
269 public static function uiLanguages($justCodes = FALSE) {
270 // In multilang we only allow the languages that are configured in db
271 // Otherwise, the languages configured in uiLanguages
272 $settings = Civi::settings();
273 if (CRM_Core_I18n::isMultiLingual()) {
274 $codes = array_keys((array) $settings->get('languageLimit'));
275 }
276 else {
277 $codes = $settings->get('uiLanguages');
278 if (!$codes) {
279 $codes = [$settings->get('lcMessages')];
280 }
281 }
282 return $justCodes ? $codes
283 : CRM_Utils_Array::subset(CRM_Core_I18n::languages(), $codes);
284 }
285
286 /**
287 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
288 *
289 * @param string $str
290 * source string.
291 *
292 * @return string
293 * modified string
294 */
295 public function strarg($str) {
296 $tr = [];
297 $p = 0;
298 for ($i = 1; $i < func_num_args(); $i++) {
299 $arg = func_get_arg($i);
300 if (is_array($arg)) {
301 foreach ($arg as $aarg) {
302 $tr['%' . ++$p] = $aarg;
303 }
304 }
305 else {
306 $tr['%' . ++$p] = $arg;
307 }
308 }
309 return strtr($str, $tr);
310 }
311
312 /**
313 * Get the directory for l10n resources.
314 *
315 * @return string
316 */
317 public static function getResourceDir() {
318 return CRM_Utils_File::addTrailingSlash(\Civi::paths()->getPath('[civicrm.l10n]/.'));
319 }
320
321 /**
322 * Smarty block function, provides gettext support for smarty.
323 *
324 * The block content is the text that should be translated.
325 *
326 * Any parameter that is sent to the function will be represented as %n in the translation text,
327 * where n is 1 for the first parameter. The following parameters are reserved:
328 * - escape - sets escape mode:
329 * - 'html' for HTML escaping, this is the default.
330 * - 'js' for javascript escaping.
331 * - 'no'/'off'/0 - turns off escaping
332 * - plural - The plural version of the text (2nd parameter of ngettext())
333 * - count - The item count for plural mode (3rd parameter of ngettext())
334 * - context - gettext context of that string (for homonym handling)
335 *
336 * @param string $text
337 * the original string.
338 * @param array $params
339 * The params of the translation (if any).
340 * - domain: string|array a list of translation domains to search (in order)
341 * - context: string
342 * - skip_translation: flag (do only escape/replacement, skip the actual translation)
343 *
344 * @return string
345 * the translated string
346 */
347 public function crm_translate($text, $params = []) {
348 $escape = $params['escape'] ?? NULL;
349 unset($params['escape']);
350
351 // sometimes we need to {ts}-tag a string, but don’t want to
352 // translate it in the template (like civicrm_navigation.tpl),
353 // because we handle the translation in a different way (CRM-6998)
354 // in such cases we return early, only doing SQL/JS escaping
355 if (isset($params['skip']) and $params['skip']) {
356 return self::escape($text, $escape);
357 }
358
359 $plural = $count = NULL;
360 if (isset($params['plural'])) {
361 $plural = $params['plural'];
362 unset($params['plural']);
363 if (isset($params['count'])) {
364 $count = $params['count'];
365 }
366 }
367
368 if (isset($params['context'])) {
369 $context = $params['context'];
370 unset($params['context']);
371 }
372 else {
373 $context = NULL;
374 }
375
376 if (isset($params['domain'])) {
377 $domain = $params['domain'];
378 unset($params['domain']);
379 }
380 else {
381 $domain = NULL;
382 }
383
384 $raw = !empty($params['raw']);
385 unset($params['raw']);
386
387 if (!isset($params['skip_translation'])) {
388 if (!empty($domain)) {
389 // It might be prettier to cast to an array, but this is high-traffic stuff.
390 if (is_array($domain)) {
391 foreach ($domain as $d) {
392 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
393 if ($candidate != $text) {
394 $text = $candidate;
395 break;
396 }
397 }
398 }
399 else {
400 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
401 }
402 }
403 else {
404 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
405 }
406 }
407
408 // replace the numbered %1, %2, etc. params if present
409 if (count($params) && !$raw) {
410 $text = $this->strarg($text, $params);
411 }
412
413 return self::escape($text, $escape);
414 }
415
416 /**
417 * Lookup the raw translation of a string (without any extra escaping or interpolation).
418 *
419 * @param string $text
420 * @param string|null $domain
421 * @param int|null $count
422 * @param string $plural
423 * @param string $context
424 *
425 * @return string
426 */
427 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
428 // gettext domain for extensions
429 $domain_changed = FALSE;
430 if (!empty($domain) && $this->_phpgettext) {
431 if ($this->setGettextDomain($domain)) {
432 $domain_changed = TRUE;
433 }
434 }
435
436 // do all wildcard translations first
437
438 $stringTable = $this->getWordReplacements();
439
440 $exactMatch = FALSE;
441 if (isset($stringTable['enabled']['exactMatch'])) {
442 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
443 if ($search === $text) {
444 $exactMatch = TRUE;
445 $text = $replace;
446 break;
447 }
448 }
449 }
450
451 if (
452 !$exactMatch &&
453 isset($stringTable['enabled']['wildcardMatch'])
454 ) {
455 $search = array_keys($stringTable['enabled']['wildcardMatch']);
456 $replace = array_values($stringTable['enabled']['wildcardMatch']);
457 $text = str_replace($search, $replace, $text);
458 }
459
460 // dont translate if we've done exactMatch already
461 if (!$exactMatch) {
462 // use plural if required parameters are set
463 if (isset($count) && isset($plural)) {
464
465 if ($this->_phpgettext) {
466 $text = $this->_phpgettext->ngettext($text, $plural, (int) $count);
467 }
468 else {
469 // if the locale's not set, we do ngettext work by hand
470 // if $count == 1 then $text = $text, else $text = $plural
471 if ($count != 1) {
472 $text = $plural;
473 }
474 }
475
476 // expand %count in translated string to $count
477 $text = strtr($text, ['%count' => $count]);
478
479 // if not plural, but the locale's set, translate
480 }
481 elseif ($this->_phpgettext) {
482 if ($context) {
483 $text = $this->_phpgettext->pgettext($context, $text);
484 }
485 else {
486 $text = $this->_phpgettext->translate($text);
487 }
488 }
489 }
490
491 if ($domain_changed) {
492 $this->setGettextDomain('civicrm');
493 }
494
495 return $text;
496 }
497
498 /**
499 * Translate a string to the current locale.
500 *
501 * @param string $string
502 * this string should be translated.
503 *
504 * @return string
505 * the translated string
506 */
507 public function translate($string) {
508 return ($this->_phpgettext) ? $this->_phpgettext->translate($string) : $string;
509 }
510
511 /**
512 * Localize (destructively) array values.
513 *
514 * @param array $array
515 * the array for localization (in place).
516 * @param array $params
517 * an array of additional parameters.
518 */
519 public function localizeArray(
520 &$array,
521 $params = []
522 ) {
523 $tsLocale = CRM_Core_I18n::getLocale();
524
525 if ($tsLocale == 'en_US') {
526 return;
527 }
528
529 foreach ($array as & $value) {
530 if ($value) {
531 $value = ts($value, $params);
532 }
533 }
534 }
535
536 /**
537 * Localize (destructively) array elements with keys of 'title'.
538 *
539 * @param array $array
540 * the array for localization (in place).
541 */
542 public function localizeTitles(&$array) {
543 foreach ($array as $key => $value) {
544 if (is_array($value)) {
545 $this->localizeTitles($value);
546 $array[$key] = $value;
547 }
548 elseif ((string ) $key == 'title') {
549 $array[$key] = ts($value, ['context' => 'menu']);
550 }
551 }
552 }
553
554 /**
555 * Binds a gettext domain, wrapper over bindtextdomain().
556 *
557 * @param string $key
558 * Key of the extension (can be 'civicrm', or 'org.example.foo').
559 *
560 * @return Bool
561 * True if the domain was changed for an extension.
562 */
563 public function setGettextDomain($key) {
564 /* No domain changes for en_US */
565 if (!$this->_phpgettext) {
566 return FALSE;
567 }
568
569 // It's only necessary to find/bind once
570 if (!isset($this->_extensioncache[$key])) {
571 try {
572 $mapper = CRM_Extension_System::singleton()->getMapper();
573 $path = $mapper->keyToBasePath($key);
574 $info = $mapper->keyToInfo($key);
575 $domain = $info->file;
576
577 if ($this->_nativegettext) {
578 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR . 'l10n');
579 bind_textdomain_codeset($domain, 'UTF-8');
580 $this->_extensioncache[$key] = $domain;
581 }
582 else {
583 // phpgettext
584 $mo_file = $path . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR . $this->locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $domain . '.mo';
585 $streamer = new FileReader($mo_file);
586 $this->_extensioncache[$key] = $streamer->length() ? new gettext_reader($streamer) : NULL;
587 }
588 }
589 catch (CRM_Extension_Exception $e) {
590 // Intentionally not translating this string to avoid possible infinite loops
591 // Only developers should see this string, if they made a mistake in their ts() usage.
592 CRM_Core_Session::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
593 $this->_extensioncache[$key] = FALSE;
594 }
595 }
596
597 if (isset($this->_extensioncache[$key]) && $this->_extensioncache[$key]) {
598 if ($this->_nativegettext) {
599 textdomain($this->_extensioncache[$key]);
600 }
601 else {
602 $this->_phpgettext = $this->_extensioncache[$key];
603 }
604
605 return TRUE;
606 }
607
608 return FALSE;
609 }
610
611 /**
612 * Is the current CiviCRM domain in multilingual mode.
613 *
614 * @return bool
615 * True if CiviCRM is in multilingual mode.
616 */
617 public static function isMultilingual() {
618 $domain = CRM_Core_BAO_Domain::getDomain();
619 return (bool) $domain->locales;
620 }
621
622 /**
623 * Returns languages if domain is in multilingual mode.
624 *
625 * @return array|bool
626 */
627 public static function getMultilingual() {
628 $domain = CRM_Core_BAO_Domain::getDomain();
629 return $domain->locales ? CRM_Core_DAO::unSerializeField($domain->locales, CRM_Core_DAO::SERIALIZE_SEPARATOR_TRIMMED) : FALSE;
630 }
631
632 /**
633 * Is the language written "right-to-left"?
634 *
635 * @param string $language
636 * Language (for example 'en_US', or 'fr_CA').
637 *
638 * @return bool
639 * True if it is an RTL language.
640 */
641 public static function isLanguageRTL($language) {
642 $rtl = CRM_Core_I18n_PseudoConstant::getRTLlanguages();
643 $short = CRM_Core_I18n_PseudoConstant::shortForLong($language);
644
645 return (in_array($short, $rtl));
646 }
647
648 /**
649 * If you switch back/forth between locales/drivers, it may be necessary
650 * to reset some options.
651 */
652 protected function reactivate() {
653 if ($this->_nativegettext) {
654 $this->setNativeGettextLocale($this->locale);
655 }
656
657 }
658
659 /**
660 * Change the processing language without changing the current user language
661 *
662 * @param string $locale
663 * Locale (for example 'en_US', or 'fr_CA').
664 * True if the domain was changed for an extension.
665 */
666 public function setLocale($locale) {
667
668 // Change the language of the CMS as well, for URLs.
669 CRM_Utils_System::setUFLocale($locale);
670
671 // For sql queries, if running in DB multi-lingual mode.
672 global $dbLocale;
673
674 if ($dbLocale) {
675 $dbLocale = "_{$locale}";
676 }
677
678 // For self::getLocale()
679 global $tsLocale;
680 $tsLocale = $locale;
681
682 CRM_Core_I18n::singleton()->reactivate();
683 }
684
685 /**
686 * Static instance provider - return the instance for the current locale.
687 *
688 * @return CRM_Core_I18n
689 */
690 public static function &singleton() {
691 if (!isset(Civi::$statics[__CLASS__]['singleton'])) {
692 Civi::$statics[__CLASS__]['singleton'] = [];
693 }
694 $tsLocale = CRM_Core_I18n::getLocale();
695 if (!isset(Civi::$statics[__CLASS__]['singleton'][$tsLocale])) {
696 Civi::$statics[__CLASS__]['singleton'][$tsLocale] = new CRM_Core_I18n($tsLocale);
697 }
698
699 return Civi::$statics[__CLASS__]['singleton'][$tsLocale];
700 }
701
702 /**
703 * Set the LC_TIME locale if it's not set already (for a given language choice).
704 *
705 * @return string
706 * the final LC_TIME that got set
707 */
708 public static function setLcTime() {
709 static $locales = [];
710
711 $tsLocale = CRM_Core_I18n::getLocale();
712 if (!isset($locales[$tsLocale])) {
713 // with the config being set to pl_PL: try pl_PL.UTF-8,
714 // then pl_PL, if neither present fall back to C
715 $locales[$tsLocale] = setlocale(LC_TIME, $tsLocale . '.UTF-8', $tsLocale, 'C');
716 }
717
718 return $locales[$tsLocale];
719 }
720
721 /**
722 * Get the default language for contacts where no language is provided.
723 *
724 * Note that NULL is a valid option so be careful with checking for empty etc.
725 *
726 * NULL would mean 'we don't know & we don't want to hazard a guess'.
727 *
728 * @return string
729 */
730 public static function getContactDefaultLanguage() {
731 $language = Civi::settings()->get('contact_default_language');
732 if ($language == 'undefined') {
733 return NULL;
734 }
735 if (empty($language) || $language === '*default*') {
736 $language = civicrm_api3('setting', 'getvalue', [
737 'name' => 'lcMessages',
738 'group' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
739 ]);
740 }
741 elseif ($language == 'current_site_language') {
742 return CRM_Core_I18n::getLocale();
743 }
744
745 return $language;
746 }
747
748 /**
749 * Get the current locale
750 *
751 * @return string
752 */
753 public static function getLocale() {
754 global $tsLocale;
755 return $tsLocale ? $tsLocale : 'en_US';
756 }
757
758 /**
759 * @return array
760 * Ex: $stringTable['enabled']['wildcardMatch']['foo'] = 'bar';
761 */
762 private function getWordReplacements() {
763 if (isset(Civi::$statics['testPreInstall'])) {
764 return [];
765 }
766
767 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
768 $replacementsLocale = $this->locale ? $this->locale : 'en_US';
769 if ((!isset(Civi::$statics[__CLASS__]) || !array_key_exists($replacementsLocale, Civi::$statics[__CLASS__]))) {
770 if (defined('CIVICRM_DSN') && !CRM_Core_Config::isUpgradeMode()) {
771 Civi::$statics[__CLASS__][$replacementsLocale] = CRM_Core_BAO_WordReplacement::getLocaleCustomStrings($replacementsLocale);
772 }
773 else {
774 Civi::$statics[__CLASS__][$replacementsLocale] = [];
775 }
776 }
777 return Civi::$statics[__CLASS__][$replacementsLocale];
778 }
779
780 }
781
782 /**
783 * Short-named function for string translation, defined in global scope so it's available everywhere.
784 *
785 * @param string $text
786 * String string for translating.
787 * @param array $params
788 * Array an array of additional parameters.
789 *
790 * @return string
791 * the translated string
792 */
793 function ts($text, $params = []) {
794 static $bootstrapReady = FALSE;
795 static $lastLocale = NULL;
796 static $i18n = NULL;
797 static $function = NULL;
798
799 if ($text == '') {
800 return '';
801 }
802
803 // When the settings become available, lookup customTranslateFunction.
804 if (!$bootstrapReady) {
805 $bootstrapReady = (bool) \Civi\Core\Container::isContainerBooted();
806 if ($bootstrapReady) {
807 // just got ready: determine whether there is a working custom translation function
808 $config = CRM_Core_Config::singleton();
809 if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
810 $function = $config->customTranslateFunction;
811 }
812 }
813 }
814
815 $activeLocale = CRM_Core_I18n::getLocale();
816 if (!$i18n or $lastLocale != $activeLocale) {
817 $i18n = CRM_Core_I18n::singleton();
818 $lastLocale = $activeLocale;
819 }
820
821 if ($function) {
822 return $function($text, $params);
823 }
824 else {
825 return $i18n->crm_translate($text, $params);
826 }
827 }