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 // 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');
191 // FIXME: How is this not duplicative of the lines above?
195 CRM_Core_OptionValue
::getValues(['name' => 'languages'], $rows);
196 foreach ($rows as $id => $row) {
197 $labels[$row['name']] = $row['label'];
200 // check which ones are available; add them to $all if not there already
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)";
214 // drop the unavailable languages (except en_US)
215 foreach (array_keys($all) as $code) {
216 if ($code == 'en_US') {
219 if (!in_array($code, $codes)) {
227 if ($enabled === NULL) {
228 $languageLimit = Civi
::settings()->get('languageLimit');
230 if ($languageLimit) {
231 foreach ($all as $code => $name) {
232 if (array_key_exists($code, $languageLimit)) {
233 $enabled[$code] = $name;
239 return $justEnabled ?
$enabled : $all;
243 * Return the available UI languages
244 * @return array|string
245 * array(string languageCode => string languageName) if !$justCodes
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'));
255 $codes = $settings->get('uiLanguages');
257 $codes = [$settings->get('lcMessages')];
260 return $justCodes ?
$codes
261 : CRM_Utils_Array
::subset(CRM_Core_I18n
::languages(), $codes);
265 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
273 public function strarg($str) {
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;
284 $tr['%' . ++
$p] = $arg;
287 return strtr($str, $tr);
291 * Get the directory for l10n resources.
295 public static function getResourceDir() {
296 return CRM_Utils_File
::addTrailingSlash(\Civi
::paths()->getPath('[civicrm.l10n]/.'));
300 * Smarty block function, provides gettext support for smarty.
302 * The block content is the text that should be translated.
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)
314 * @param string $text
315 * the original string.
316 * @param array $params
317 * The params of the translation (if any).
318 * - domain: string|array a list of translation domains to search (in order)
320 * - skip_translation: flag (do only escape/replacement, skip the actual translation)
323 * the translated string
325 public function crm_translate($text, $params = []) {
326 $escape = $params['escape'] ??
NULL;
327 unset($params['escape']);
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']) {
334 return self
::escape($text, $escape);
337 $plural = $count = NULL;
338 if (isset($params['plural'])) {
339 $plural = $params['plural'];
340 unset($params['plural']);
341 if (isset($params['count'])) {
342 $count = $params['count'];
346 if (isset($params['context'])) {
347 $context = $params['context'];
348 unset($params['context']);
354 if (isset($params['domain'])) {
355 $domain = $params['domain'];
356 unset($params['domain']);
362 $raw = !empty($params['raw']);
363 unset($params['raw']);
365 if (!isset($params['skip_translation'])) {
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) {
378 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
382 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
386 // replace the numbered %1, %2, etc. params if present
387 if (count($params) && !$raw) {
388 $text = $this->strarg($text, $params);
391 return self
::escape($text, $escape);
395 * Lookup the raw translation of a string (without any extra escaping or interpolation).
397 * @param string $text
398 * @param string|null $domain
399 * @param int|null $count
400 * @param string $plural
401 * @param string $context
405 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
406 // gettext domain for extensions
407 $domain_changed = FALSE;
408 if (!empty($domain) && $this->_phpgettext
) {
409 if ($this->setGettextDomain($domain)) {
410 $domain_changed = TRUE;
414 // do all wildcard translations first
416 $stringTable = $this->getWordReplacements();
419 if (isset($stringTable['enabled']['exactMatch'])) {
420 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
421 if ($search === $text) {
431 isset($stringTable['enabled']['wildcardMatch'])
433 $search = array_keys($stringTable['enabled']['wildcardMatch']);
434 $replace = array_values($stringTable['enabled']['wildcardMatch']);
435 $text = str_replace($search, $replace, $text);
438 // dont translate if we've done exactMatch already
440 // use plural if required parameters are set
441 if (isset($count) && isset($plural)) {
443 if ($this->_phpgettext
) {
444 $text = $this->_phpgettext
->ngettext($text, $plural, (int) $count);
447 // if the locale's not set, we do ngettext work by hand
448 // if $count == 1 then $text = $text, else $text = $plural
454 // expand %count in translated string to $count
455 $text = strtr($text, ['%count' => $count]);
457 // if not plural, but the locale's set, translate
459 elseif ($this->_phpgettext
) {
461 $text = $this->_phpgettext
->pgettext($context, $text);
464 $text = $this->_phpgettext
->translate($text);
469 if ($domain_changed) {
470 $this->setGettextDomain('civicrm');
477 * Translate a string to the current locale.
479 * @param string $string
480 * this string should be translated.
483 * the translated string
485 public function translate($string) {
486 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
490 * Localize (destructively) array values.
492 * @param array $array
493 * the array for localization (in place).
494 * @param array $params
495 * an array of additional parameters.
497 public function localizeArray(
501 $tsLocale = CRM_Core_I18n
::getLocale();
503 if ($tsLocale == 'en_US') {
507 foreach ($array as & $value) {
509 $value = ts($value, $params);
515 * Localize (destructively) array elements with keys of 'title'.
517 * @param array $array
518 * the array for localization (in place).
520 public function localizeTitles(&$array) {
521 foreach ($array as $key => $value) {
522 if (is_array($value)) {
523 $this->localizeTitles($value);
524 $array[$key] = $value;
526 elseif ((string ) $key == 'title') {
527 $array[$key] = ts($value, ['context' => 'menu']);
533 * Binds a gettext domain, wrapper over bindtextdomain().
536 * Key of the extension (can be 'civicrm', or 'org.example.foo').
539 * True if the domain was changed for an extension.
541 public function setGettextDomain($key) {
542 /* No domain changes for en_US */
543 if (!$this->_phpgettext
) {
547 // It's only necessary to find/bind once
548 if (!isset($this->_extensioncache
[$key])) {
550 $mapper = CRM_Extension_System
::singleton()->getMapper();
551 $path = $mapper->keyToBasePath($key);
552 $info = $mapper->keyToInfo($key);
553 $domain = $info->file
;
555 if ($this->_nativegettext
) {
556 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
557 bind_textdomain_codeset($domain, 'UTF-8');
558 $this->_extensioncache
[$key] = $domain;
562 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
563 $streamer = new FileReader($mo_file);
564 $this->_extensioncache
[$key] = new gettext_reader($streamer);
567 catch (CRM_Extension_Exception
$e) {
568 // Intentionally not translating this string to avoid possible infinite loops
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;
575 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
576 if ($this->_nativegettext
) {
577 textdomain($this->_extensioncache
[$key]);
580 $this->_phpgettext
= $this->_extensioncache
[$key];
590 * Is the current CiviCRM domain in multilingual mode.
593 * True if CiviCRM is in multilingual mode.
595 public static function isMultilingual() {
596 $domain = CRM_Core_BAO_Domain
::getDomain();
597 return (bool) $domain->locales
;
601 * Returns languages if domain is in multilingual mode.
605 public static function getMultilingual() {
606 $domain = CRM_Core_BAO_Domain
::getDomain();
607 return $domain->locales ? CRM_Core_DAO
::unSerializeField($domain->locales
, CRM_Core_DAO
::SERIALIZE_SEPARATOR_TRIMMED
) : FALSE;
611 * Is the language written "right-to-left"?
614 * Language (for example 'en_US', or 'fr_CA').
617 * True if it is an RTL language.
619 public static function isLanguageRTL($language) {
620 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
621 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
623 return (in_array($short, $rtl));
627 * If you switch back/forth between locales/drivers, it may be necessary
628 * to reset some options.
630 protected function reactivate() {
631 if ($this->_nativegettext
) {
632 $this->setNativeGettextLocale($this->locale
);
638 * Change the processing language without changing the current user language
641 * Locale (for example 'en_US', or 'fr_CA').
642 * True if the domain was changed for an extension.
644 public function setLocale($locale) {
646 // Change the language of the CMS as well, for URLs.
647 CRM_Utils_System
::setUFLocale($locale);
649 // For sql queries, if running in DB multi-lingual mode.
653 $dbLocale = "_{$locale}";
656 // For self::getLocale()
660 CRM_Core_I18n
::singleton()->reactivate();
664 * Static instance provider - return the instance for the current locale.
666 * @return CRM_Core_I18n
668 public static function &singleton() {
669 if (!isset(Civi
::$statics[__CLASS__
]['singleton'])) {
670 Civi
::$statics[__CLASS__
]['singleton'] = [];
672 $tsLocale = CRM_Core_I18n
::getLocale();
673 if (!isset(Civi
::$statics[__CLASS__
]['singleton'][$tsLocale])) {
674 Civi
::$statics[__CLASS__
]['singleton'][$tsLocale] = new CRM_Core_I18n($tsLocale);
677 return Civi
::$statics[__CLASS__
]['singleton'][$tsLocale];
681 * Set the LC_TIME locale if it's not set already (for a given language choice).
684 * the final LC_TIME that got set
686 public static function setLcTime() {
687 static $locales = [];
689 $tsLocale = CRM_Core_I18n
::getLocale();
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');
696 return $locales[$tsLocale];
700 * Get the default language for contacts where no language is provided.
702 * Note that NULL is a valid option so be careful with checking for empty etc.
704 * NULL would mean 'we don't know & we don't want to hazard a guess'.
708 public static function getContactDefaultLanguage() {
709 $language = Civi
::settings()->get('contact_default_language');
710 if ($language == 'undefined') {
713 if (empty($language) ||
$language === '*default*') {
714 $language = civicrm_api3('setting', 'getvalue', [
715 'name' => 'lcMessages',
716 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
719 elseif ($language == 'current_site_language') {
720 return CRM_Core_I18n
::getLocale();
727 * Get the current locale
731 public static function getLocale() {
733 return $tsLocale ?
$tsLocale : 'en_US';
738 * Ex: $stringTable['enabled']['wildcardMatch']['foo'] = 'bar';
740 private function getWordReplacements() {
741 if (isset(Civi
::$statics['testPreInstall'])) {
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);
752 Civi
::$statics[__CLASS__
][$replacementsLocale] = [];
755 return Civi
::$statics[__CLASS__
][$replacementsLocale];
761 * Short-named function for string translation, defined in global scope so it's available everywhere.
763 * @param string $text
764 * String string for translating.
765 * @param array $params
766 * Array an array of additional parameters.
769 * the translated string
771 function ts($text, $params = []) {
772 static $bootstrapReady = FALSE;
773 static $lastLocale = NULL;
775 static $function = NULL;
781 // When the settings become available, lookup customTranslateFunction.
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
786 $config = CRM_Core_Config
::singleton();
787 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
788 $function = $config->customTranslateFunction
;
793 $activeLocale = CRM_Core_I18n
::getLocale();
794 if (!$i18n or $lastLocale != $activeLocale) {
795 $i18n = CRM_Core_I18n
::singleton();
796 $lastLocale = $activeLocale;
800 return $function($text, $params);
803 return $i18n->crm_translate($text, $params);