3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 * Constants for communication preferences.
24 const NONE
= 'none', AUTO
= 'auto';
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])`.
32 * This option is not intended for general consumption. It is only intended
33 * for certain pre-boot/pre-install contexts.
35 * You might ask, "Why on Earth does string-translation have an opinion on
36 * SQL escaping?" Good question!
38 public static $SQL_ESCAPER = NULL;
41 * Escape a string if a mode is specified, otherwise return string unmodified.
47 protected static function escape($text, $mode) {
50 if (self
::$SQL_ESCAPER == NULL) {
51 return CRM_Core_DAO
::escapeString($text);
54 return call_user_func(self
::$SQL_ESCAPER, $text);
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);
64 * A PHP-gettext instance for string translation;
65 * should stay null if the strings are not to be translated (en_US).
68 private $_phpgettext = NULL;
71 * Whether we are using native gettext or not.
74 private $_nativegettext = FALSE;
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.
82 private $_extensioncache = [];
90 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
92 * @param string $locale
93 * the base of this certain object's existence.
95 * @return \CRM_Core_I18n
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
103 $this->_nativegettext
= TRUE;
104 $this->setNativeGettextLocale($locale);
108 // Otherwise, use PHP-gettext
109 $this->setPhpGettextLocale($locale);
114 * Returns whether gettext is running natively or using PHP-Gettext.
117 * True if gettext is native
119 public function isNative() {
120 return $this->_nativegettext
;
124 * Set native locale for getText.
126 * @param string $locale
128 protected function setNativeGettextLocale($locale) {
131 putenv("LANG=$locale");
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);
138 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
139 bind_textdomain_codeset('civicrm', 'UTF-8');
140 textdomain('civicrm');
142 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
143 $this->_extensioncache
['civicrm'] = 'civicrm';
148 * Set getText locale.
150 * @param string $locale
152 protected function setPhpGettextLocale($locale) {
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';
160 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
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';
167 $streamer = new FileReader($mo_file);
168 $this->_phpgettext
= new gettext_reader($streamer);
169 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
174 * Return languages available in this instance of CiviCRM.
176 * @param bool $justEnabled
177 * whether to return all languages or just the enabled ones.
180 * Array of code/language name mappings
182 public static function languages($justEnabled = FALSE) {
184 static $enabled = NULL;
187 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
192 CRM_Core_OptionValue
::getValues(['name' => 'languages'], $rows);
193 foreach ($rows as $id => $row) {
194 $labels[$row['name']] = $row['label'];
197 // check which ones are available; add them to $all if not there already
199 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
200 while ($filename = readdir($dir)) {
201 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
202 $codes[] = $filename;
203 if (!isset($all[$filename])) {
204 $all[$filename] = $labels[$filename] ??
"($filename)";
211 // drop the unavailable languages (except en_US)
212 foreach (array_keys($all) as $code) {
213 if ($code == 'en_US') {
216 if (!in_array($code, $codes)) {
224 if ($enabled === NULL) {
225 $languageLimit = Civi
::settings()->get('languageLimit');
227 if ($languageLimit) {
228 foreach ($all as $code => $name) {
229 if (array_key_exists($code, $languageLimit)) {
230 $enabled[$code] = $name;
236 return $justEnabled ?
$enabled : $all;
240 * Return the available UI languages
241 * @return array|string
242 * array(string languageCode => string languageName) if !$justCodes
244 public static function uiLanguages($justCodes = FALSE) {
245 // In multilang we only allow the languages that are configured in db
246 // Otherwise, the languages configured in uiLanguages
247 $settings = Civi
::settings();
248 if (CRM_Core_I18n
::isMultiLingual()) {
249 $codes = array_keys((array) $settings->get('languageLimit'));
252 $codes = $settings->get('uiLanguages');
254 $codes = [$settings->get('lcMessages')];
257 return $justCodes ?
$codes
258 : CRM_Utils_Array
::subset(CRM_Core_I18n
::languages(), $codes);
262 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
270 public function strarg($str) {
273 for ($i = 1; $i < func_num_args(); $i++
) {
274 $arg = func_get_arg($i);
275 if (is_array($arg)) {
276 foreach ($arg as $aarg) {
277 $tr['%' . ++
$p] = $aarg;
281 $tr['%' . ++
$p] = $arg;
284 return strtr($str, $tr);
288 * Get the directory for l10n resources.
292 public static function getResourceDir() {
293 return CRM_Utils_File
::addTrailingSlash(\Civi
::paths()->getPath('[civicrm.l10n]/.'));
297 * Smarty block function, provides gettext support for smarty.
299 * The block content is the text that should be translated.
301 * Any parameter that is sent to the function will be represented as %n in the translation text,
302 * where n is 1 for the first parameter. The following parameters are reserved:
303 * - escape - sets escape mode:
304 * - 'html' for HTML escaping, this is the default.
305 * - 'js' for javascript escaping.
306 * - 'no'/'off'/0 - turns off escaping
307 * - plural - The plural version of the text (2nd parameter of ngettext())
308 * - count - The item count for plural mode (3rd parameter of ngettext())
309 * - context - gettext context of that string (for homonym handling)
311 * @param string $text
312 * the original string.
313 * @param array $params
314 * The params of the translation (if any).
315 * - domain: string|array a list of translation domains to search (in order)
317 * - skip_translation: flag (do only escape/replacement, skip the actual translation)
320 * the translated string
322 public function crm_translate($text, $params = []) {
323 $escape = $params['escape'] ??
NULL;
324 unset($params['escape']);
326 // sometimes we need to {ts}-tag a string, but don’t want to
327 // translate it in the template (like civicrm_navigation.tpl),
328 // because we handle the translation in a different way (CRM-6998)
329 // in such cases we return early, only doing SQL/JS escaping
330 if (isset($params['skip']) and $params['skip']) {
331 return self
::escape($text, $escape);
334 $plural = $count = NULL;
335 if (isset($params['plural'])) {
336 $plural = $params['plural'];
337 unset($params['plural']);
338 if (isset($params['count'])) {
339 $count = $params['count'];
343 if (isset($params['context'])) {
344 $context = $params['context'];
345 unset($params['context']);
351 if (isset($params['domain'])) {
352 $domain = $params['domain'];
353 unset($params['domain']);
359 $raw = !empty($params['raw']);
360 unset($params['raw']);
362 if (!isset($params['skip_translation'])) {
363 if (!empty($domain)) {
364 // It might be prettier to cast to an array, but this is high-traffic stuff.
365 if (is_array($domain)) {
366 foreach ($domain as $d) {
367 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
368 if ($candidate != $text) {
375 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
379 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
383 // replace the numbered %1, %2, etc. params if present
384 if (count($params) && !$raw) {
385 $text = $this->strarg($text, $params);
388 return self
::escape($text, $escape);
392 * Lookup the raw translation of a string (without any extra escaping or interpolation).
394 * @param string $text
395 * @param string|null $domain
396 * @param int|null $count
397 * @param string $plural
398 * @param string $context
402 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
403 // gettext domain for extensions
404 $domain_changed = FALSE;
405 if (!empty($domain) && $this->_phpgettext
) {
406 if ($this->setGettextDomain($domain)) {
407 $domain_changed = TRUE;
411 // do all wildcard translations first
413 $stringTable = $this->getWordReplacements();
416 if (isset($stringTable['enabled']['exactMatch'])) {
417 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
418 if ($search === $text) {
428 isset($stringTable['enabled']['wildcardMatch'])
430 $search = array_keys($stringTable['enabled']['wildcardMatch']);
431 $replace = array_values($stringTable['enabled']['wildcardMatch']);
432 $text = str_replace($search, $replace, $text);
435 // dont translate if we've done exactMatch already
437 // use plural if required parameters are set
438 if (isset($count) && isset($plural)) {
440 if ($this->_phpgettext
) {
441 $text = $this->_phpgettext
->ngettext($text, $plural, (int) $count);
444 // if the locale's not set, we do ngettext work by hand
445 // if $count == 1 then $text = $text, else $text = $plural
451 // expand %count in translated string to $count
452 $text = strtr($text, ['%count' => $count]);
454 // if not plural, but the locale's set, translate
456 elseif ($this->_phpgettext
) {
458 $text = $this->_phpgettext
->pgettext($context, $text);
461 $text = $this->_phpgettext
->translate($text);
466 if ($domain_changed) {
467 $this->setGettextDomain('civicrm');
474 * Translate a string to the current locale.
476 * @param string $string
477 * this string should be translated.
480 * the translated string
482 public function translate($string) {
483 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
487 * Localize (destructively) array values.
489 * @param array $array
490 * the array for localization (in place).
491 * @param array $params
492 * an array of additional parameters.
494 public function localizeArray(
498 $tsLocale = CRM_Core_I18n
::getLocale();
500 if ($tsLocale == 'en_US') {
504 foreach ($array as & $value) {
506 $value = ts($value, $params);
512 * Localize (destructively) array elements with keys of 'title'.
514 * @param array $array
515 * the array for localization (in place).
517 public function localizeTitles(&$array) {
518 foreach ($array as $key => $value) {
519 if (is_array($value)) {
520 $this->localizeTitles($value);
521 $array[$key] = $value;
523 elseif ((string ) $key == 'title') {
524 $array[$key] = ts($value, ['context' => 'menu']);
530 * Binds a gettext domain, wrapper over bindtextdomain().
533 * Key of the extension (can be 'civicrm', or 'org.example.foo').
536 * True if the domain was changed for an extension.
538 public function setGettextDomain($key) {
539 /* No domain changes for en_US */
540 if (!$this->_phpgettext
) {
544 // It's only necessary to find/bind once
545 if (!isset($this->_extensioncache
[$key])) {
547 $mapper = CRM_Extension_System
::singleton()->getMapper();
548 $path = $mapper->keyToBasePath($key);
549 $info = $mapper->keyToInfo($key);
550 $domain = $info->file
;
552 if ($this->_nativegettext
) {
553 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
554 bind_textdomain_codeset($domain, 'UTF-8');
555 $this->_extensioncache
[$key] = $domain;
559 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
560 $streamer = new FileReader($mo_file);
561 $this->_extensioncache
[$key] = new gettext_reader($streamer);
564 catch (CRM_Extension_Exception
$e) {
565 // Intentionally not translating this string to avoid possible infinite loops
566 // Only developers should see this string, if they made a mistake in their ts() usage.
567 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
568 $this->_extensioncache
[$key] = FALSE;
572 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
573 if ($this->_nativegettext
) {
574 textdomain($this->_extensioncache
[$key]);
577 $this->_phpgettext
= $this->_extensioncache
[$key];
587 * Is the current CiviCRM domain in multilingual mode.
590 * True if CiviCRM is in multilingual mode.
592 public static function isMultilingual() {
593 $domain = CRM_Core_BAO_Domain
::getDomain();
594 return (bool) $domain->locales
;
598 * Returns languages if domain is in multilingual mode.
602 public static function getMultilingual() {
603 $domain = CRM_Core_BAO_Domain
::getDomain();
604 return $domain->locales ? CRM_Core_DAO
::unSerializeField($domain->locales
, CRM_Core_DAO
::SERIALIZE_SEPARATOR_TRIMMED
) : FALSE;
608 * Is the language written "right-to-left"?
611 * Language (for example 'en_US', or 'fr_CA').
614 * True if it is an RTL language.
616 public static function isLanguageRTL($language) {
617 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
618 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
620 return (in_array($short, $rtl));
624 * If you switch back/forth between locales/drivers, it may be necessary
625 * to reset some options.
627 protected function reactivate() {
628 if ($this->_nativegettext
) {
629 $this->setNativeGettextLocale($this->locale
);
635 * Change the processing language without changing the current user language
638 * Locale (for example 'en_US', or 'fr_CA').
639 * True if the domain was changed for an extension.
641 public function setLocale($locale) {
643 // Change the language of the CMS as well, for URLs.
644 CRM_Utils_System
::setUFLocale($locale);
646 // For sql queries, if running in DB multi-lingual mode.
650 $dbLocale = "_{$locale}";
653 // For self::getLocale()
657 CRM_Core_I18n
::singleton()->reactivate();
661 * Static instance provider - return the instance for the current locale.
663 * @return CRM_Core_I18n
665 public static function &singleton() {
666 if (!isset(Civi
::$statics[__CLASS__
]['singleton'])) {
667 Civi
::$statics[__CLASS__
]['singleton'] = [];
669 $tsLocale = CRM_Core_I18n
::getLocale();
670 if (!isset(Civi
::$statics[__CLASS__
]['singleton'][$tsLocale])) {
671 Civi
::$statics[__CLASS__
]['singleton'][$tsLocale] = new CRM_Core_I18n($tsLocale);
674 return Civi
::$statics[__CLASS__
]['singleton'][$tsLocale];
678 * Set the LC_TIME locale if it's not set already (for a given language choice).
681 * the final LC_TIME that got set
683 public static function setLcTime() {
684 static $locales = [];
686 $tsLocale = CRM_Core_I18n
::getLocale();
687 if (!isset($locales[$tsLocale])) {
688 // with the config being set to pl_PL: try pl_PL.UTF-8,
689 // then pl_PL, if neither present fall back to C
690 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
693 return $locales[$tsLocale];
697 * Get the default language for contacts where no language is provided.
699 * Note that NULL is a valid option so be careful with checking for empty etc.
701 * NULL would mean 'we don't know & we don't want to hazard a guess'.
705 public static function getContactDefaultLanguage() {
706 $language = Civi
::settings()->get('contact_default_language');
707 if ($language == 'undefined') {
710 if (empty($language) ||
$language === '*default*') {
711 $language = civicrm_api3('setting', 'getvalue', [
712 'name' => 'lcMessages',
713 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
716 elseif ($language == 'current_site_language') {
717 return CRM_Core_I18n
::getLocale();
724 * Get the current locale
728 public static function getLocale() {
730 return $tsLocale ?
$tsLocale : 'en_US';
735 * Ex: $stringTable['enabled']['wildcardMatch']['foo'] = 'bar';
737 private function getWordReplacements() {
738 if (isset(Civi
::$statics['testPreInstall'])) {
742 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
743 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
744 if ((!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
]))) {
745 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
746 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
749 Civi
::$statics[__CLASS__
][$replacementsLocale] = [];
752 return Civi
::$statics[__CLASS__
][$replacementsLocale];
758 * Short-named function for string translation, defined in global scope so it's available everywhere.
760 * @param string $text
761 * String string for translating.
762 * @param array $params
763 * Array an array of additional parameters.
766 * the translated string
768 function ts($text, $params = []) {
769 static $bootstrapReady = FALSE;
770 static $lastLocale = NULL;
772 static $function = NULL;
778 // When the settings become available, lookup customTranslateFunction.
779 if (!$bootstrapReady) {
780 $bootstrapReady = (bool) \Civi\Core\Container
::isContainerBooted();
781 if ($bootstrapReady) {
782 // just got ready: determine whether there is a working custom translation function
783 $config = CRM_Core_Config
::singleton();
784 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
785 $function = $config->customTranslateFunction
;
790 $activeLocale = CRM_Core_I18n
::getLocale();
791 if (!$i18n or $lastLocale != $activeLocale) {
792 $i18n = CRM_Core_I18n
::singleton();
793 $lastLocale = $activeLocale;
797 return $function($text, $params);
800 return $i18n->crm_translate($text, $params);