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).
75 private $_phpgettext = NULL;
78 * Whether we are using native gettext or not.
80 private $_nativegettext = FALSE;
83 * Gettext cache for extension domains/streamers, depending on if native or phpgettext.
84 * - native gettext: we cache the value for textdomain()
85 * - phpgettext: we cache the file streamer.
87 private $_extensioncache = array();
95 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
97 * @param string $locale
98 * the base of this certain object's existence.
100 * @return \CRM_Core_I18n
102 public function __construct($locale) {
103 $this->locale
= $locale;
104 if ($locale != '' and $locale != 'en_US') {
105 if (defined('CIVICRM_GETTEXT_NATIVE') && CIVICRM_GETTEXT_NATIVE
&& function_exists('gettext')) {
106 // Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
108 $this->_nativegettext
= TRUE;
109 $this->setNativeGettextLocale($locale);
113 // Otherwise, use PHP-gettext
114 $this->setPhpGettextLocale($locale);
119 * Returns whether gettext is running natively or using PHP-Gettext.
122 * True if gettext is native
124 public function isNative() {
125 return $this->_nativegettext
;
129 * Set native locale for getText.
131 * @param string $locale
133 protected function setNativeGettextLocale($locale) {
136 putenv("LANG=$locale");
138 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
139 setlocale(LC_TIME
, $locale);
140 setlocale(LC_MESSAGES
, $locale);
141 setlocale(LC_CTYPE
, $locale);
143 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
144 bind_textdomain_codeset('civicrm', 'UTF-8');
145 textdomain('civicrm');
147 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
148 $this->_extensioncache
['civicrm'] = 'civicrm';
153 * Set getText locale.
155 * @param string $locale
157 protected function setPhpGettextLocale($locale) {
159 // we support both the old file hierarchy format and the new:
160 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
161 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
162 require_once 'PHPgettext/streams.php';
163 require_once 'PHPgettext/gettext.php';
165 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
167 if (!file_exists($mo_file)) {
168 // fallback to pre-4.5 mode
169 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'civicrm.mo';
172 $streamer = new FileReader($mo_file);
173 $this->_phpgettext
= new gettext_reader($streamer);
174 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
179 * Return languages available in this instance of CiviCRM.
181 * @param bool $justEnabled
182 * whether to return all languages or just the enabled ones.
185 * Array of code/language name mappings
187 public static function languages($justEnabled = FALSE) {
189 static $enabled = NULL;
192 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
197 CRM_Core_OptionValue
::getValues(array('name' => 'languages'), $rows);
198 foreach ($rows as $id => $row) {
199 $labels[$row['name']] = $row['label'];
202 // check which ones are available; add them to $all if not there already
204 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
205 while ($filename = readdir($dir)) {
206 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
207 $codes[] = $filename;
208 if (!isset($all[$filename])) {
209 $all[$filename] = $labels[$filename];
216 // drop the unavailable languages (except en_US)
217 foreach (array_keys($all) as $code) {
218 if ($code == 'en_US') {
221 if (!in_array($code, $codes)) {
229 if ($enabled === NULL) {
230 $config = CRM_Core_Config
::singleton();
232 if (isset($config->languageLimit
) and $config->languageLimit
) {
233 foreach ($all as $code => $name) {
234 if (in_array($code, array_keys($config->languageLimit
))) {
235 $enabled[$code] = $name;
241 return $justEnabled ?
$enabled : $all;
245 * Return the available UI languages
246 * @return array(string languageCode) if $justCodes
247 * array(string languageCode => string languageName) if !$justCodes
249 public static function uiLanguages($justCodes = FALSE) {
250 // In multilang we only allow the languages that are configured in db
251 // Otherwise, the languages configured in uiLanguages
252 $settings = Civi
::settings();
253 if (CRM_Core_I18n
::isMultiLingual()) {
254 $codes = array_keys((array) $settings->get('languageLimit'));
257 $codes = $settings->get('uiLanguages');
259 $codes = [$settings->get('lcMessages')];
262 return $justCodes ?
$codes
263 : CRM_Utils_Array
::subset(CRM_Core_I18n
::languages(), $codes);
267 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
275 public function strarg($str) {
278 for ($i = 1; $i < func_num_args(); $i++
) {
279 $arg = func_get_arg($i);
280 if (is_array($arg)) {
281 foreach ($arg as $aarg) {
282 $tr['%' . ++
$p] = $aarg;
286 $tr['%' . ++
$p] = $arg;
289 return strtr($str, $tr);
293 * Get the directory for l10n resources.
297 public static function getResourceDir() {
300 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
306 * Smarty block function, provides gettext support for smarty.
308 * The block content is the text that should be translated.
310 * Any parameter that is sent to the function will be represented as %n in the translation text,
311 * where n is 1 for the first parameter. The following parameters are reserved:
312 * - escape - sets escape mode:
313 * - 'html' for HTML escaping, this is the default.
314 * - 'js' for javascript escaping.
315 * - 'no'/'off'/0 - turns off escaping
316 * - plural - The plural version of the text (2nd parameter of ngettext())
317 * - count - The item count for plural mode (3rd parameter of ngettext())
318 * - context - gettext context of that string (for homonym handling)
320 * @param string $text
321 * the original string.
322 * @param array $params
323 * The params of the translation (if any).
324 * - domain: string|array a list of translation domains to search (in order)
328 * the translated string
330 public function crm_translate($text, $params = array()) {
331 if (isset($params['escape'])) {
332 $escape = $params['escape'];
333 unset($params['escape']);
336 // sometimes we need to {ts}-tag a string, but don’t want to
337 // translate it in the template (like civicrm_navigation.tpl),
338 // because we handle the translation in a different way (CRM-6998)
339 // in such cases we return early, only doing SQL/JS escaping
340 if (isset($params['skip']) and $params['skip']) {
341 if (isset($escape) and ($escape == 'sql')) {
342 $text = self
::escapeSql($text);
344 if (isset($escape) and ($escape == 'js')) {
345 $text = addcslashes($text, "'");
350 $plural = $count = NULL;
351 if (isset($params['plural'])) {
352 $plural = $params['plural'];
353 unset($params['plural']);
354 if (isset($params['count'])) {
355 $count = $params['count'];
359 if (isset($params['context'])) {
360 $context = $params['context'];
361 unset($params['context']);
367 if (isset($params['domain'])) {
368 $domain = $params['domain'];
369 unset($params['domain']);
375 $raw = !empty($params['raw']);
376 unset($params['raw']);
378 if (!empty($domain)) {
379 // It might be prettier to cast to an array, but this is high-traffic stuff.
380 if (is_array($domain)) {
381 foreach ($domain as $d) {
382 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
383 if ($candidate != $text) {
390 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
394 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
397 // replace the numbered %1, %2, etc. params if present
398 if (count($params) && !$raw) {
399 $text = $this->strarg($text, $params);
402 // escape SQL if we were asked for it
403 if (isset($escape) and ($escape == 'sql')) {
404 $text = self
::escapeSql($text);
407 // escape for JavaScript (if requested)
408 if (isset($escape) and ($escape == 'js')) {
409 $text = addcslashes($text, "'");
416 * Lookup the raw translation of a string (without any extra escaping or interpolation).
418 * @param string $text
419 * @param string|NULL $domain
420 * @param int|NULL $count
421 * @param string $plural
422 * @param string $context
426 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
427 // gettext domain for extensions
428 $domain_changed = FALSE;
429 if (!empty($domain) && $this->_phpgettext
) {
430 if ($this->setGettextDomain($domain)) {
431 $domain_changed = TRUE;
435 // do all wildcard translations first
437 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
438 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
439 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
])) {
440 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
441 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
444 Civi
::$statics[__CLASS__
][$replacementsLocale] = array();
447 $stringTable = Civi
::$statics[__CLASS__
][$replacementsLocale];
450 if (isset($stringTable['enabled']['exactMatch'])) {
451 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
452 if ($search === $text) {
462 isset($stringTable['enabled']['wildcardMatch'])
464 $search = array_keys($stringTable['enabled']['wildcardMatch']);
465 $replace = array_values($stringTable['enabled']['wildcardMatch']);
466 $text = str_replace($search, $replace, $text);
469 // dont translate if we've done exactMatch already
471 // use plural if required parameters are set
472 if (isset($count) && isset($plural)) {
474 if ($this->_phpgettext
) {
475 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
478 // if the locale's not set, we do ngettext work by hand
479 // if $count == 1 then $text = $text, else $text = $plural
485 // expand %count in translated string to $count
486 $text = strtr($text, array('%count' => $count));
488 // if not plural, but the locale's set, translate
490 elseif ($this->_phpgettext
) {
492 $text = $this->_phpgettext
->pgettext($context, $text);
495 $text = $this->_phpgettext
->translate($text);
500 if ($domain_changed) {
501 $this->setGettextDomain('civicrm');
508 * Translate a string to the current locale.
510 * @param string $string
511 * this string should be translated.
514 * the translated string
516 public function translate($string) {
517 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
521 * Localize (destructively) array values.
523 * @param array $array
524 * the array for localization (in place).
525 * @param array $params
526 * an array of additional parameters.
528 public function localizeArray(
532 $tsLocale = CRM_Core_I18n
::getLocale();
534 if ($tsLocale == 'en_US') {
538 foreach ($array as & $value) {
540 $value = ts($value, $params);
546 * Localize (destructively) array elements with keys of 'title'.
548 * @param array $array
549 * the array for localization (in place).
551 public function localizeTitles(&$array) {
552 foreach ($array as $key => $value) {
553 if (is_array($value)) {
554 $this->localizeTitles($value);
555 $array[$key] = $value;
557 elseif ((string ) $key == 'title') {
558 $array[$key] = ts($value, array('context' => 'menu'));
564 * Binds a gettext domain, wrapper over bindtextdomain().
567 * Key of the extension (can be 'civicrm', or 'org.example.foo').
570 * True if the domain was changed for an extension.
572 public function setGettextDomain($key) {
573 /* No domain changes for en_US */
574 if (!$this->_phpgettext
) {
578 // It's only necessary to find/bind once
579 if (!isset($this->_extensioncache
[$key])) {
581 $mapper = CRM_Extension_System
::singleton()->getMapper();
582 $path = $mapper->keyToBasePath($key);
583 $info = $mapper->keyToInfo($key);
584 $domain = $info->file
;
586 if ($this->_nativegettext
) {
587 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
588 bind_textdomain_codeset($domain, 'UTF-8');
589 $this->_extensioncache
[$key] = $domain;
593 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
594 $streamer = new FileReader($mo_file);
595 $this->_extensioncache
[$key] = new gettext_reader($streamer);
598 catch (CRM_Extension_Exception
$e) {
599 // Intentionally not translating this string to avoid possible infinite loops
600 // Only developers should see this string, if they made a mistake in their ts() usage.
601 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
602 $this->_extensioncache
[$key] = FALSE;
606 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
607 if ($this->_nativegettext
) {
608 textdomain($this->_extensioncache
[$key]);
611 $this->_phpgettext
= $this->_extensioncache
[$key];
622 * Is the CiviCRM in multilingual mode.
625 * True if CiviCRM is in multilingual mode.
627 public static function isMultilingual() {
628 $domain = new CRM_Core_DAO_Domain();
630 return (bool) $domain->locales
;
634 * Is the language written "right-to-left"?
637 * Language (for example 'en_US', or 'fr_CA').
640 * True if it is an RTL language.
642 public static function isLanguageRTL($language) {
643 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
644 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
646 return (in_array($short, $rtl));
650 * Change the processing language without changing the current user language
653 * Locale (for example 'en_US', or 'fr_CA').
654 * True if the domain was changed for an extension.
656 public function setLocale($locale) {
658 // Change the language of the CMS as well, for URLs.
659 CRM_Utils_System
::setUFLocale($locale);
661 // change the gettext ressources
662 if ($this->_nativegettext
) {
663 $this->setNativeGettextLocale($locale);
667 $this->setPhpGettextLocale($locale);
672 $dbLocale = "_{$locale}";
674 // For self::getLocale()
680 * Static instance provider - return the instance for the current locale.
682 * @return CRM_Core_I18n
684 public static function &singleton() {
685 if (!isset(Civi
::$statics[__CLASS__
]['singleton'])) {
686 Civi
::$statics[__CLASS__
]['singleton'] = array();
688 $tsLocale = CRM_Core_I18n
::getLocale();
689 if (!isset(Civi
::$statics[__CLASS__
]['singleton'][$tsLocale])) {
690 Civi
::$statics[__CLASS__
]['singleton'][$tsLocale] = new CRM_Core_I18n($tsLocale);
693 return Civi
::$statics[__CLASS__
]['singleton'][$tsLocale];
697 * Set the LC_TIME locale if it's not set already (for a given language choice).
700 * the final LC_TIME that got set
702 public static function setLcTime() {
703 static $locales = array();
705 $tsLocale = CRM_Core_I18n
::getLocale();
706 if (!isset($locales[$tsLocale])) {
707 // with the config being set to pl_PL: try pl_PL.UTF-8,
708 // then pl_PL, if neither present fall back to C
709 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
712 return $locales[$tsLocale];
716 * Get the default language for contacts where no language is provided.
718 * Note that NULL is a valid option so be careful with checking for empty etc.
720 * NULL would mean 'we don't know & we don't want to hazard a guess'.
724 public static function getContactDefaultLanguage() {
725 $language = Civi
::settings()->get('contact_default_language');
726 if ($language == 'undefined') {
729 if (empty($language) ||
$language === '*default*') {
730 $language = civicrm_api3('setting', 'getvalue', array(
731 'name' => 'lcMessages',
732 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
735 elseif ($language == 'current_site_language') {
736 return CRM_Core_I18n
::getLocale();
743 * Get the current locale
747 public static function getLocale() {
749 return $tsLocale ?
$tsLocale : 'en_US';
755 * Short-named function for string translation, defined in global scope so it's available everywhere.
757 * @param string $text
758 * String string for translating.
759 * @param array $params
760 * Array an array of additional parameters.
763 * the translated string
765 function ts($text, $params = array()) {
766 static $areSettingsAvailable = FALSE;
767 static $lastLocale = NULL;
769 static $function = NULL;
775 // When the settings become available, lookup customTranslateFunction.
776 if (!$areSettingsAvailable) {
777 $areSettingsAvailable = (bool) \Civi\Core\Container
::getBootService('settings_manager');
778 if ($areSettingsAvailable) {
779 $config = CRM_Core_Config
::singleton();
780 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
781 $function = $config->customTranslateFunction
;
786 $activeLocale = CRM_Core_I18n
::getLocale();
787 if (!$i18n or $lastLocale != $activeLocale) {
788 $i18n = CRM_Core_I18n
::singleton();
789 $lastLocale = $activeLocale;
793 return $function($text, $params);
796 return $i18n->crm_translate($text, $params);