CRM-16355 - add the contact filter based on language and dynamic language change
[civicrm-core.git] / CRM / Core / I18n.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33 class CRM_Core_I18n {
34
35 /**
36 * Constants for communication preferences.
37 *
38 * @var int
39 */
40 const NONE = 'none', AUTO = 'auto';
41
42
43 /**
44 * A PHP-gettext instance for string translation;
45 * should stay null if the strings are not to be translated (en_US).
46 */
47 private $_phpgettext = NULL;
48
49 /**
50 * Whether we are using native gettext or not.
51 */
52 private $_nativegettext = FALSE;
53
54 /**
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.
58 */
59 private $_extensioncache = array();
60
61 /**
62 * @var string
63 */
64 private $locale;
65
66 /**
67 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
68 *
69 * @param string $locale
70 * the base of this certain object's existence.
71 *
72 * @return \CRM_Core_I18n
73 */
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
79
80 $this->_nativegettext = TRUE;
81
82 $locale .= '.utf8';
83 putenv("LANG=$locale");
84
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);
89
90 bindtextdomain('civicrm', CRM_Core_I18n::getResourceDir());
91 bind_textdomain_codeset('civicrm', 'UTF-8');
92 textdomain('civicrm');
93
94 $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
95 $this->_extensioncache['civicrm'] = 'civicrm';
96 return;
97 }
98
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';
105
106 $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
107
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';
111 }
112
113 $streamer = new FileReader($mo_file);
114 $this->_phpgettext = new gettext_reader($streamer);
115 $this->_extensioncache['civicrm'] = $this->_phpgettext;
116 }
117 }
118
119 /**
120 * Returns whether gettext is running natively or using PHP-Gettext.
121 *
122 * @return bool
123 * True if gettext is native
124 */
125 public function isNative() {
126 return $this->_nativegettext;
127 }
128
129 /**
130 * Return languages available in this instance of CiviCRM.
131 *
132 * @param bool $justEnabled
133 * whether to return all languages or just the enabled ones.
134 *
135 * @return array
136 * Array of code/language name mappings
137 */
138 public static function languages($justEnabled = FALSE) {
139 static $all = NULL;
140 static $enabled = NULL;
141
142 if (!$all) {
143 $all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
144
145 // check which ones are available; add them to $all if not there already
146 $codes = array();
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;
153 }
154 }
155 }
156 closedir($dir);
157 }
158
159 // drop the unavailable languages (except en_US)
160 foreach (array_keys($all) as $code) {
161 if ($code == 'en_US') {
162 continue;
163 }
164 if (!in_array($code, $codes)) {
165 unset($all[$code]);
166 }
167 }
168 }
169
170 if ($enabled === NULL) {
171 $config = CRM_Core_Config::singleton();
172 $enabled = array();
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;
177 }
178 }
179 }
180 }
181
182 return $justEnabled ? $enabled : $all;
183 }
184
185 /**
186 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
187 *
188 * @param string $str
189 * source string.
190 *
191 * @return string
192 * modified string
193 */
194 public function strarg($str) {
195 $tr = array();
196 $p = 0;
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;
202 }
203 }
204 else {
205 $tr['%' . ++$p] = $arg;
206 }
207 }
208 return strtr($str, $tr);
209 }
210
211 public static function getResourceDir() {
212 static $dir = NULL;
213 if ($dir === NULL) {
214 $dir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR;
215 }
216 return $dir;
217 }
218
219 /**
220 * Smarty block function, provides gettext support for smarty.
221 *
222 * The block content is the text that should be translated.
223 *
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)
233 *
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)
239 * - context: string
240 *
241 * @return string
242 * the translated string
243 */
244 public function crm_translate($text, $params = array()) {
245 if (isset($params['escape'])) {
246 $escape = $params['escape'];
247 unset($params['escape']);
248 }
249
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);
257 }
258 if (isset($escape) and ($escape == 'js')) {
259 $text = addcslashes($text, "'");
260 }
261 return $text;
262 }
263
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'];
270 }
271 }
272
273 if (isset($params['context'])) {
274 $context = $params['context'];
275 unset($params['context']);
276 }
277 else {
278 $context = NULL;
279 }
280
281 if (isset($params['domain'])) {
282 $domain = $params['domain'];
283 unset($params['domain']);
284 }
285 else {
286 $domain = NULL;
287 }
288
289 $raw = !empty($params['raw']);
290 unset($params['raw']);
291
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) {
298 $text = $candidate;
299 break;
300 }
301 }
302 }
303 else {
304 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
305 }
306 }
307 else {
308 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
309 }
310
311 // replace the numbered %1, %2, etc. params if present
312 if (count($params) && !$raw) {
313 $text = $this->strarg($text, $params);
314 }
315
316 // escape SQL if we were asked for it
317 if (isset($escape) and ($escape == 'sql')) {
318 $text = CRM_Core_DAO::escapeString($text);
319 }
320
321 // escape for JavaScript (if requested)
322 if (isset($escape) and ($escape == 'js')) {
323 $text = addcslashes($text, "'");
324 }
325
326 return $text;
327 }
328
329 /**
330 * Lookup the raw translation of a string (without any extra escaping or interpolation).
331 *
332 * @param string $text
333 * @param string|NULL $domain
334 * @param int|NULL $count
335 * @param string $plural
336 * @param string $context
337 *
338 * @return string
339 */
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;
346 }
347 }
348
349 // do all wildcard translations first
350 if (!isset(Civi::$statics[__CLASS__][$this->locale])) {
351 if (defined('CIVICRM_DSN') && !CRM_Core_Config::isUpgradeMode()) {
352 Civi::$statics[__CLASS__][$this->locale] = CRM_Core_BAO_WordReplacement::getLocaleCustomStrings($this->locale);
353 }
354 else {
355 Civi::$statics[__CLASS__][$this->locale] = array();
356 }
357 }
358 $stringTable = Civi::$statics[__CLASS__][$this->locale];
359
360 $exactMatch = FALSE;
361 if (isset($stringTable['enabled']['exactMatch'])) {
362 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
363 if ($search === $text) {
364 $exactMatch = TRUE;
365 $text = $replace;
366 break;
367 }
368 }
369 }
370
371 if (
372 !$exactMatch &&
373 isset($stringTable['enabled']['wildcardMatch'])
374 ) {
375 $search = array_keys($stringTable['enabled']['wildcardMatch']);
376 $replace = array_values($stringTable['enabled']['wildcardMatch']);
377 $text = str_replace($search, $replace, $text);
378 }
379
380 // dont translate if we've done exactMatch already
381 if (!$exactMatch) {
382 // use plural if required parameters are set
383 if (isset($count) && isset($plural)) {
384
385 if ($this->_phpgettext) {
386 $text = $this->_phpgettext->ngettext($text, $plural, $count);
387 }
388 else {
389 // if the locale's not set, we do ngettext work by hand
390 // if $count == 1 then $text = $text, else $text = $plural
391 if ($count != 1) {
392 $text = $plural;
393 }
394 }
395
396 // expand %count in translated string to $count
397 $text = strtr($text, array('%count' => $count));
398
399 // if not plural, but the locale's set, translate
400 }
401 elseif ($this->_phpgettext) {
402 if ($context) {
403 $text = $this->_phpgettext->pgettext($context, $text);
404 }
405 else {
406 $text = $this->_phpgettext->translate($text);
407 }
408 }
409 }
410
411 if ($domain_changed) {
412 $this->setGettextDomain('civicrm');
413 }
414
415 return $text;
416 }
417
418 /**
419 * Translate a string to the current locale.
420 *
421 * @param string $string
422 * this string should be translated.
423 *
424 * @return string
425 * the translated string
426 */
427 public function translate($string) {
428 return ($this->_phpgettext) ? $this->_phpgettext->translate($string) : $string;
429 }
430
431 /**
432 * Localize (destructively) array values.
433 *
434 * @param array $array
435 * the array for localization (in place).
436 * @param array $params
437 * an array of additional parameters.
438 */
439 public function localizeArray(
440 &$array,
441 $params = array()
442 ) {
443 global $tsLocale;
444
445 if ($tsLocale == 'en_US') {
446 return;
447 }
448
449 foreach ($array as & $value) {
450 if ($value) {
451 $value = ts($value, $params);
452 }
453 }
454 }
455
456 /**
457 * Localize (destructively) array elements with keys of 'title'.
458 *
459 * @param array $array
460 * the array for localization (in place).
461 */
462 public function localizeTitles(&$array) {
463 foreach ($array as $key => $value) {
464 if (is_array($value)) {
465 $this->localizeTitles($value);
466 $array[$key] = $value;
467 }
468 elseif ((string ) $key == 'title') {
469 $array[$key] = ts($value, array('context' => 'menu'));
470 }
471 }
472 }
473
474 /**
475 * Binds a gettext domain, wrapper over bindtextdomain().
476 *
477 * @param $key
478 * Key of the extension (can be 'civicrm', or 'org.example.foo').
479 *
480 * @return Bool
481 * True if the domain was changed for an extension.
482 */
483 public function setGettextDomain($key) {
484 /* No domain changes for en_US */
485 if (!$this->_phpgettext) {
486 return FALSE;
487 }
488
489 // It's only necessary to find/bind once
490 if (!isset($this->_extensioncache[$key])) {
491 try {
492 $mapper = CRM_Extension_System::singleton()->getMapper();
493 $path = $mapper->keyToBasePath($key);
494 $info = $mapper->keyToInfo($key);
495 $domain = $info->file;
496
497 if ($this->_nativegettext) {
498 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR . 'l10n');
499 bind_textdomain_codeset($domain, 'UTF-8');
500 $this->_extensioncache[$key] = $domain;
501 }
502 else {
503 // phpgettext
504 $mo_file = $path . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR . $this->locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $domain . '.mo';
505 $streamer = new FileReader($mo_file);
506 $this->_extensioncache[$key] = new gettext_reader($streamer);
507 }
508 }
509 catch (CRM_Extension_Exception $e) {
510 // Intentionally not translating this string to avoid possible infinite loops
511 // Only developers should see this string, if they made a mistake in their ts() usage.
512 CRM_Core_Session::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
513 $this->_extensioncache[$key] = FALSE;
514 }
515 }
516
517 if (isset($this->_extensioncache[$key]) && $this->_extensioncache[$key]) {
518 if ($this->_nativegettext) {
519 textdomain($this->_extensioncache[$key]);
520 }
521 else {
522 $this->_phpgettext = $this->_extensioncache[$key];
523 }
524
525 return TRUE;
526 }
527
528 return FALSE;
529 }
530
531
532 /**
533 * Is the CiviCRM in multilingual mode.
534 *
535 * @return Bool
536 * True if CiviCRM is in multilingual mode.
537 */
538 public static function isMultilingual() {
539 $domain = new CRM_Core_DAO_Domain();
540 $domain->find(TRUE);
541 return (bool) $domain->locales;
542 }
543
544 /**
545 * Get the enabled locales list
546 *
547 * @return array
548 */
549 public static function getLocales() {
550 $domain = new CRM_Core_DAO_Domain();
551 $domain->find(TRUE);
552 return $domain->locales;
553 }
554
555 /**
556 * Change the processing language without changing the current user language
557 *
558 * @param $language
559 * Language (for example 'en_US', or 'fr_CA').
560 * True if the domain was changed for an extension.
561 */
562 public function setLanguage($language) {
563
564
565 $config = CRM_Core_Config::singleton();
566 if ($this->_nativegettext) {
567 $locale = $language . '.utf8';
568 putenv("LANG=$locale");
569
570 setlocale(LC_TIME, $locale);
571 setlocale(LC_MESSAGES, $locale);
572 setlocale(LC_CTYPE, $locale);
573
574 bindtextdomain('civicrm', $config->gettextResourceDir);
575 bind_textdomain_codeset('civicrm', 'UTF-8');
576 textdomain('civicrm');
577
578 $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
579 $this->_extensioncache['civicrm'] = 'civicrm';
580 }
581 else {
582 // phpgettext
583 require_once 'PHPgettext/streams.php';
584 require_once 'PHPgettext/gettext.php';
585
586 $mo_file = $config->gettextResourceDir . $language . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
587
588 $streamer = new FileReader($mo_file);
589 $this->_phpgettext = new gettext_reader($streamer);
590 $this->_extensioncache['civicrm'] = $this->_phpgettext;
591
592 }
593
594 // for sql queries
595 global $dbLocale;
596 $dbLocale = "_{$language}";
597
598 }
599
600 /**
601 * Static instance provider - return the instance for the current locale.
602 *
603 * @return CRM_Core_I18n
604 */
605 public static function &singleton() {
606 static $singleton = array();
607
608 global $tsLocale;
609 if (!isset($singleton[$tsLocale])) {
610 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
611 }
612
613 return $singleton[$tsLocale];
614 }
615
616 /**
617 * Set the LC_TIME locale if it's not set already (for a given language choice).
618 *
619 * @return string
620 * the final LC_TIME that got set
621 */
622 public static function setLcTime() {
623 static $locales = array();
624
625 global $tsLocale;
626 if (!isset($locales[$tsLocale])) {
627 // with the config being set to pl_PL: try pl_PL.UTF-8,
628 // then pl_PL, if neither present fall back to C
629 $locales[$tsLocale] = setlocale(LC_TIME, $tsLocale . '.UTF-8', $tsLocale, 'C');
630 }
631
632 return $locales[$tsLocale];
633 }
634
635 /**
636 * Get the default language for contacts where no language is provided.
637 *
638 * Note that NULL is a valid option so be careful with checking for empty etc.
639 *
640 * NULL would mean 'we don't know & we don't want to hazard a guess'.
641 *
642 * @return string
643 */
644 public static function getContactDefaultLanguage() {
645 $language = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME, 'contact_default_language');
646 if ($language == 'undefined') {
647 return NULL;
648 }
649 if (empty($language) || $language === '*default*') {
650 $language = civicrm_api3('setting', 'getvalue', array(
651 'name' => 'lcMessages',
652 'group' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
653 ));
654 }
655 elseif ($language == 'current_site_language') {
656 global $tsLocale;
657 return $tsLocale;
658 }
659
660 return $language;
661 }
662
663 }
664
665 /**
666 * Short-named function for string translation, defined in global scope so it's available everywhere.
667 *
668 * @param string $text
669 * String string for translating.
670 * @param array $params
671 * Array an array of additional parameters.
672 *
673 * @return string
674 * the translated string
675 */
676 function ts($text, $params = array()) {
677 static $config = NULL;
678 static $locale = NULL;
679 static $i18n = NULL;
680 static $function = NULL;
681
682 if ($text == '') {
683 return '';
684 }
685
686 if (!$config) {
687 $config = CRM_Core_Config::singleton();
688 }
689
690 global $tsLocale;
691 if (!$i18n or $locale != $tsLocale) {
692 $i18n = CRM_Core_I18n::singleton();
693 $locale = $tsLocale;
694 if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
695 $function = $config->customTranslateFunction;
696 }
697 }
698
699 if ($function) {
700 return $function($text, $params);
701 }
702 else {
703 return $i18n->crm_translate($text, $params);
704 }
705 }