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');
169 CRM_Core_OptionValue
::getValues(array('name' => 'languages'), $rows);
170 foreach ($rows as $id => $row) {
171 $labels[$row['name']] = $row['label'];
174 // check which ones are available; add them to $all if not there already
176 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
177 while ($filename = readdir($dir)) {
178 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
179 $codes[] = $filename;
180 if (!isset($all[$filename])) {
181 $all[$filename] = $labels[$filename];
188 // drop the unavailable languages (except en_US)
189 foreach (array_keys($all) as $code) {
190 if ($code == 'en_US') {
193 if (!in_array($code, $codes)) {
201 if ($enabled === NULL) {
202 $config = CRM_Core_Config
::singleton();
204 if (isset($config->languageLimit
) and $config->languageLimit
) {
205 foreach ($all as $code => $name) {
206 if (in_array($code, array_keys($config->languageLimit
))) {
207 $enabled[$code] = $name;
213 return $justEnabled ?
$enabled : $all;
217 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
225 public function strarg($str) {
228 for ($i = 1; $i < func_num_args(); $i++
) {
229 $arg = func_get_arg($i);
230 if (is_array($arg)) {
231 foreach ($arg as $aarg) {
232 $tr['%' . ++
$p] = $aarg;
236 $tr['%' . ++
$p] = $arg;
239 return strtr($str, $tr);
243 * Get the directory for l10n resources.
247 public static function getResourceDir() {
250 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
256 * Smarty block function, provides gettext support for smarty.
258 * The block content is the text that should be translated.
260 * Any parameter that is sent to the function will be represented as %n in the translation text,
261 * where n is 1 for the first parameter. The following parameters are reserved:
262 * - escape - sets escape mode:
263 * - 'html' for HTML escaping, this is the default.
264 * - 'js' for javascript escaping.
265 * - 'no'/'off'/0 - turns off escaping
266 * - plural - The plural version of the text (2nd parameter of ngettext())
267 * - count - The item count for plural mode (3rd parameter of ngettext())
268 * - context - gettext context of that string (for homonym handling)
270 * @param string $text
271 * the original string.
272 * @param array $params
273 * The params of the translation (if any).
274 * - domain: string|array a list of translation domains to search (in order)
278 * the translated string
280 public function crm_translate($text, $params = array()) {
281 if (isset($params['escape'])) {
282 $escape = $params['escape'];
283 unset($params['escape']);
286 // sometimes we need to {ts}-tag a string, but don’t want to
287 // translate it in the template (like civicrm_navigation.tpl),
288 // because we handle the translation in a different way (CRM-6998)
289 // in such cases we return early, only doing SQL/JS escaping
290 if (isset($params['skip']) and $params['skip']) {
291 if (isset($escape) and ($escape == 'sql')) {
292 $text = CRM_Core_DAO
::escapeString($text);
294 if (isset($escape) and ($escape == 'js')) {
295 $text = addcslashes($text, "'");
300 $plural = $count = NULL;
301 if (isset($params['plural'])) {
302 $plural = $params['plural'];
303 unset($params['plural']);
304 if (isset($params['count'])) {
305 $count = $params['count'];
309 if (isset($params['context'])) {
310 $context = $params['context'];
311 unset($params['context']);
317 if (isset($params['domain'])) {
318 $domain = $params['domain'];
319 unset($params['domain']);
325 $raw = !empty($params['raw']);
326 unset($params['raw']);
328 if (!empty($domain)) {
329 // It might be prettier to cast to an array, but this is high-traffic stuff.
330 if (is_array($domain)) {
331 foreach ($domain as $d) {
332 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
333 if ($candidate != $text) {
340 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
344 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
347 // replace the numbered %1, %2, etc. params if present
348 if (count($params) && !$raw) {
349 $text = $this->strarg($text, $params);
352 // escape SQL if we were asked for it
353 if (isset($escape) and ($escape == 'sql')) {
354 $text = CRM_Core_DAO
::escapeString($text);
357 // escape for JavaScript (if requested)
358 if (isset($escape) and ($escape == 'js')) {
359 $text = addcslashes($text, "'");
366 * Lookup the raw translation of a string (without any extra escaping or interpolation).
368 * @param string $text
369 * @param string|NULL $domain
370 * @param int|NULL $count
371 * @param string $plural
372 * @param string $context
376 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
377 // gettext domain for extensions
378 $domain_changed = FALSE;
379 if (!empty($domain) && $this->_phpgettext
) {
380 if ($this->setGettextDomain($domain)) {
381 $domain_changed = TRUE;
385 // do all wildcard translations first
387 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
388 $replacementsLocale = $this->locale ?
$this->locale
: 'en_US';
389 if (!isset(Civi
::$statics[__CLASS__
]) ||
!array_key_exists($replacementsLocale, Civi
::$statics[__CLASS__
])) {
390 if (defined('CIVICRM_DSN') && !CRM_Core_Config
::isUpgradeMode()) {
391 Civi
::$statics[__CLASS__
][$replacementsLocale] = CRM_Core_BAO_WordReplacement
::getLocaleCustomStrings($replacementsLocale);
394 Civi
::$statics[__CLASS__
][$replacementsLocale] = array();
397 $stringTable = Civi
::$statics[__CLASS__
][$replacementsLocale];
400 if (isset($stringTable['enabled']['exactMatch'])) {
401 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
402 if ($search === $text) {
412 isset($stringTable['enabled']['wildcardMatch'])
414 $search = array_keys($stringTable['enabled']['wildcardMatch']);
415 $replace = array_values($stringTable['enabled']['wildcardMatch']);
416 $text = str_replace($search, $replace, $text);
419 // dont translate if we've done exactMatch already
421 // use plural if required parameters are set
422 if (isset($count) && isset($plural)) {
424 if ($this->_phpgettext
) {
425 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
428 // if the locale's not set, we do ngettext work by hand
429 // if $count == 1 then $text = $text, else $text = $plural
435 // expand %count in translated string to $count
436 $text = strtr($text, array('%count' => $count));
438 // if not plural, but the locale's set, translate
440 elseif ($this->_phpgettext
) {
442 $text = $this->_phpgettext
->pgettext($context, $text);
445 $text = $this->_phpgettext
->translate($text);
450 if ($domain_changed) {
451 $this->setGettextDomain('civicrm');
458 * Translate a string to the current locale.
460 * @param string $string
461 * this string should be translated.
464 * the translated string
466 public function translate($string) {
467 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
471 * Localize (destructively) array values.
473 * @param array $array
474 * the array for localization (in place).
475 * @param array $params
476 * an array of additional parameters.
478 public function localizeArray(
482 $tsLocale = CRM_Core_I18n
::getLocale();
484 if ($tsLocale == 'en_US') {
488 foreach ($array as & $value) {
490 $value = ts($value, $params);
496 * Localize (destructively) array elements with keys of 'title'.
498 * @param array $array
499 * the array for localization (in place).
501 public function localizeTitles(&$array) {
502 foreach ($array as $key => $value) {
503 if (is_array($value)) {
504 $this->localizeTitles($value);
505 $array[$key] = $value;
507 elseif ((string ) $key == 'title') {
508 $array[$key] = ts($value, array('context' => 'menu'));
514 * Binds a gettext domain, wrapper over bindtextdomain().
517 * Key of the extension (can be 'civicrm', or 'org.example.foo').
520 * True if the domain was changed for an extension.
522 public function setGettextDomain($key) {
523 /* No domain changes for en_US */
524 if (!$this->_phpgettext
) {
528 // It's only necessary to find/bind once
529 if (!isset($this->_extensioncache
[$key])) {
531 $mapper = CRM_Extension_System
::singleton()->getMapper();
532 $path = $mapper->keyToBasePath($key);
533 $info = $mapper->keyToInfo($key);
534 $domain = $info->file
;
536 if ($this->_nativegettext
) {
537 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
538 bind_textdomain_codeset($domain, 'UTF-8');
539 $this->_extensioncache
[$key] = $domain;
543 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $this->locale
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
544 $streamer = new FileReader($mo_file);
545 $this->_extensioncache
[$key] = new gettext_reader($streamer);
548 catch (CRM_Extension_Exception
$e) {
549 // Intentionally not translating this string to avoid possible infinite loops
550 // Only developers should see this string, if they made a mistake in their ts() usage.
551 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
552 $this->_extensioncache
[$key] = FALSE;
556 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
557 if ($this->_nativegettext
) {
558 textdomain($this->_extensioncache
[$key]);
561 $this->_phpgettext
= $this->_extensioncache
[$key];
572 * Is the CiviCRM in multilingual mode.
575 * True if CiviCRM is in multilingual mode.
577 public static function isMultilingual() {
578 $domain = new CRM_Core_DAO_Domain();
580 return (bool) $domain->locales
;
584 * Is the language written "right-to-left"?
587 * Language (for example 'en_US', or 'fr_CA').
590 * True if it is an RTL language.
592 public static function isLanguageRTL($language) {
593 $rtl = CRM_Core_I18n_PseudoConstant
::getRTLlanguages();
594 $short = CRM_Core_I18n_PseudoConstant
::shortForLong($language);
596 return (in_array($short, $rtl));
600 * Change the processing language without changing the current user language
603 * Locale (for example 'en_US', or 'fr_CA').
604 * True if the domain was changed for an extension.
606 public function setLocale($locale) {
608 // Change the language of the CMS as well, for URLs.
609 CRM_Utils_System
::setUFLocale($locale);
611 // change the gettext ressources
612 if ($this->_nativegettext
) {
613 $this->setNativeGettextLocale($locale);
617 $this->setPhpGettextLocale($locale);
622 $dbLocale = "_{$locale}";
627 * Static instance provider - return the instance for the current locale.
629 * @return CRM_Core_I18n
631 public static function &singleton() {
632 static $singleton = array();
634 $tsLocale = CRM_Core_I18n
::getLocale();
635 if (!isset($singleton[$tsLocale])) {
636 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
639 return $singleton[$tsLocale];
643 * Set the LC_TIME locale if it's not set already (for a given language choice).
646 * the final LC_TIME that got set
648 public static function setLcTime() {
649 static $locales = array();
651 $tsLocale = CRM_Core_I18n
::getLocale();
652 if (!isset($locales[$tsLocale])) {
653 // with the config being set to pl_PL: try pl_PL.UTF-8,
654 // then pl_PL, if neither present fall back to C
655 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
658 return $locales[$tsLocale];
662 * Get the default language for contacts where no language is provided.
664 * Note that NULL is a valid option so be careful with checking for empty etc.
666 * NULL would mean 'we don't know & we don't want to hazard a guess'.
670 public static function getContactDefaultLanguage() {
671 $language = Civi
::settings()->get('contact_default_language');
672 if ($language == 'undefined') {
675 if (empty($language) ||
$language === '*default*') {
676 $language = civicrm_api3('setting', 'getvalue', array(
677 'name' => 'lcMessages',
678 'group' => CRM_Core_BAO_Setting
::LOCALIZATION_PREFERENCES_NAME
,
681 elseif ($language == 'current_site_language') {
682 return CRM_Core_I18n
::getLocale();
689 * Get the current locale
693 public static function getLocale() {
695 return $tsLocale ?
$tsLocale : 'en_US';
701 * Short-named function for string translation, defined in global scope so it's available everywhere.
703 * @param string $text
704 * String string for translating.
705 * @param array $params
706 * Array an array of additional parameters.
709 * the translated string
711 function ts($text, $params = array()) {
712 static $config = NULL;
713 static $locale = NULL;
715 static $function = NULL;
722 $config = CRM_Core_Config
::singleton();
725 $tsLocale = CRM_Core_I18n
::getLocale();
726 if (!$i18n or $locale != $tsLocale) {
727 $i18n = CRM_Core_I18n
::singleton();
729 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
730 $function = $config->customTranslateFunction
;
735 return $function($text, $params);
738 return $i18n->crm_translate($text, $params);