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 * Set native locale for getText.
103 * @param string $locale
105 protected function setNativeGettextLocale($locale) {
108 putenv("LANG=$locale");
110 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
111 setlocale(LC_TIME
, $locale);
112 setlocale(LC_MESSAGES
, $locale);
113 setlocale(LC_CTYPE
, $locale);
115 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
116 bind_textdomain_codeset('civicrm', 'UTF-8');
117 textdomain('civicrm');
119 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
120 $this->_extensioncache
['civicrm'] = 'civicrm';
125 * Set getText locale.
127 * @param string $locale
129 protected function setPhpGettextLocale($locale) {
131 // we support both the old file hierarchy format and the new:
132 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
133 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
134 require_once 'PHPgettext/streams.php';
135 require_once 'PHPgettext/gettext.php';
137 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
139 if (!file_exists($mo_file)) {
140 // fallback to pre-4.5 mode
141 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'civicrm.mo';
144 $streamer = new FileReader($mo_file);
145 $this->_phpgettext
= new gettext_reader($streamer);
146 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
151 * Return languages available in this instance of CiviCRM.
153 * @param bool $justEnabled
154 * whether to return all languages or just the enabled ones.
157 * Array of code/language name mappings
159 public static function languages($justEnabled = FALSE) {
161 static $enabled = NULL;
164 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
166 // check which ones are available; add them to $all if not there already
168 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
169 while ($filename = readdir($dir)) {
170 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
171 $codes[] = $filename;
172 if (!isset($all[$filename])) {
173 $all[$filename] = $filename;
180 // drop the unavailable languages (except en_US)
181 foreach (array_keys($all) as $code) {
182 if ($code == 'en_US') {
185 if (!in_array($code, $codes)) {
191 if ($enabled === NULL) {
192 $config = CRM_Core_Config
::singleton();
194 if (isset($config->languageLimit
) and $config->languageLimit
) {
195 foreach ($all as $code => $name) {
196 if (in_array($code, array_keys($config->languageLimit
))) {
197 $enabled[$code] = $name;
203 return $justEnabled ?
$enabled : $all;
207 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
215 public function strarg($str) {
218 for ($i = 1; $i < func_num_args(); $i++
) {
219 $arg = func_get_arg($i);
220 if (is_array($arg)) {
221 foreach ($arg as $aarg) {
222 $tr['%' . ++
$p] = $aarg;
226 $tr['%' . ++
$p] = $arg;
229 return strtr($str, $tr);
233 * Get the directory for l10n resources.
237 public static function getResourceDir() {
240 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
246 * Smarty block function, provides gettext support for smarty.
248 * The block content is the text that should be translated.
250 * Any parameter that is sent to the function will be represented as %n in the translation text,
251 * where n is 1 for the first parameter. The following parameters are reserved:
252 * - escape - sets escape mode:
253 * - 'html' for HTML escaping, this is the default.
254 * - 'js' for javascript escaping.
255 * - 'no'/'off'/0 - turns off escaping
256 * - plural - The plural version of the text (2nd parameter of ngettext())
257 * - count - The item count for plural mode (3rd parameter of ngettext())
258 * - context - gettext context of that string (for homonym handling)
260 * @param string $text
261 * the original string.
262 * @param array $params
263 * The params of the translation (if any).
264 * - domain: string|array a list of translation domains to search (in order)
268 * the translated string
270 public function crm_translate($text, $params = array()) {
271 if (isset($params['escape'])) {
272 $escape = $params['escape'];
273 unset($params['escape']);
276 // sometimes we need to {ts}-tag a string, but don’t want to
277 // translate it in the template (like civicrm_navigation.tpl),
278 // because we handle the translation in a different way (CRM-6998)
279 // in such cases we return early, only doing SQL/JS escaping
280 if (isset($params['skip']) and $params['skip']) {
281 if (isset($escape) and ($escape == 'sql')) {
282 $text = CRM_Core_DAO
::escapeString($text);
284 if (isset($escape) and ($escape == 'js')) {
285 $text = addcslashes($text, "'");
290 $plural = $count = NULL;
291 if (isset($params['plural'])) {
292 $plural = $params['plural'];
293 unset($params['plural']);
294 if (isset($params['count'])) {
295 $count = $params['count'];
299 if (isset($params['context'])) {
300 $context = $params['context'];
301 unset($params['context']);
307 if (isset($params['domain'])) {
308 $domain = $params['domain'];
309 unset($params['domain']);
315 $raw = !empty($params['raw']);
316 unset($params['raw']);
318 if (!empty($domain)) {
319 // It might be prettier to cast to an array, but this is high-traffic stuff.
320 if (is_array($domain)) {
321 foreach ($domain as $d) {
322 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
323 if ($candidate != $text) {
330 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
334 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
337 // replace the numbered %1, %2, etc. params if present
338 if (count($params) && !$raw) {
339 $text = $this->strarg($text, $params);
342 // escape SQL if we were asked for it
343 if (isset($escape) and ($escape == 'sql')) {
344 $text = CRM_Core_DAO
::escapeString($text);
347 // escape for JavaScript (if requested)
348 if (isset($escape) and ($escape == 'js')) {
349 $text = addcslashes($text, "'");
356 * Lookup the raw translation of a string (without any extra escaping or interpolation).
358 * @param string $text
359 * @param string|NULL $domain
360 * @param int|NULL $count
361 * @param string $plural
362 * @param string $context
366 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
367 // gettext domain for extensions
368 $domain_changed = FALSE;
369 if (!empty($domain) && $this->_phpgettext
) {
370 if ($this->setGettextDomain($domain)) {
371 $domain_changed = TRUE;
375 // do all wildcard translations first
377 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
378 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
379 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
])) {
380 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
381 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
384 Civi
::$statics[__CLASS__
][$replacementsLocale] = array();
387 $stringTable = Civi
::$statics[__CLASS__
][$replacementsLocale];
390 if (isset($stringTable['enabled']['exactMatch'])) {
391 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
392 if ($search === $text) {
402 isset($stringTable['enabled']['wildcardMatch'])
404 $search = array_keys($stringTable['enabled']['wildcardMatch']);
405 $replace = array_values($stringTable['enabled']['wildcardMatch']);
406 $text = str_replace($search, $replace, $text);
409 // dont translate if we've done exactMatch already
411 // use plural if required parameters are set
412 if (isset($count) && isset($plural)) {
414 if ($this->_phpgettext
) {
415 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
418 // if the locale's not set, we do ngettext work by hand
419 // if $count == 1 then $text = $text, else $text = $plural
425 // expand %count in translated string to $count
426 $text = strtr($text, array('%count' => $count));
428 // if not plural, but the locale's set, translate
430 elseif ($this->_phpgettext
) {
432 $text = $this->_phpgettext
->pgettext($context, $text);
435 $text = $this->_phpgettext
->translate($text);
440 if ($domain_changed) {
441 $this->setGettextDomain('civicrm');
448 * Translate a string to the current locale.
450 * @param string $string
451 * this string should be translated.
454 * the translated string
456 public function translate($string) {
457 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
461 * Localize (destructively) array values.
463 * @param array $array
464 * the array for localization (in place).
465 * @param array $params
466 * an array of additional parameters.
468 public function localizeArray(
472 $tsLocale = CRM_Core_I18n
::getLocale();
474 if ($tsLocale == 'en_US') {
478 foreach ($array as & $value) {
480 $value = ts($value, $params);
486 * Localize (destructively) array elements with keys of 'title'.
488 * @param array $array
489 * the array for localization (in place).
491 public function localizeTitles(&$array) {
492 foreach ($array as $key => $value) {
493 if (is_array($value)) {
494 $this->localizeTitles($value);
495 $array[$key] = $value;
497 elseif ((string ) $key == 'title') {
498 $array[$key] = ts($value, array('context' => 'menu'));
504 * Binds a gettext domain, wrapper over bindtextdomain().
507 * Key of the extension (can be 'civicrm', or 'org.example.foo').
510 * True if the domain was changed for an extension.
512 public function setGettextDomain($key) {
513 /* No domain changes for en_US */
514 if (!$this->_phpgettext
) {
518 // It's only necessary to find/bind once
519 if (!isset($this->_extensioncache
[$key])) {
521 $mapper = CRM_Extension_System
::singleton()->getMapper();
522 $path = $mapper->keyToBasePath($key);
523 $info = $mapper->keyToInfo($key);
524 $domain = $info->file
;
526 if ($this->_nativegettext
) {
527 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
528 bind_textdomain_codeset($domain, 'UTF-8');
529 $this->_extensioncache
[$key] = $domain;
533 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
534 $streamer = new FileReader($mo_file);
535 $this->_extensioncache
[$key] = new gettext_reader($streamer);
538 catch (CRM_Extension_Exception
$e) {
539 // Intentionally not translating this string to avoid possible infinite loops
540 // Only developers should see this string, if they made a mistake in their ts() usage.
541 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
542 $this->_extensioncache
[$key] = FALSE;
546 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
547 if ($this->_nativegettext
) {
548 textdomain($this->_extensioncache
[$key]);
551 $this->_phpgettext
= $this->_extensioncache
[$key];
562 * Is the CiviCRM in multilingual mode.
565 * True if CiviCRM is in multilingual mode.
567 public static function isMultilingual() {
568 $domain = new CRM_Core_DAO_Domain();
570 return (bool) $domain->locales
;
574 * Is the language written "right-to-left"?
577 * Language (for example 'en_US', or 'fr_CA').
580 * True if it is an RTL language.
582 public static function isLanguageRTL($language) {
583 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
584 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
586 return (in_array($short, $rtl));
590 * Change the processing language without changing the current user language
593 * Locale (for example 'en_US', or 'fr_CA').
594 * True if the domain was changed for an extension.
596 public function setLocale($locale) {
598 // Change the language of the CMS as well, for URLs.
599 CRM_Utils_System
::setUFLocale($locale);
601 // change the gettext ressources
602 if ($this->_nativegettext
) {
603 $this->setNativeGettextLocale($locale);
607 $this->setPhpGettextLocale($locale);
612 $dbLocale = "_{$locale}";
617 * Static instance provider - return the instance for the current locale.
619 * @return CRM_Core_I18n
621 public static function &singleton() {
622 static $singleton = array();
624 $tsLocale = CRM_Core_I18n
::getLocale();
625 if (!isset($singleton[$tsLocale])) {
626 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
629 return $singleton[$tsLocale];
633 * Set the LC_TIME locale if it's not set already (for a given language choice).
636 * the final LC_TIME that got set
638 public static function setLcTime() {
639 static $locales = array();
641 $tsLocale = CRM_Core_I18n
::getLocale();
642 if (!isset($locales[$tsLocale])) {
643 // with the config being set to pl_PL: try pl_PL.UTF-8,
644 // then pl_PL, if neither present fall back to C
645 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
648 return $locales[$tsLocale];
652 * Get the default language for contacts where no language is provided.
654 * Note that NULL is a valid option so be careful with checking for empty etc.
656 * NULL would mean 'we don't know & we don't want to hazard a guess'.
660 public static function getContactDefaultLanguage() {
661 $language = Civi
::settings()->get('contact_default_language');
662 if ($language == 'undefined') {
665 if (empty($language) ||
$language === '*default*') {
666 $language = civicrm_api3('setting', 'getvalue', array(
667 'name' => 'lcMessages',
668 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
671 elseif ($language == 'current_site_language') {
672 return CRM_Core_I18n
::getLocale();
679 * Get the current locale
683 public static function getLocale() {
685 return $tsLocale ?
$tsLocale : 'en_US';
691 * Short-named function for string translation, defined in global scope so it's available everywhere.
693 * @param string $text
694 * String string for translating.
695 * @param array $params
696 * Array an array of additional parameters.
699 * the translated string
701 function ts($text, $params = array()) {
702 static $config = NULL;
703 static $locale = NULL;
705 static $function = NULL;
712 $config = CRM_Core_Config
::singleton();
715 $tsLocale = CRM_Core_I18n
::getLocale();
716 if (!$i18n or $locale != $tsLocale) {
717 $i18n = CRM_Core_I18n
::singleton();
719 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
720 $function = $config->customTranslateFunction
;
725 return $function($text, $params);
728 return $i18n->crm_translate($text, $params);