3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
36 * Constants for communication preferences.
40 const NONE
= 'none', AUTO
= 'auto';
44 * A PHP-gettext instance for string translation;
45 * should stay null if the strings are not to be translated (en_US).
47 private $_phpgettext = NULL;
50 * Whether we are using native gettext or not.
52 private $_nativegettext = FALSE;
55 * Gettext cache for extension domains/streamers, depending on if native or phpgettext.
56 * - native gettext: we cache the value for textdomain()
57 * - phpgettext: we cache the file streamer.
59 private $_extensioncache = array();
67 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
69 * @param string $locale
70 * the base of this certain object's existence.
72 * @return \CRM_Core_I18n
74 public function __construct($locale) {
75 $this->locale
= $locale;
76 if ($locale != '' and $locale != 'en_US') {
77 if (defined('CIVICRM_GETTEXT_NATIVE') && CIVICRM_GETTEXT_NATIVE
&& function_exists('gettext')) {
78 // Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
80 $this->_nativegettext
= TRUE;
81 $this->setNativeGettextLocale($locale);
85 // Otherwise, use PHP-gettext
86 $this->setPhpGettextLocale($locale);
91 * Returns whether gettext is running natively or using PHP-Gettext.
94 * True if gettext is native
96 public function isNative() {
97 return $this->_nativegettext
;
101 protected function setNativeGettextLocale($locale) {
104 putenv("LANG=$locale");
106 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
107 setlocale(LC_TIME
, $locale);
108 setlocale(LC_MESSAGES
, $locale);
109 setlocale(LC_CTYPE
, $locale);
111 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
112 bind_textdomain_codeset('civicrm', 'UTF-8');
113 textdomain('civicrm');
115 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
116 $this->_extensioncache
['civicrm'] = 'civicrm';
120 protected function setPhpGettextLocale($locale) {
122 // we support both the old file hierarchy format and the new:
123 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
124 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
125 require_once 'PHPgettext/streams.php';
126 require_once 'PHPgettext/gettext.php';
128 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
130 if (!file_exists($mo_file)) {
131 // fallback to pre-4.5 mode
132 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'civicrm.mo';
135 $streamer = new FileReader($mo_file);
136 $this->_phpgettext
= new gettext_reader($streamer);
137 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
143 * Return languages available in this instance of CiviCRM.
145 * @param bool $justEnabled
146 * whether to return all languages or just the enabled ones.
149 * Array of code/language name mappings
151 public static function languages($justEnabled = FALSE) {
153 static $enabled = NULL;
156 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
158 // check which ones are available; add them to $all if not there already
160 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
161 while ($filename = readdir($dir)) {
162 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
163 $codes[] = $filename;
164 if (!isset($all[$filename])) {
165 $all[$filename] = $filename;
172 // drop the unavailable languages (except en_US)
173 foreach (array_keys($all) as $code) {
174 if ($code == 'en_US') {
177 if (!in_array($code, $codes)) {
183 if ($enabled === NULL) {
184 $config = CRM_Core_Config
::singleton();
186 if (isset($config->languageLimit
) and $config->languageLimit
) {
187 foreach ($all as $code => $name) {
188 if (in_array($code, array_keys($config->languageLimit
))) {
189 $enabled[$code] = $name;
195 return $justEnabled ?
$enabled : $all;
199 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
207 public function strarg($str) {
210 for ($i = 1; $i < func_num_args(); $i++
) {
211 $arg = func_get_arg($i);
212 if (is_array($arg)) {
213 foreach ($arg as $aarg) {
214 $tr['%' . ++
$p] = $aarg;
218 $tr['%' . ++
$p] = $arg;
221 return strtr($str, $tr);
224 public static function getResourceDir() {
227 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
233 * Smarty block function, provides gettext support for smarty.
235 * The block content is the text that should be translated.
237 * Any parameter that is sent to the function will be represented as %n in the translation text,
238 * where n is 1 for the first parameter. The following parameters are reserved:
239 * - escape - sets escape mode:
240 * - 'html' for HTML escaping, this is the default.
241 * - 'js' for javascript escaping.
242 * - 'no'/'off'/0 - turns off escaping
243 * - plural - The plural version of the text (2nd parameter of ngettext())
244 * - count - The item count for plural mode (3rd parameter of ngettext())
245 * - context - gettext context of that string (for homonym handling)
247 * @param string $text
248 * the original string.
249 * @param array $params
250 * The params of the translation (if any).
251 * - domain: string|array a list of translation domains to search (in order)
255 * the translated string
257 public function crm_translate($text, $params = array()) {
258 if (isset($params['escape'])) {
259 $escape = $params['escape'];
260 unset($params['escape']);
263 // sometimes we need to {ts}-tag a string, but don’t want to
264 // translate it in the template (like civicrm_navigation.tpl),
265 // because we handle the translation in a different way (CRM-6998)
266 // in such cases we return early, only doing SQL/JS escaping
267 if (isset($params['skip']) and $params['skip']) {
268 if (isset($escape) and ($escape == 'sql')) {
269 $text = CRM_Core_DAO
::escapeString($text);
271 if (isset($escape) and ($escape == 'js')) {
272 $text = addcslashes($text, "'");
277 $plural = $count = NULL;
278 if (isset($params['plural'])) {
279 $plural = $params['plural'];
280 unset($params['plural']);
281 if (isset($params['count'])) {
282 $count = $params['count'];
286 if (isset($params['context'])) {
287 $context = $params['context'];
288 unset($params['context']);
294 if (isset($params['domain'])) {
295 $domain = $params['domain'];
296 unset($params['domain']);
302 $raw = !empty($params['raw']);
303 unset($params['raw']);
305 if (!empty($domain)) {
306 // It might be prettier to cast to an array, but this is high-traffic stuff.
307 if (is_array($domain)) {
308 foreach ($domain as $d) {
309 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
310 if ($candidate != $text) {
317 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
321 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
324 // replace the numbered %1, %2, etc. params if present
325 if (count($params) && !$raw) {
326 $text = $this->strarg($text, $params);
329 // escape SQL if we were asked for it
330 if (isset($escape) and ($escape == 'sql')) {
331 $text = CRM_Core_DAO
::escapeString($text);
334 // escape for JavaScript (if requested)
335 if (isset($escape) and ($escape == 'js')) {
336 $text = addcslashes($text, "'");
343 * Lookup the raw translation of a string (without any extra escaping or interpolation).
345 * @param string $text
346 * @param string|NULL $domain
347 * @param int|NULL $count
348 * @param string $plural
349 * @param string $context
353 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
354 // gettext domain for extensions
355 $domain_changed = FALSE;
356 if (!empty($domain) && $this->_phpgettext
) {
357 if ($this->setGettextDomain($domain)) {
358 $domain_changed = TRUE;
362 // do all wildcard translations first
364 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
365 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
366 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
])) {
367 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
368 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
371 Civi
::$statics[__CLASS__
][$replacementsLocale] = array();
374 $stringTable = Civi
::$statics[__CLASS__
][$replacementsLocale];
377 if (isset($stringTable['enabled']['exactMatch'])) {
378 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
379 if ($search === $text) {
389 isset($stringTable['enabled']['wildcardMatch'])
391 $search = array_keys($stringTable['enabled']['wildcardMatch']);
392 $replace = array_values($stringTable['enabled']['wildcardMatch']);
393 $text = str_replace($search, $replace, $text);
396 // dont translate if we've done exactMatch already
398 // use plural if required parameters are set
399 if (isset($count) && isset($plural)) {
401 if ($this->_phpgettext
) {
402 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
405 // if the locale's not set, we do ngettext work by hand
406 // if $count == 1 then $text = $text, else $text = $plural
412 // expand %count in translated string to $count
413 $text = strtr($text, array('%count' => $count));
415 // if not plural, but the locale's set, translate
417 elseif ($this->_phpgettext
) {
419 $text = $this->_phpgettext
->pgettext($context, $text);
422 $text = $this->_phpgettext
->translate($text);
427 if ($domain_changed) {
428 $this->setGettextDomain('civicrm');
435 * Translate a string to the current locale.
437 * @param string $string
438 * this string should be translated.
441 * the translated string
443 public function translate($string) {
444 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
448 * Localize (destructively) array values.
450 * @param array $array
451 * the array for localization (in place).
452 * @param array $params
453 * an array of additional parameters.
455 public function localizeArray(
459 $tsLocale = CRM_Core_I18n
::getLocale();
461 if ($tsLocale == 'en_US') {
465 foreach ($array as & $value) {
467 $value = ts($value, $params);
473 * Localize (destructively) array elements with keys of 'title'.
475 * @param array $array
476 * the array for localization (in place).
478 public function localizeTitles(&$array) {
479 foreach ($array as $key => $value) {
480 if (is_array($value)) {
481 $this->localizeTitles($value);
482 $array[$key] = $value;
484 elseif ((string ) $key == 'title') {
485 $array[$key] = ts($value, array('context' => 'menu'));
491 * Binds a gettext domain, wrapper over bindtextdomain().
494 * Key of the extension (can be 'civicrm', or 'org.example.foo').
497 * True if the domain was changed for an extension.
499 public function setGettextDomain($key) {
500 /* No domain changes for en_US */
501 if (!$this->_phpgettext
) {
505 // It's only necessary to find/bind once
506 if (!isset($this->_extensioncache
[$key])) {
508 $mapper = CRM_Extension_System
::singleton()->getMapper();
509 $path = $mapper->keyToBasePath($key);
510 $info = $mapper->keyToInfo($key);
511 $domain = $info->file
;
513 if ($this->_nativegettext
) {
514 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
515 bind_textdomain_codeset($domain, 'UTF-8');
516 $this->_extensioncache
[$key] = $domain;
520 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
521 $streamer = new FileReader($mo_file);
522 $this->_extensioncache
[$key] = new gettext_reader($streamer);
525 catch (CRM_Extension_Exception
$e) {
526 // Intentionally not translating this string to avoid possible infinite loops
527 // Only developers should see this string, if they made a mistake in their ts() usage.
528 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
529 $this->_extensioncache
[$key] = FALSE;
533 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
534 if ($this->_nativegettext
) {
535 textdomain($this->_extensioncache
[$key]);
538 $this->_phpgettext
= $this->_extensioncache
[$key];
549 * Is the CiviCRM in multilingual mode.
552 * True if CiviCRM is in multilingual mode.
554 public static function isMultilingual() {
555 $domain = new CRM_Core_DAO_Domain();
557 return (bool) $domain->locales
;
561 * Is the language written "right-to-left"?
564 * Language (for example 'en_US', or 'fr_CA').
567 * True if it is an RTL language.
569 public static function isLanguageRTL($language) {
570 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
571 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
573 return (in_array($short, $rtl));
577 * Change the processing language without changing the current user language
580 * Locale (for example 'en_US', or 'fr_CA').
581 * True if the domain was changed for an extension.
583 public function setLocale($locale) {
585 // Change the language of the CMS as well, for URLs.
586 CRM_Utils_System
::setUFLocale($locale);
588 // change the gettext ressources
589 if ($this->_nativegettext
) {
590 $this->setNativeGettextLocale($locale);
594 $this->setPhpGettextLocale($locale);
599 $dbLocale = "_{$locale}";
604 * Static instance provider - return the instance for the current locale.
606 * @return CRM_Core_I18n
608 public static function &singleton() {
609 static $singleton = array();
611 $tsLocale = CRM_Core_I18n
::getLocale();
612 if (!isset($singleton[$tsLocale])) {
613 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
616 return $singleton[$tsLocale];
620 * Set the LC_TIME locale if it's not set already (for a given language choice).
623 * the final LC_TIME that got set
625 public static function setLcTime() {
626 static $locales = array();
628 $tsLocale = CRM_Core_I18n
::getLocale();
629 if (!isset($locales[$tsLocale])) {
630 // with the config being set to pl_PL: try pl_PL.UTF-8,
631 // then pl_PL, if neither present fall back to C
632 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
635 return $locales[$tsLocale];
639 * Get the default language for contacts where no language is provided.
641 * Note that NULL is a valid option so be careful with checking for empty etc.
643 * NULL would mean 'we don't know & we don't want to hazard a guess'.
647 public static function getContactDefaultLanguage() {
648 $language = Civi
::settings()->get('contact_default_language');
649 if ($language == 'undefined') {
652 if (empty($language) ||
$language === '*default*') {
653 $language = civicrm_api3('setting', 'getvalue', array(
654 'name' => 'lcMessages',
655 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
658 elseif ($language == 'current_site_language') {
659 return CRM_Core_I18n
::getLocale();
666 * Get the current locale
670 public static function getLocale() {
672 return $tsLocale ?
$tsLocale : 'en_US';
678 * Short-named function for string translation, defined in global scope so it's available everywhere.
680 * @param string $text
681 * String string for translating.
682 * @param array $params
683 * Array an array of additional parameters.
686 * the translated string
688 function ts($text, $params = array()) {
689 static $config = NULL;
690 static $locale = NULL;
692 static $function = NULL;
699 $config = CRM_Core_Config
::singleton();
702 $tsLocale = CRM_Core_I18n
::getLocale();
703 if (!$i18n or $locale != $tsLocale) {
704 $i18n = CRM_Core_I18n
::singleton();
706 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
707 $function = $config->customTranslateFunction
;
712 return $function($text, $params);
715 return $i18n->crm_translate($text, $params);