3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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;
83 putenv("LANG=$locale");
85 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
86 setlocale(LC_TIME
, $locale);
87 setlocale(LC_MESSAGES
, $locale);
88 setlocale(LC_CTYPE
, $locale);
90 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
91 bind_textdomain_codeset('civicrm', 'UTF-8');
92 textdomain('civicrm');
94 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
95 $this->_extensioncache
['civicrm'] = 'civicrm';
99 // Otherwise, use PHP-gettext
100 // we support both the old file hierarchy format and the new:
101 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
102 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
103 require_once 'PHPgettext/streams.php';
104 require_once 'PHPgettext/gettext.php';
106 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
108 if (!file_exists($mo_file)) {
109 // fallback to pre-4.5 mode
110 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'civicrm.mo';
113 $streamer = new FileReader($mo_file);
114 $this->_phpgettext
= new gettext_reader($streamer);
115 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
120 * Returns whether gettext is running natively or using PHP-Gettext.
123 * True if gettext is native
125 public function isNative() {
126 return $this->_nativegettext
;
130 * Return languages available in this instance of CiviCRM.
132 * @param bool $justEnabled
133 * whether to return all languages or just the enabled ones.
136 * Array of code/language name mappings
138 public static function languages($justEnabled = FALSE) {
140 static $enabled = NULL;
143 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
145 // check which ones are available; add them to $all if not there already
147 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
148 while ($filename = readdir($dir)) {
149 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
150 $codes[] = $filename;
151 if (!isset($all[$filename])) {
152 $all[$filename] = $filename;
159 // drop the unavailable languages (except en_US)
160 foreach (array_keys($all) as $code) {
161 if ($code == 'en_US') {
164 if (!in_array($code, $codes)) {
170 if ($enabled === NULL) {
171 $config = CRM_Core_Config
::singleton();
173 if (isset($config->languageLimit
) and $config->languageLimit
) {
174 foreach ($all as $code => $name) {
175 if (in_array($code, array_keys($config->languageLimit
))) {
176 $enabled[$code] = $name;
182 return $justEnabled ?
$enabled : $all;
186 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
194 public function strarg($str) {
197 for ($i = 1; $i < func_num_args(); $i++
) {
198 $arg = func_get_arg($i);
199 if (is_array($arg)) {
200 foreach ($arg as $aarg) {
201 $tr['%' . ++
$p] = $aarg;
205 $tr['%' . ++
$p] = $arg;
208 return strtr($str, $tr);
211 public static function getResourceDir() {
214 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
220 * Smarty block function, provides gettext support for smarty.
222 * The block content is the text that should be translated.
224 * Any parameter that is sent to the function will be represented as %n in the translation text,
225 * where n is 1 for the first parameter. The following parameters are reserved:
226 * - escape - sets escape mode:
227 * - 'html' for HTML escaping, this is the default.
228 * - 'js' for javascript escaping.
229 * - 'no'/'off'/0 - turns off escaping
230 * - plural - The plural version of the text (2nd parameter of ngettext())
231 * - count - The item count for plural mode (3rd parameter of ngettext())
232 * - context - gettext context of that string (for homonym handling)
234 * @param string $text
235 * the original string.
236 * @param array $params
237 * The params of the translation (if any).
238 * - domain: string|array a list of translation domains to search (in order)
242 * the translated string
244 public function crm_translate($text, $params = array()) {
245 if (isset($params['escape'])) {
246 $escape = $params['escape'];
247 unset($params['escape']);
250 // sometimes we need to {ts}-tag a string, but don’t want to
251 // translate it in the template (like civicrm_navigation.tpl),
252 // because we handle the translation in a different way (CRM-6998)
253 // in such cases we return early, only doing SQL/JS escaping
254 if (isset($params['skip']) and $params['skip']) {
255 if (isset($escape) and ($escape == 'sql')) {
256 $text = CRM_Core_DAO
::escapeString($text);
258 if (isset($escape) and ($escape == 'js')) {
259 $text = addcslashes($text, "'");
264 $plural = $count = NULL;
265 if (isset($params['plural'])) {
266 $plural = $params['plural'];
267 unset($params['plural']);
268 if (isset($params['count'])) {
269 $count = $params['count'];
273 if (isset($params['context'])) {
274 $context = $params['context'];
275 unset($params['context']);
281 if (isset($params['domain'])) {
282 $domain = $params['domain'];
283 unset($params['domain']);
289 $raw = !empty($params['raw']);
290 unset($params['raw']);
292 if (!empty($domain)) {
293 // It might be prettier to cast to an array, but this is high-traffic stuff.
294 if (is_array($domain)) {
295 foreach ($domain as $d) {
296 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
297 if ($candidate != $text) {
304 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
308 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
311 // replace the numbered %1, %2, etc. params if present
312 if (count($params) && !$raw) {
313 $text = $this->strarg($text, $params);
316 // escape SQL if we were asked for it
317 if (isset($escape) and ($escape == 'sql')) {
318 $text = CRM_Core_DAO
::escapeString($text);
321 // escape for JavaScript (if requested)
322 if (isset($escape) and ($escape == 'js')) {
323 $text = addcslashes($text, "'");
330 * Lookup the raw translation of a string (without any extra escaping or interpolation).
332 * @param string $text
333 * @param string|NULL $domain
334 * @param int|NULL $count
335 * @param string $plural
336 * @param string $context
340 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
341 // gettext domain for extensions
342 $domain_changed = FALSE;
343 if (!empty($domain) && $this->_phpgettext
) {
344 if ($this->setGettextDomain($domain)) {
345 $domain_changed = TRUE;
349 // do all wildcard translations first
351 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($this->locale
, Civi
::$statics[__CLASS__
])) {
352 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
353 Civi
::$statics[__CLASS__
][$this->locale
] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($this->locale
);
356 Civi
::$statics[__CLASS__
][$this->locale
] = array();
359 $stringTable = Civi
::$statics[__CLASS__
][$this->locale
];
362 if (isset($stringTable['enabled']['exactMatch'])) {
363 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
364 if ($search === $text) {
374 isset($stringTable['enabled']['wildcardMatch'])
376 $search = array_keys($stringTable['enabled']['wildcardMatch']);
377 $replace = array_values($stringTable['enabled']['wildcardMatch']);
378 $text = str_replace($search, $replace, $text);
381 // dont translate if we've done exactMatch already
383 // use plural if required parameters are set
384 if (isset($count) && isset($plural)) {
386 if ($this->_phpgettext
) {
387 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
390 // if the locale's not set, we do ngettext work by hand
391 // if $count == 1 then $text = $text, else $text = $plural
397 // expand %count in translated string to $count
398 $text = strtr($text, array('%count' => $count));
400 // if not plural, but the locale's set, translate
402 elseif ($this->_phpgettext
) {
404 $text = $this->_phpgettext
->pgettext($context, $text);
407 $text = $this->_phpgettext
->translate($text);
412 if ($domain_changed) {
413 $this->setGettextDomain('civicrm');
420 * Translate a string to the current locale.
422 * @param string $string
423 * this string should be translated.
426 * the translated string
428 public function translate($string) {
429 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
433 * Localize (destructively) array values.
435 * @param array $array
436 * the array for localization (in place).
437 * @param array $params
438 * an array of additional parameters.
440 public function localizeArray(
444 $tsLocale = CRM_Core_I18n
::getLocale();
446 if ($tsLocale == 'en_US') {
450 foreach ($array as & $value) {
452 $value = ts($value, $params);
458 * Localize (destructively) array elements with keys of 'title'.
460 * @param array $array
461 * the array for localization (in place).
463 public function localizeTitles(&$array) {
464 foreach ($array as $key => $value) {
465 if (is_array($value)) {
466 $this->localizeTitles($value);
467 $array[$key] = $value;
469 elseif ((string ) $key == 'title') {
470 $array[$key] = ts($value, array('context' => 'menu'));
476 * Binds a gettext domain, wrapper over bindtextdomain().
479 * Key of the extension (can be 'civicrm', or 'org.example.foo').
482 * True if the domain was changed for an extension.
484 public function setGettextDomain($key) {
485 /* No domain changes for en_US */
486 if (!$this->_phpgettext
) {
490 // It's only necessary to find/bind once
491 if (!isset($this->_extensioncache
[$key])) {
493 $mapper = CRM_Extension_System
::singleton()->getMapper();
494 $path = $mapper->keyToBasePath($key);
495 $info = $mapper->keyToInfo($key);
496 $domain = $info->file
;
498 if ($this->_nativegettext
) {
499 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
500 bind_textdomain_codeset($domain, 'UTF-8');
501 $this->_extensioncache
[$key] = $domain;
505 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
506 $streamer = new FileReader($mo_file);
507 $this->_extensioncache
[$key] = new gettext_reader($streamer);
510 catch (CRM_Extension_Exception
$e) {
511 // Intentionally not translating this string to avoid possible infinite loops
512 // Only developers should see this string, if they made a mistake in their ts() usage.
513 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
514 $this->_extensioncache
[$key] = FALSE;
518 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
519 if ($this->_nativegettext
) {
520 textdomain($this->_extensioncache
[$key]);
523 $this->_phpgettext
= $this->_extensioncache
[$key];
534 * Is the CiviCRM in multilingual mode.
537 * True if CiviCRM is in multilingual mode.
539 public static function isMultilingual() {
540 $domain = new CRM_Core_DAO_Domain();
542 return (bool) $domain->locales
;
546 * Is the language written "right-to-left"?
549 * Language (for example 'en_US', or 'fr_CA').
552 * True if it is an RTL language.
554 public static function isLanguageRTL($language) {
555 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
556 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
558 return (in_array($short, $rtl));
562 * Change the processing language without changing the current user language
565 * Language (for example 'en_US', or 'fr_CA').
566 * True if the domain was changed for an extension.
568 public function setLocale($language) {
570 $config = CRM_Core_Config
::singleton();
572 // Change the language of the CMS as well, for URLs.
573 CRM_Utils_System
::setUFLocale($language);
575 // change the gettext ressources
576 if ($this->_nativegettext
) {
577 $locale = $language . '.utf8';
578 putenv("LANG=$locale");
580 setlocale(LC_TIME
, $locale);
581 setlocale(LC_MESSAGES
, $locale);
582 setlocale(LC_CTYPE
, $locale);
584 bindtextdomain('civicrm', $config->gettextResourceDir
);
585 bind_textdomain_codeset('civicrm', 'UTF-8');
586 textdomain('civicrm');
588 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
589 $this->_extensioncache
['civicrm'] = 'civicrm';
593 require_once 'PHPgettext/streams.php';
594 require_once 'PHPgettext/gettext.php';
596 $mo_file = $config->gettextResourceDir
. $language . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
598 $streamer = new FileReader($mo_file);
599 $this->_phpgettext
= new gettext_reader($streamer);
600 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
606 $dbLocale = "_{$language}";
611 * Static instance provider - return the instance for the current locale.
613 * @return CRM_Core_I18n
615 public static function &singleton() {
616 static $singleton = array();
618 $tsLocale = CRM_Core_I18n
::getLocale();
619 if (!isset($singleton[$tsLocale])) {
620 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
623 return $singleton[$tsLocale];
627 * Set the LC_TIME locale if it's not set already (for a given language choice).
630 * the final LC_TIME that got set
632 public static function setLcTime() {
633 static $locales = array();
635 $tsLocale = CRM_Core_I18n
::getLocale();
636 if (!isset($locales[$tsLocale])) {
637 // with the config being set to pl_PL: try pl_PL.UTF-8,
638 // then pl_PL, if neither present fall back to C
639 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
642 return $locales[$tsLocale];
646 * Get the default language for contacts where no language is provided.
648 * Note that NULL is a valid option so be careful with checking for empty etc.
650 * NULL would mean 'we don't know & we don't want to hazard a guess'.
654 public static function getContactDefaultLanguage() {
655 $language = Civi
::settings()->get('contact_default_language');
656 if ($language == 'undefined') {
659 if (empty($language) ||
$language === '*default*') {
660 $language = civicrm_api3('setting', 'getvalue', array(
661 'name' => 'lcMessages',
662 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
665 elseif ($language == 'current_site_language') {
666 return CRM_Core_I18n
::getLocale();
673 * Get the current locale
677 public static function getLocale() {
685 * Short-named function for string translation, defined in global scope so it's available everywhere.
687 * @param string $text
688 * String string for translating.
689 * @param array $params
690 * Array an array of additional parameters.
693 * the translated string
695 function ts($text, $params = array()) {
696 static $config = NULL;
697 static $locale = NULL;
699 static $function = NULL;
706 $config = CRM_Core_Config
::singleton();
709 $tsLocale = CRM_Core_I18n
::getLocale();
710 if (!$i18n or $locale != $tsLocale) {
711 $i18n = CRM_Core_I18n
::singleton();
713 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
714 $function = $config->customTranslateFunction
;
719 return $function($text, $params);
722 return $i18n->crm_translate($text, $params);