3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
36 * Constants for communication preferences.
40 const NONE
= 'none', AUTO
= 'auto';
44 * A callback function which handles SQL string encoding.
45 * Set NULL to use the default, CRM_Core_DAO::escapeString().
46 * This is used by `ts(..., [escape=>sql])`.
48 * This option is not intended for general consumption. It is only intended
49 * for certain pre-boot/pre-install contexts.
51 * You might ask, "Why on Earth does string-translation have an opinion on
52 * SQL escaping?" Good question!
54 public static $SQL_ESCAPER = NULL;
57 * Encode a string for use in SQL.
62 protected static function escapeSql($text) {
63 if (self
::$SQL_ESCAPER == NULL) {
64 return CRM_Core_DAO
::escapeString($text);
67 return call_user_func(self
::$SQL_ESCAPER, $text);
72 * A PHP-gettext instance for string translation;
73 * should stay null if the strings are not to be translated (en_US).
76 private $_phpgettext = NULL;
79 * Whether we are using native gettext or not.
82 private $_nativegettext = FALSE;
85 * Gettext cache for extension domains/streamers, depending on if native or phpgettext.
86 * - native gettext: we cache the value for textdomain()
87 * - phpgettext: we cache the file streamer.
90 private $_extensioncache = [];
98 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
100 * @param string $locale
101 * the base of this certain object's existence.
103 * @return \CRM_Core_I18n
105 public function __construct($locale) {
106 $this->locale
= $locale;
107 if ($locale != '' and $locale != 'en_US') {
108 if (defined('CIVICRM_GETTEXT_NATIVE') && CIVICRM_GETTEXT_NATIVE
&& function_exists('gettext')) {
109 // Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
111 $this->_nativegettext
= TRUE;
112 $this->setNativeGettextLocale($locale);
116 // Otherwise, use PHP-gettext
117 $this->setPhpGettextLocale($locale);
122 * Returns whether gettext is running natively or using PHP-Gettext.
125 * True if gettext is native
127 public function isNative() {
128 return $this->_nativegettext
;
132 * Set native locale for getText.
134 * @param string $locale
136 protected function setNativeGettextLocale($locale) {
139 putenv("LANG=$locale");
141 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
142 setlocale(LC_TIME
, $locale);
143 setlocale(LC_MESSAGES
, $locale);
144 setlocale(LC_CTYPE
, $locale);
146 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
147 bind_textdomain_codeset('civicrm', 'UTF-8');
148 textdomain('civicrm');
150 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
151 $this->_extensioncache
['civicrm'] = 'civicrm';
156 * Set getText locale.
158 * @param string $locale
160 protected function setPhpGettextLocale($locale) {
162 // we support both the old file hierarchy format and the new:
163 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
164 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
165 require_once 'PHPgettext/streams.php';
166 require_once 'PHPgettext/gettext.php';
168 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
170 if (!file_exists($mo_file)) {
171 // fallback to pre-4.5 mode
172 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'civicrm.mo';
175 $streamer = new FileReader($mo_file);
176 $this->_phpgettext
= new gettext_reader($streamer);
177 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
182 * Return languages available in this instance of CiviCRM.
184 * @param bool $justEnabled
185 * whether to return all languages or just the enabled ones.
188 * Array of code/language name mappings
190 public static function languages($justEnabled = FALSE) {
192 static $enabled = NULL;
195 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
200 CRM_Core_OptionValue
::getValues(['name' => 'languages'], $rows);
201 foreach ($rows as $id => $row) {
202 $labels[$row['name']] = $row['label'];
205 // check which ones are available; add them to $all if not there already
207 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
208 while ($filename = readdir($dir)) {
209 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
210 $codes[] = $filename;
211 if (!isset($all[$filename])) {
212 $all[$filename] = $labels[$filename];
219 // drop the unavailable languages (except en_US)
220 foreach (array_keys($all) as $code) {
221 if ($code == 'en_US') {
224 if (!in_array($code, $codes)) {
232 if ($enabled === NULL) {
233 $config = CRM_Core_Config
::singleton();
235 if (isset($config->languageLimit
) and $config->languageLimit
) {
236 foreach ($all as $code => $name) {
237 if (in_array($code, array_keys($config->languageLimit
))) {
238 $enabled[$code] = $name;
244 return $justEnabled ?
$enabled : $all;
248 * Return the available UI languages
249 * @return array|string
250 * array(string languageCode => string languageName) if !$justCodes
252 public static function uiLanguages($justCodes = FALSE) {
253 // In multilang we only allow the languages that are configured in db
254 // Otherwise, the languages configured in uiLanguages
255 $settings = Civi
::settings();
256 if (CRM_Core_I18n
::isMultiLingual()) {
257 $codes = array_keys((array) $settings->get('languageLimit'));
260 $codes = $settings->get('uiLanguages');
262 $codes = [$settings->get('lcMessages')];
265 return $justCodes ?
$codes
266 : CRM_Utils_Array
::subset(CRM_Core_I18n
::languages(), $codes);
270 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
278 public function strarg($str) {
281 for ($i = 1; $i < func_num_args(); $i++
) {
282 $arg = func_get_arg($i);
283 if (is_array($arg)) {
284 foreach ($arg as $aarg) {
285 $tr['%' . ++
$p] = $aarg;
289 $tr['%' . ++
$p] = $arg;
292 return strtr($str, $tr);
296 * Get the directory for l10n resources.
300 public static function getResourceDir() {
303 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
309 * Smarty block function, provides gettext support for smarty.
311 * The block content is the text that should be translated.
313 * Any parameter that is sent to the function will be represented as %n in the translation text,
314 * where n is 1 for the first parameter. The following parameters are reserved:
315 * - escape - sets escape mode:
316 * - 'html' for HTML escaping, this is the default.
317 * - 'js' for javascript escaping.
318 * - 'no'/'off'/0 - turns off escaping
319 * - plural - The plural version of the text (2nd parameter of ngettext())
320 * - count - The item count for plural mode (3rd parameter of ngettext())
321 * - context - gettext context of that string (for homonym handling)
323 * @param string $text
324 * the original string.
325 * @param array $params
326 * The params of the translation (if any).
327 * - domain: string|array a list of translation domains to search (in order)
331 * the translated string
333 public function crm_translate($text, $params = []) {
334 if (isset($params['escape'])) {
335 $escape = $params['escape'];
336 unset($params['escape']);
339 // sometimes we need to {ts}-tag a string, but don’t want to
340 // translate it in the template (like civicrm_navigation.tpl),
341 // because we handle the translation in a different way (CRM-6998)
342 // in such cases we return early, only doing SQL/JS escaping
343 if (isset($params['skip']) and $params['skip']) {
344 if (isset($escape) and ($escape == 'sql')) {
345 $text = self
::escapeSql($text);
347 if (isset($escape) and ($escape == 'js')) {
348 $text = addcslashes($text, "'");
353 $plural = $count = NULL;
354 if (isset($params['plural'])) {
355 $plural = $params['plural'];
356 unset($params['plural']);
357 if (isset($params['count'])) {
358 $count = $params['count'];
362 if (isset($params['context'])) {
363 $context = $params['context'];
364 unset($params['context']);
370 if (isset($params['domain'])) {
371 $domain = $params['domain'];
372 unset($params['domain']);
378 $raw = !empty($params['raw']);
379 unset($params['raw']);
381 if (!empty($domain)) {
382 // It might be prettier to cast to an array, but this is high-traffic stuff.
383 if (is_array($domain)) {
384 foreach ($domain as $d) {
385 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
386 if ($candidate != $text) {
393 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
397 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
400 // replace the numbered %1, %2, etc. params if present
401 if (count($params) && !$raw) {
402 $text = $this->strarg($text, $params);
405 // escape SQL if we were asked for it
406 if (isset($escape) and ($escape == 'sql')) {
407 $text = self
::escapeSql($text);
410 // escape for JavaScript (if requested)
411 if (isset($escape) and ($escape == 'js')) {
412 $text = addcslashes($text, "'");
419 * Lookup the raw translation of a string (without any extra escaping or interpolation).
421 * @param string $text
422 * @param string|null $domain
423 * @param int|null $count
424 * @param string $plural
425 * @param string $context
429 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
430 // gettext domain for extensions
431 $domain_changed = FALSE;
432 if (!empty($domain) && $this->_phpgettext
) {
433 if ($this->setGettextDomain($domain)) {
434 $domain_changed = TRUE;
438 // do all wildcard translations first
440 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
441 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
442 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
])) {
443 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
444 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
447 Civi
::$statics[__CLASS__
][$replacementsLocale] = [];
450 $stringTable = Civi
::$statics[__CLASS__
][$replacementsLocale];
453 if (isset($stringTable['enabled']['exactMatch'])) {
454 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
455 if ($search === $text) {
465 isset($stringTable['enabled']['wildcardMatch'])
467 $search = array_keys($stringTable['enabled']['wildcardMatch']);
468 $replace = array_values($stringTable['enabled']['wildcardMatch']);
469 $text = str_replace($search, $replace, $text);
472 // dont translate if we've done exactMatch already
474 // use plural if required parameters are set
475 if (isset($count) && isset($plural)) {
477 if ($this->_phpgettext
) {
478 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
481 // if the locale's not set, we do ngettext work by hand
482 // if $count == 1 then $text = $text, else $text = $plural
488 // expand %count in translated string to $count
489 $text = strtr($text, ['%count' => $count]);
491 // if not plural, but the locale's set, translate
493 elseif ($this->_phpgettext
) {
495 $text = $this->_phpgettext
->pgettext($context, $text);
498 $text = $this->_phpgettext
->translate($text);
503 if ($domain_changed) {
504 $this->setGettextDomain('civicrm');
511 * Translate a string to the current locale.
513 * @param string $string
514 * this string should be translated.
517 * the translated string
519 public function translate($string) {
520 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
524 * Localize (destructively) array values.
526 * @param array $array
527 * the array for localization (in place).
528 * @param array $params
529 * an array of additional parameters.
531 public function localizeArray(
535 $tsLocale = CRM_Core_I18n
::getLocale();
537 if ($tsLocale == 'en_US') {
541 foreach ($array as & $value) {
543 $value = ts($value, $params);
549 * Localize (destructively) array elements with keys of 'title'.
551 * @param array $array
552 * the array for localization (in place).
554 public function localizeTitles(&$array) {
555 foreach ($array as $key => $value) {
556 if (is_array($value)) {
557 $this->localizeTitles($value);
558 $array[$key] = $value;
560 elseif ((string ) $key == 'title') {
561 $array[$key] = ts($value, ['context' => 'menu']);
567 * Binds a gettext domain, wrapper over bindtextdomain().
570 * Key of the extension (can be 'civicrm', or 'org.example.foo').
573 * True if the domain was changed for an extension.
575 public function setGettextDomain($key) {
576 /* No domain changes for en_US */
577 if (!$this->_phpgettext
) {
581 // It's only necessary to find/bind once
582 if (!isset($this->_extensioncache
[$key])) {
584 $mapper = CRM_Extension_System
::singleton()->getMapper();
585 $path = $mapper->keyToBasePath($key);
586 $info = $mapper->keyToInfo($key);
587 $domain = $info->file
;
589 if ($this->_nativegettext
) {
590 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
591 bind_textdomain_codeset($domain, 'UTF-8');
592 $this->_extensioncache
[$key] = $domain;
596 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
597 $streamer = new FileReader($mo_file);
598 $this->_extensioncache
[$key] = new gettext_reader($streamer);
601 catch (CRM_Extension_Exception
$e) {
602 // Intentionally not translating this string to avoid possible infinite loops
603 // Only developers should see this string, if they made a mistake in their ts() usage.
604 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
605 $this->_extensioncache
[$key] = FALSE;
609 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
610 if ($this->_nativegettext
) {
611 textdomain($this->_extensioncache
[$key]);
614 $this->_phpgettext
= $this->_extensioncache
[$key];
624 * Is the CiviCRM in multilingual mode.
627 * True if CiviCRM is in multilingual mode.
629 public static function isMultilingual() {
630 $domain = new CRM_Core_DAO_Domain();
632 return (bool) $domain->locales
;
636 * Is the language written "right-to-left"?
639 * Language (for example 'en_US', or 'fr_CA').
642 * True if it is an RTL language.
644 public static function isLanguageRTL($language) {
645 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
646 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
648 return (in_array($short, $rtl));
652 * Change the processing language without changing the current user language
655 * Locale (for example 'en_US', or 'fr_CA').
656 * True if the domain was changed for an extension.
658 public function setLocale($locale) {
660 // Change the language of the CMS as well, for URLs.
661 CRM_Utils_System
::setUFLocale($locale);
663 // change the gettext ressources
664 if ($this->_nativegettext
) {
665 $this->setNativeGettextLocale($locale);
669 $this->setPhpGettextLocale($locale);
672 // For sql queries, if running in DB multi-lingual mode.
676 $dbLocale = "_{$locale}";
679 // For self::getLocale()
685 * Static instance provider - return the instance for the current locale.
687 * @return CRM_Core_I18n
689 public static function &singleton() {
690 if (!isset(Civi
::$statics[__CLASS__
]['singleton'])) {
691 Civi
::$statics[__CLASS__
]['singleton'] = [];
693 $tsLocale = CRM_Core_I18n
::getLocale();
694 if (!isset(Civi
::$statics[__CLASS__
]['singleton'][$tsLocale])) {
695 Civi
::$statics[__CLASS__
]['singleton'][$tsLocale] = new CRM_Core_I18n($tsLocale);
698 return Civi
::$statics[__CLASS__
]['singleton'][$tsLocale];
702 * Set the LC_TIME locale if it's not set already (for a given language choice).
705 * the final LC_TIME that got set
707 public static function setLcTime() {
708 static $locales = [];
710 $tsLocale = CRM_Core_I18n
::getLocale();
711 if (!isset($locales[$tsLocale])) {
712 // with the config being set to pl_PL: try pl_PL.UTF-8,
713 // then pl_PL, if neither present fall back to C
714 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
717 return $locales[$tsLocale];
721 * Get the default language for contacts where no language is provided.
723 * Note that NULL is a valid option so be careful with checking for empty etc.
725 * NULL would mean 'we don't know & we don't want to hazard a guess'.
729 public static function getContactDefaultLanguage() {
730 $language = Civi
::settings()->get('contact_default_language');
731 if ($language == 'undefined') {
734 if (empty($language) ||
$language === '*default*') {
735 $language = civicrm_api3('setting', 'getvalue', [
736 'name' => 'lcMessages',
737 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
740 elseif ($language == 'current_site_language') {
741 return CRM_Core_I18n
::getLocale();
748 * Get the current locale
752 public static function getLocale() {
754 return $tsLocale ?
$tsLocale : 'en_US';
760 * Short-named function for string translation, defined in global scope so it's available everywhere.
762 * @param string $text
763 * String string for translating.
764 * @param array $params
765 * Array an array of additional parameters.
768 * the translated string
770 function ts($text, $params = []) {
771 static $areSettingsAvailable = FALSE;
772 static $lastLocale = NULL;
774 static $function = NULL;
780 // When the settings become available, lookup customTranslateFunction.
781 if (!$areSettingsAvailable) {
782 $areSettingsAvailable = (bool) \Civi\Core\Container
::getBootService('settings_manager');
783 if ($areSettingsAvailable) {
784 $config = CRM_Core_Config
::singleton();
785 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
786 $function = $config->customTranslateFunction
;
791 $activeLocale = CRM_Core_I18n
::getLocale();
792 if (!$i18n or $lastLocale != $activeLocale) {
793 $i18n = CRM_Core_I18n
::singleton();
794 $lastLocale = $activeLocale;
798 return $function($text, $params);
801 return $i18n->crm_translate($text, $params);