3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
38 * A PHP-gettext instance for string translation;
39 * should stay null if the strings are not to be translated (en_US).
41 private $_phpgettext = NULL;
44 * Whether we are using native gettext or not.
46 private $_nativegettext = FALSE;
49 * Gettext cache for extension domains/streamers, depending on if native or phpgettext.
50 * - native gettext: we cache the value for textdomain()
51 * - phpgettext: we cache the file streamer.
53 private $_extensioncache = array();
56 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
58 * @param string $locale
59 * the base of this certain object's existence.
61 * @return \CRM_Core_I18n
63 public function __construct($locale) {
64 if ($locale != '' and $locale != 'en_US') {
65 $config = CRM_Core_Config
::singleton();
67 if (defined('CIVICRM_GETTEXT_NATIVE') && CIVICRM_GETTEXT_NATIVE
&& function_exists('gettext')) {
68 // Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
70 $this->_nativegettext
= TRUE;
73 putenv("LANG=$locale");
75 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
76 setlocale(LC_TIME
, $locale);
77 setlocale(LC_MESSAGES
, $locale);
78 setlocale(LC_CTYPE
, $locale);
80 bindtextdomain('civicrm', CRM_Core_I18n
::getResourceDir());
81 bind_textdomain_codeset('civicrm', 'UTF-8');
82 textdomain('civicrm');
84 $this->_phpgettext
= new CRM_Core_I18n_NativeGettext();
85 $this->_extensioncache
['civicrm'] = 'civicrm';
89 // Otherwise, use PHP-gettext
90 // we support both the old file hierarchy format and the new:
91 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
92 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
93 require_once 'PHPgettext/streams.php';
94 require_once 'PHPgettext/gettext.php';
96 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. 'civicrm.mo';
98 if (!file_exists($mo_file)) {
99 // fallback to pre-4.5 mode
100 $mo_file = CRM_Core_I18n
::getResourceDir() . $locale . DIRECTORY_SEPARATOR
. 'civicrm.mo';
103 $streamer = new FileReader($mo_file);
104 $this->_phpgettext
= new gettext_reader($streamer);
105 $this->_extensioncache
['civicrm'] = $this->_phpgettext
;
110 * Returns whether gettext is running natively or using PHP-Gettext.
113 * True if gettext is native
115 public function isNative() {
116 return $this->_nativegettext
;
120 * Return languages available in this instance of CiviCRM.
122 * @param bool $justEnabled
123 * whether to return all languages or just the enabled ones.
126 * Array of code/language name mappings
128 public static function languages($justEnabled = FALSE) {
130 static $enabled = NULL;
133 $all = CRM_Contact_BAO_Contact
::buildOptions('preferred_language');
135 // check which ones are available; add them to $all if not there already
136 $config = CRM_Core_Config
::singleton();
138 if (is_dir(CRM_Core_I18n
::getResourceDir()) && $dir = opendir(CRM_Core_I18n
::getResourceDir())) {
139 while ($filename = readdir($dir)) {
140 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
141 $codes[] = $filename;
142 if (!isset($all[$filename])) {
143 $all[$filename] = $filename;
150 // drop the unavailable languages (except en_US)
151 foreach (array_keys($all) as $code) {
152 if ($code == 'en_US') {
155 if (!in_array($code, $codes)) {
161 if ($enabled === NULL) {
162 $config = CRM_Core_Config
::singleton();
164 if (isset($config->languageLimit
) and $config->languageLimit
) {
165 foreach ($all as $code => $name) {
166 if (in_array($code, array_keys($config->languageLimit
))) {
167 $enabled[$code] = $name;
173 return $justEnabled ?
$enabled : $all;
177 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
185 public function strarg($str) {
188 for ($i = 1; $i < func_num_args(); $i++
) {
189 $arg = func_get_arg($i);
190 if (is_array($arg)) {
191 foreach ($arg as $aarg) {
192 $tr['%' . ++
$p] = $aarg;
196 $tr['%' . ++
$p] = $arg;
199 return strtr($str, $tr);
202 public static function getResourceDir() {
205 $dir = dirname(dirname(__DIR__
)) . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
;
211 * Smarty block function, provides gettext support for smarty.
213 * The block content is the text that should be translated.
215 * Any parameter that is sent to the function will be represented as %n in the translation text,
216 * where n is 1 for the first parameter. The following parameters are reserved:
217 * - escape - sets escape mode:
218 * - 'html' for HTML escaping, this is the default.
219 * - 'js' for javascript escaping.
220 * - 'no'/'off'/0 - turns off escaping
221 * - plural - The plural version of the text (2nd parameter of ngettext())
222 * - count - The item count for plural mode (3rd parameter of ngettext())
223 * - context - gettext context of that string (for homonym handling)
225 * @param string $text
226 * the original string.
227 * @param array $params
228 * The params of the translation (if any).
229 * - domain: string|array a list of translation domains to search (in order)
232 * the translated string
234 public function crm_translate($text, $params = array()) {
235 if (isset($params['escape'])) {
236 $escape = $params['escape'];
237 unset($params['escape']);
240 // sometimes we need to {ts}-tag a string, but don’t want to
241 // translate it in the template (like civicrm_navigation.tpl),
242 // because we handle the translation in a different way (CRM-6998)
243 // in such cases we return early, only doing SQL/JS escaping
244 if (isset($params['skip']) and $params['skip']) {
245 if (isset($escape) and ($escape == 'sql')) {
246 $text = CRM_Core_DAO
::escapeString($text);
248 if (isset($escape) and ($escape == 'js')) {
249 $text = addcslashes($text, "'");
254 $plural = $count = NULL;
255 if (isset($params['plural'])) {
256 $plural = $params['plural'];
257 unset($params['plural']);
258 if (isset($params['count'])) {
259 $count = $params['count'];
263 if (isset($params['context'])) {
264 $context = $params['context'];
265 unset($params['context']);
271 if (isset($params['domain'])) {
272 $domain = $params['domain'];
273 unset($params['domain']);
279 $raw = !empty($params['raw']);
280 unset($params['raw']);
282 if (!empty($domain)) {
283 // It might be prettier to cast to an array, but this is high-traffic stuff.
284 if (is_array($domain)) {
285 foreach ($domain as $d) {
286 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
287 if ($candidate != $text) {
294 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
298 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
301 // replace the numbered %1, %2, etc. params if present
302 if (count($params) && !$raw) {
303 $text = $this->strarg($text, $params);
306 // escape SQL if we were asked for it
307 if (isset($escape) and ($escape == 'sql')) {
308 $text = CRM_Core_DAO
::escapeString($text);
311 // escape for JavaScript (if requested)
312 if (isset($escape) and ($escape == 'js')) {
313 $text = addcslashes($text, "'");
320 * Lookup the raw translation of a string (without any extra escaping or interpolation).
322 * @param string $text
323 * @param string|NULL $domain
324 * @param int|NULL $count
325 * @param string $plural
326 * @param string $context
327 * @return mixed|string|translated
329 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
330 // gettext domain for extensions
331 $domain_changed = FALSE;
332 if (!empty($domain) && $this->_phpgettext
) {
333 if ($this->setGettextDomain($domain)) {
334 $domain_changed = TRUE;
338 // do all wildcard translations first
339 $config = CRM_Core_Config
::singleton();
340 $stringTable = CRM_Utils_Array
::value(
342 $config->localeCustomStrings
346 if (isset($stringTable['enabled']['exactMatch'])) {
347 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
348 if ($search === $text) {
358 isset($stringTable['enabled']['wildcardMatch'])
360 $search = array_keys($stringTable['enabled']['wildcardMatch']);
361 $replace = array_values($stringTable['enabled']['wildcardMatch']);
362 $text = str_replace($search, $replace, $text);
365 // dont translate if we've done exactMatch already
367 // use plural if required parameters are set
368 if (isset($count) && isset($plural)) {
370 if ($this->_phpgettext
) {
371 $text = $this->_phpgettext
->ngettext($text, $plural, $count);
374 // if the locale's not set, we do ngettext work by hand
375 // if $count == 1 then $text = $text, else $text = $plural
381 // expand %count in translated string to $count
382 $text = strtr($text, array('%count' => $count));
384 // if not plural, but the locale's set, translate
386 elseif ($this->_phpgettext
) {
388 $text = $this->_phpgettext
->pgettext($context, $text);
391 $text = $this->_phpgettext
->translate($text);
396 if ($domain_changed) {
397 $this->setGettextDomain('civicrm');
404 * Translate a string to the current locale.
406 * @param string $string
407 * this string should be translated.
410 * the translated string
412 public function translate($string) {
413 return ($this->_phpgettext
) ?
$this->_phpgettext
->translate($string) : $string;
417 * Localize (destructively) array values.
419 * @param array $array
420 * the array for localization (in place).
421 * @param array $params
422 * an array of additional parameters.
426 public function localizeArray(
432 if ($tsLocale == 'en_US') {
436 foreach ($array as & $value) {
438 $value = ts($value, $params);
444 * Localize (destructively) array elements with keys of 'title'.
446 * @param array $array
447 * the array for localization (in place).
451 public function localizeTitles(&$array) {
452 foreach ($array as $key => $value) {
453 if (is_array($value)) {
454 $this->localizeTitles($value);
455 $array[$key] = $value;
457 elseif ((string ) $key == 'title') {
458 $array[$key] = ts($value, array('context' => 'menu'));
464 * Binds a gettext domain, wrapper over bindtextdomain().
467 * Key of the extension (can be 'civicrm', or 'org.example.foo').
470 * True if the domain was changed for an extension.
472 public function setGettextDomain($key) {
473 /* No domain changes for en_US */
474 if (!$this->_phpgettext
) {
478 // It's only necessary to find/bind once
479 if (!isset($this->_extensioncache
[$key])) {
480 $config = CRM_Core_Config
::singleton();
483 $mapper = CRM_Extension_System
::singleton()->getMapper();
484 $path = $mapper->keyToBasePath($key);
485 $info = $mapper->keyToInfo($key);
486 $domain = $info->file
;
488 if ($this->_nativegettext
) {
489 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR
. 'l10n');
490 bind_textdomain_codeset($domain, 'UTF-8');
491 $this->_extensioncache
[$key] = $domain;
495 $mo_file = $path . DIRECTORY_SEPARATOR
. 'l10n' . DIRECTORY_SEPARATOR
. $config->lcMessages
. DIRECTORY_SEPARATOR
. 'LC_MESSAGES' . DIRECTORY_SEPARATOR
. $domain . '.mo';
496 $streamer = new FileReader($mo_file);
497 $this->_extensioncache
[$key] = new gettext_reader($streamer);
500 catch (CRM_Extension_Exception
$e) {
501 // Intentionally not translating this string to avoid possible infinite loops
502 // Only developers should see this string, if they made a mistake in their ts() usage.
503 CRM_Core_Session
::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
504 $this->_extensioncache
[$key] = FALSE;
508 if (isset($this->_extensioncache
[$key]) && $this->_extensioncache
[$key]) {
509 if ($this->_nativegettext
) {
510 textdomain($this->_extensioncache
[$key]);
513 $this->_phpgettext
= $this->_extensioncache
[$key];
523 * Static instance provider - return the instance for the current locale.
525 * @return CRM_Core_I18n
527 public static function &singleton() {
528 static $singleton = array();
531 if (!isset($singleton[$tsLocale])) {
532 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
535 return $singleton[$tsLocale];
539 * Set the LC_TIME locale if it's not set already (for a given language choice).
542 * the final LC_TIME that got set
544 public static function setLcTime() {
545 static $locales = array();
548 if (!isset($locales[$tsLocale])) {
549 // with the config being set to pl_PL: try pl_PL.UTF-8,
550 // then pl_PL, if neither present fall back to C
551 $locales[$tsLocale] = setlocale(LC_TIME
, $tsLocale . '.UTF-8', $tsLocale, 'C');
554 return $locales[$tsLocale];
560 * Short-named function for string translation, defined in global scope so it's available everywhere.
563 * String string for translating.
564 * @param array $params
565 * Array an array of additional parameters.
568 * the translated string
570 function ts($text, $params = array()) {
571 static $config = NULL;
572 static $locale = NULL;
574 static $function = NULL;
581 $config = CRM_Core_Config
::singleton();
585 if (!$i18n or $locale != $tsLocale) {
586 $i18n = CRM_Core_I18n
::singleton();
588 if (isset($config->customTranslateFunction
) and function_exists($config->customTranslateFunction
)) {
589 $function = $config->customTranslateFunction
;
594 return $function($text, $params);
597 return $i18n->crm_translate($text, $params);