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