3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
253 public function strarg($str) {
256 for ($i = 1; $i < func_num_args(); $i++
) {
257 $arg = func_get_arg($i);
258 if (is_array($arg)) {
259 foreach ($arg as $aarg) {
260 $tr['%' . ++
$p] = $aarg;
264 $tr['%' . ++
$p] = $arg;
267 return strtr($str, $tr);
271 * Get the directory for l10n resources.
275 public static function getResourceDir() {
278 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
284 * Smarty block function, provides gettext support for smarty.
286 * The block content is the text that should be translated.
288 * Any parameter that is sent to the function will be represented as %n in the translation text,
289 * where n is 1 for the first parameter. The following parameters are reserved:
290 * - escape - sets escape mode:
291 * - 'html' for HTML escaping, this is the default.
292 * - 'js' for javascript escaping.
293 * - 'no'/'off'/0 - turns off escaping
294 * - plural - The plural version of the text (2nd parameter of ngettext())
295 * - count - The item count for plural mode (3rd parameter of ngettext())
296 * - context - gettext context of that string (for homonym handling)
298 * @param string $text
299 * the original string.
300 * @param array $params
301 * The params of the translation (if any).
302 * - domain: string|array a list of translation domains to search (in order)
306 * the translated string
308 public function crm_translate($text, $params = array()) {
309 if (isset($params['escape'])) {
310 $escape = $params['escape'];
311 unset($params['escape']);
314 // sometimes we need to {ts}-tag a string, but don’t want to
315 // translate it in the template (like civicrm_navigation.tpl),
316 // because we handle the translation in a different way (CRM-6998)
317 // in such cases we return early, only doing SQL/JS escaping
318 if (isset($params['skip']) and $params['skip']) {
319 if (isset($escape) and ($escape == 'sql')) {
320 $text = self
::escapeSql($text);
322 if (isset($escape) and ($escape == 'js')) {
323 $text = addcslashes($text, "'");
328 $plural = $count = NULL;
329 if (isset($params['plural'])) {
330 $plural = $params['plural'];
331 unset($params['plural']);
332 if (isset($params['count'])) {
333 $count = $params['count'];
337 if (isset($params['context'])) {
338 $context = $params['context'];
339 unset($params['context']);
345 if (isset($params['domain'])) {
346 $domain = $params['domain'];
347 unset($params['domain']);
353 $raw = !empty($params['raw']);
354 unset($params['raw']);
356 if (!empty($domain)) {
357 // It might be prettier to cast to an array, but this is high-traffic stuff.
358 if (is_array($domain)) {
359 foreach ($domain as $d) {
360 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
361 if ($candidate != $text) {
368 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
372 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
375 // replace the numbered %1, %2, etc. params if present
376 if (count($params) && !$raw) {
377 $text = $this->strarg($text, $params);
380 // escape SQL if we were asked for it
381 if (isset($escape) and ($escape == 'sql')) {
382 $text = self
::escapeSql($text);
385 // escape for JavaScript (if requested)
386 if (isset($escape) and ($escape == 'js')) {
387 $text = addcslashes($text, "'");
394 * Lookup the raw translation of a string (without any extra escaping or interpolation).
396 * @param string $text
397 * @param string|NULL $domain
398 * @param int|NULL $count
399 * @param string $plural
400 * @param string $context
404 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
405 // gettext domain for extensions
406 $domain_changed = FALSE;
407 if (!empty($domain) && $this->_phpgettext
) {
408 if ($this->setGettextDomain($domain)) {
409 $domain_changed = TRUE;
413 // do all wildcard translations first
415 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
416 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
417 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
])) {
418 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
419 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
422 Civi
::$statics[__CLASS__
][$replacementsLocale] = array();
425 $stringTable = Civi
::$statics[__CLASS__
][$replacementsLocale];
428 if (isset($stringTable['enabled']['exactMatch'])) {
429 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
430 if ($search === $text) {
440 isset($stringTable['enabled']['wildcardMatch'])
442 $search = array_keys($stringTable['enabled']['wildcardMatch']);
443 $replace = array_values($stringTable['enabled']['wildcardMatch']);
444 $text = str_replace($search, $replace, $text);
447 // dont translate if we've done exactMatch already
449 // use plural if required parameters are set
450 if (isset($count) && isset($plural)) {
452 if ($this->_phpgettext
) {
453 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
456 // if the locale's not set, we do ngettext work by hand
457 // if $count == 1 then $text = $text, else $text = $plural
463 // expand %count in translated string to $count
464 $text = strtr($text, array('%count' => $count));
466 // if not plural, but the locale's set, translate
468 elseif ($this->_phpgettext
) {
470 $text = $this->_phpgettext
->pgettext($context, $text);
473 $text = $this->_phpgettext
->translate($text);
478 if ($domain_changed) {
479 $this->setGettextDomain('civicrm');
486 * Translate a string to the current locale.
488 * @param string $string
489 * this string should be translated.
492 * the translated string
494 public function translate($string) {
495 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
499 * Localize (destructively) array values.
501 * @param array $array
502 * the array for localization (in place).
503 * @param array $params
504 * an array of additional parameters.
506 public function localizeArray(
510 $tsLocale = CRM_Core_I18n
::getLocale();
512 if ($tsLocale == 'en_US') {
516 foreach ($array as & $value) {
518 $value = ts($value, $params);
524 * Localize (destructively) array elements with keys of 'title'.
526 * @param array $array
527 * the array for localization (in place).
529 public function localizeTitles(&$array) {
530 foreach ($array as $key => $value) {
531 if (is_array($value)) {
532 $this->localizeTitles($value);
533 $array[$key] = $value;
535 elseif ((string ) $key == 'title') {
536 $array[$key] = ts($value, array('context' => 'menu'));
542 * Binds a gettext domain, wrapper over bindtextdomain().
545 * Key of the extension (can be 'civicrm', or 'org.example.foo').
548 * True if the domain was changed for an extension.
550 public function setGettextDomain($key) {
551 /* No domain changes for en_US */
552 if (!$this->_phpgettext
) {
556 // It's only necessary to find/bind once
557 if (!isset($this->_extensioncache
[$key])) {
559 $mapper = CRM_Extension_System
::singleton()->getMapper();
560 $path = $mapper->keyToBasePath($key);
561 $info = $mapper->keyToInfo($key);
562 $domain = $info->file
;
564 if ($this->_nativegettext
) {
565 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
566 bind_textdomain_codeset($domain, 'UTF-8');
567 $this->_extensioncache
[$key] = $domain;
571 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
572 $streamer = new FileReader($mo_file);
573 $this->_extensioncache
[$key] = new gettext_reader($streamer);
576 catch (CRM_Extension_Exception
$e) {
577 // Intentionally not translating this string to avoid possible infinite loops
578 // Only developers should see this string, if they made a mistake in their ts() usage.
579 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
580 $this->_extensioncache
[$key] = FALSE;
584 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
585 if ($this->_nativegettext
) {
586 textdomain($this->_extensioncache
[$key]);
589 $this->_phpgettext
= $this->_extensioncache
[$key];
600 * Is the CiviCRM in multilingual mode.
603 * True if CiviCRM is in multilingual mode.
605 public static function isMultilingual() {
606 $domain = new CRM_Core_DAO_Domain();
608 return (bool) $domain->locales
;
612 * Is the language written "right-to-left"?
615 * Language (for example 'en_US', or 'fr_CA').
618 * True if it is an RTL language.
620 public static function isLanguageRTL($language) {
621 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
622 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
624 return (in_array($short, $rtl));
628 * Change the processing language without changing the current user language
631 * Locale (for example 'en_US', or 'fr_CA').
632 * True if the domain was changed for an extension.
634 public function setLocale($locale) {
636 // Change the language of the CMS as well, for URLs.
637 CRM_Utils_System
::setUFLocale($locale);
639 // change the gettext ressources
640 if ($this->_nativegettext
) {
641 $this->setNativeGettextLocale($locale);
645 $this->setPhpGettextLocale($locale);
650 $dbLocale = "_{$locale}";
655 * Static instance provider - return the instance for the current locale.
657 * @return CRM_Core_I18n
659 public static function &singleton() {
660 static $singleton = array();
662 $tsLocale = CRM_Core_I18n
::getLocale();
663 if (!isset($singleton[$tsLocale])) {
664 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
667 return $singleton[$tsLocale];
671 * Set the LC_TIME locale if it's not set already (for a given language choice).
674 * the final LC_TIME that got set
676 public static function setLcTime() {
677 static $locales = array();
679 $tsLocale = CRM_Core_I18n
::getLocale();
680 if (!isset($locales[$tsLocale])) {
681 // with the config being set to pl_PL: try pl_PL.UTF-8,
682 // then pl_PL, if neither present fall back to C
683 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
686 return $locales[$tsLocale];
690 * Get the default language for contacts where no language is provided.
692 * Note that NULL is a valid option so be careful with checking for empty etc.
694 * NULL would mean 'we don't know & we don't want to hazard a guess'.
698 public static function getContactDefaultLanguage() {
699 $language = Civi
::settings()->get('contact_default_language');
700 if ($language == 'undefined') {
703 if (empty($language) ||
$language === '*default*') {
704 $language = civicrm_api3('setting', 'getvalue', array(
705 'name' => 'lcMessages',
706 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
709 elseif ($language == 'current_site_language') {
710 return CRM_Core_I18n
::getLocale();
717 * Get the current locale
721 public static function getLocale() {
723 return $tsLocale ?
$tsLocale : 'en_US';
729 * Short-named function for string translation, defined in global scope so it's available everywhere.
731 * @param string $text
732 * String string for translating.
733 * @param array $params
734 * Array an array of additional parameters.
737 * the translated string
739 function ts($text, $params = array()) {
740 static $areSettingsAvailable = FALSE;
741 static $lastLocale = NULL;
743 static $function = NULL;
749 // When the settings become available, lookup customTranslateFunction.
750 if (!$areSettingsAvailable) {
751 $areSettingsAvailable = (bool) \Civi\Core\Container
::getBootService('settings_manager');
752 if ($areSettingsAvailable) {
753 $config = CRM_Core_Config
::singleton();
754 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
755 $function = $config->customTranslateFunction
;
760 $activeLocale = CRM_Core_I18n
::getLocale();
761 if (!$i18n or $lastLocale != $activeLocale) {
762 $i18n = CRM_Core_I18n
::singleton();
763 $lastLocale = $activeLocale;
767 return $function($text, $params);
770 return $i18n->crm_translate($text, $params);