Merge pull request #8694 from eileenmcnaughton/unhurt-my-server
[civicrm-core.git] / CRM / Core / I18n.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 $this->setNativeGettextLocale($locale);
82 return;
83 }
84
85 // Otherwise, use PHP-gettext
86 $this->setPhpGettextLocale($locale);
87 }
88 }
89
90 /**
91 * Returns whether gettext is running natively or using PHP-Gettext.
92 *
93 * @return bool
94 * True if gettext is native
95 */
96 public function isNative() {
97 return $this->_nativegettext;
98 }
99
100
101 protected function setNativeGettextLocale($locale) {
102
103 $locale .= '.utf8';
104 putenv("LANG=$locale");
105
106 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
107 setlocale(LC_TIME, $locale);
108 setlocale(LC_MESSAGES, $locale);
109 setlocale(LC_CTYPE, $locale);
110
111 bindtextdomain('civicrm', CRM_Core_I18n::getResourceDir());
112 bind_textdomain_codeset('civicrm', 'UTF-8');
113 textdomain('civicrm');
114
115 $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
116 $this->_extensioncache['civicrm'] = 'civicrm';
117
118 }
119
120 protected function setPhpGettextLocale($locale) {
121
122 // we support both the old file hierarchy format and the new:
123 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
124 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
125 require_once 'PHPgettext/streams.php';
126 require_once 'PHPgettext/gettext.php';
127
128 $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
129
130 if (!file_exists($mo_file)) {
131 // fallback to pre-4.5 mode
132 $mo_file = CRM_Core_I18n::getResourceDir() . $locale . DIRECTORY_SEPARATOR . 'civicrm.mo';
133 }
134
135 $streamer = new FileReader($mo_file);
136 $this->_phpgettext = new gettext_reader($streamer);
137 $this->_extensioncache['civicrm'] = $this->_phpgettext;
138
139 }
140
141
142 /**
143 * Return languages available in this instance of CiviCRM.
144 *
145 * @param bool $justEnabled
146 * whether to return all languages or just the enabled ones.
147 *
148 * @return array
149 * Array of code/language name mappings
150 */
151 public static function languages($justEnabled = FALSE) {
152 static $all = NULL;
153 static $enabled = NULL;
154
155 if (!$all) {
156 $all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
157
158 // check which ones are available; add them to $all if not there already
159 $codes = array();
160 if (is_dir(CRM_Core_I18n::getResourceDir()) && $dir = opendir(CRM_Core_I18n::getResourceDir())) {
161 while ($filename = readdir($dir)) {
162 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
163 $codes[] = $filename;
164 if (!isset($all[$filename])) {
165 $all[$filename] = $filename;
166 }
167 }
168 }
169 closedir($dir);
170 }
171
172 // drop the unavailable languages (except en_US)
173 foreach (array_keys($all) as $code) {
174 if ($code == 'en_US') {
175 continue;
176 }
177 if (!in_array($code, $codes)) {
178 unset($all[$code]);
179 }
180 }
181 }
182
183 if ($enabled === NULL) {
184 $config = CRM_Core_Config::singleton();
185 $enabled = array();
186 if (isset($config->languageLimit) and $config->languageLimit) {
187 foreach ($all as $code => $name) {
188 if (in_array($code, array_keys($config->languageLimit))) {
189 $enabled[$code] = $name;
190 }
191 }
192 }
193 }
194
195 return $justEnabled ? $enabled : $all;
196 }
197
198 /**
199 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
200 *
201 * @param string $str
202 * source string.
203 *
204 * @return string
205 * modified string
206 */
207 public function strarg($str) {
208 $tr = array();
209 $p = 0;
210 for ($i = 1; $i < func_num_args(); $i++) {
211 $arg = func_get_arg($i);
212 if (is_array($arg)) {
213 foreach ($arg as $aarg) {
214 $tr['%' . ++$p] = $aarg;
215 }
216 }
217 else {
218 $tr['%' . ++$p] = $arg;
219 }
220 }
221 return strtr($str, $tr);
222 }
223
224 public static function getResourceDir() {
225 static $dir = NULL;
226 if ($dir === NULL) {
227 $dir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR;
228 }
229 return $dir;
230 }
231
232 /**
233 * Smarty block function, provides gettext support for smarty.
234 *
235 * The block content is the text that should be translated.
236 *
237 * Any parameter that is sent to the function will be represented as %n in the translation text,
238 * where n is 1 for the first parameter. The following parameters are reserved:
239 * - escape - sets escape mode:
240 * - 'html' for HTML escaping, this is the default.
241 * - 'js' for javascript escaping.
242 * - 'no'/'off'/0 - turns off escaping
243 * - plural - The plural version of the text (2nd parameter of ngettext())
244 * - count - The item count for plural mode (3rd parameter of ngettext())
245 * - context - gettext context of that string (for homonym handling)
246 *
247 * @param string $text
248 * the original string.
249 * @param array $params
250 * The params of the translation (if any).
251 * - domain: string|array a list of translation domains to search (in order)
252 * - context: string
253 *
254 * @return string
255 * the translated string
256 */
257 public function crm_translate($text, $params = array()) {
258 if (isset($params['escape'])) {
259 $escape = $params['escape'];
260 unset($params['escape']);
261 }
262
263 // sometimes we need to {ts}-tag a string, but don’t want to
264 // translate it in the template (like civicrm_navigation.tpl),
265 // because we handle the translation in a different way (CRM-6998)
266 // in such cases we return early, only doing SQL/JS escaping
267 if (isset($params['skip']) and $params['skip']) {
268 if (isset($escape) and ($escape == 'sql')) {
269 $text = CRM_Core_DAO::escapeString($text);
270 }
271 if (isset($escape) and ($escape == 'js')) {
272 $text = addcslashes($text, "'");
273 }
274 return $text;
275 }
276
277 $plural = $count = NULL;
278 if (isset($params['plural'])) {
279 $plural = $params['plural'];
280 unset($params['plural']);
281 if (isset($params['count'])) {
282 $count = $params['count'];
283 }
284 }
285
286 if (isset($params['context'])) {
287 $context = $params['context'];
288 unset($params['context']);
289 }
290 else {
291 $context = NULL;
292 }
293
294 if (isset($params['domain'])) {
295 $domain = $params['domain'];
296 unset($params['domain']);
297 }
298 else {
299 $domain = NULL;
300 }
301
302 $raw = !empty($params['raw']);
303 unset($params['raw']);
304
305 if (!empty($domain)) {
306 // It might be prettier to cast to an array, but this is high-traffic stuff.
307 if (is_array($domain)) {
308 foreach ($domain as $d) {
309 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
310 if ($candidate != $text) {
311 $text = $candidate;
312 break;
313 }
314 }
315 }
316 else {
317 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
318 }
319 }
320 else {
321 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
322 }
323
324 // replace the numbered %1, %2, etc. params if present
325 if (count($params) && !$raw) {
326 $text = $this->strarg($text, $params);
327 }
328
329 // escape SQL if we were asked for it
330 if (isset($escape) and ($escape == 'sql')) {
331 $text = CRM_Core_DAO::escapeString($text);
332 }
333
334 // escape for JavaScript (if requested)
335 if (isset($escape) and ($escape == 'js')) {
336 $text = addcslashes($text, "'");
337 }
338
339 return $text;
340 }
341
342 /**
343 * Lookup the raw translation of a string (without any extra escaping or interpolation).
344 *
345 * @param string $text
346 * @param string|NULL $domain
347 * @param int|NULL $count
348 * @param string $plural
349 * @param string $context
350 *
351 * @return string
352 */
353 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
354 // gettext domain for extensions
355 $domain_changed = FALSE;
356 if (!empty($domain) && $this->_phpgettext) {
357 if ($this->setGettextDomain($domain)) {
358 $domain_changed = TRUE;
359 }
360 }
361
362 // do all wildcard translations first
363
364 // FIXME: Is there a constant we can reference instead of hardcoding en_US?
365 $replacementsLocale = $this->locale ? $this->locale : 'en_US';
366 if (!isset(Civi::$statics[__CLASS__]) || !array_key_exists($replacementsLocale, Civi::$statics[__CLASS__])) {
367 if (defined('CIVICRM_DSN') && !CRM_Core_Config::isUpgradeMode()) {
368 Civi::$statics[__CLASS__][$replacementsLocale] = CRM_Core_BAO_WordReplacement::getLocaleCustomStrings($replacementsLocale);
369 }
370 else {
371 Civi::$statics[__CLASS__][$replacementsLocale] = array();
372 }
373 }
374 $stringTable = Civi::$statics[__CLASS__][$replacementsLocale];
375
376 $exactMatch = FALSE;
377 if (isset($stringTable['enabled']['exactMatch'])) {
378 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
379 if ($search === $text) {
380 $exactMatch = TRUE;
381 $text = $replace;
382 break;
383 }
384 }
385 }
386
387 if (
388 !$exactMatch &&
389 isset($stringTable['enabled']['wildcardMatch'])
390 ) {
391 $search = array_keys($stringTable['enabled']['wildcardMatch']);
392 $replace = array_values($stringTable['enabled']['wildcardMatch']);
393 $text = str_replace($search, $replace, $text);
394 }
395
396 // dont translate if we've done exactMatch already
397 if (!$exactMatch) {
398 // use plural if required parameters are set
399 if (isset($count) && isset($plural)) {
400
401 if ($this->_phpgettext) {
402 $text = $this->_phpgettext->ngettext($text, $plural, $count);
403 }
404 else {
405 // if the locale's not set, we do ngettext work by hand
406 // if $count == 1 then $text = $text, else $text = $plural
407 if ($count != 1) {
408 $text = $plural;
409 }
410 }
411
412 // expand %count in translated string to $count
413 $text = strtr($text, array('%count' => $count));
414
415 // if not plural, but the locale's set, translate
416 }
417 elseif ($this->_phpgettext) {
418 if ($context) {
419 $text = $this->_phpgettext->pgettext($context, $text);
420 }
421 else {
422 $text = $this->_phpgettext->translate($text);
423 }
424 }
425 }
426
427 if ($domain_changed) {
428 $this->setGettextDomain('civicrm');
429 }
430
431 return $text;
432 }
433
434 /**
435 * Translate a string to the current locale.
436 *
437 * @param string $string
438 * this string should be translated.
439 *
440 * @return string
441 * the translated string
442 */
443 public function translate($string) {
444 return ($this->_phpgettext) ? $this->_phpgettext->translate($string) : $string;
445 }
446
447 /**
448 * Localize (destructively) array values.
449 *
450 * @param array $array
451 * the array for localization (in place).
452 * @param array $params
453 * an array of additional parameters.
454 */
455 public function localizeArray(
456 &$array,
457 $params = array()
458 ) {
459 $tsLocale = CRM_Core_I18n::getLocale();
460
461 if ($tsLocale == 'en_US') {
462 return;
463 }
464
465 foreach ($array as & $value) {
466 if ($value) {
467 $value = ts($value, $params);
468 }
469 }
470 }
471
472 /**
473 * Localize (destructively) array elements with keys of 'title'.
474 *
475 * @param array $array
476 * the array for localization (in place).
477 */
478 public function localizeTitles(&$array) {
479 foreach ($array as $key => $value) {
480 if (is_array($value)) {
481 $this->localizeTitles($value);
482 $array[$key] = $value;
483 }
484 elseif ((string ) $key == 'title') {
485 $array[$key] = ts($value, array('context' => 'menu'));
486 }
487 }
488 }
489
490 /**
491 * Binds a gettext domain, wrapper over bindtextdomain().
492 *
493 * @param $key
494 * Key of the extension (can be 'civicrm', or 'org.example.foo').
495 *
496 * @return Bool
497 * True if the domain was changed for an extension.
498 */
499 public function setGettextDomain($key) {
500 /* No domain changes for en_US */
501 if (!$this->_phpgettext) {
502 return FALSE;
503 }
504
505 // It's only necessary to find/bind once
506 if (!isset($this->_extensioncache[$key])) {
507 try {
508 $mapper = CRM_Extension_System::singleton()->getMapper();
509 $path = $mapper->keyToBasePath($key);
510 $info = $mapper->keyToInfo($key);
511 $domain = $info->file;
512
513 if ($this->_nativegettext) {
514 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR . 'l10n');
515 bind_textdomain_codeset($domain, 'UTF-8');
516 $this->_extensioncache[$key] = $domain;
517 }
518 else {
519 // phpgettext
520 $mo_file = $path . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR . $this->locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $domain . '.mo';
521 $streamer = new FileReader($mo_file);
522 $this->_extensioncache[$key] = new gettext_reader($streamer);
523 }
524 }
525 catch (CRM_Extension_Exception $e) {
526 // Intentionally not translating this string to avoid possible infinite loops
527 // Only developers should see this string, if they made a mistake in their ts() usage.
528 CRM_Core_Session::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
529 $this->_extensioncache[$key] = FALSE;
530 }
531 }
532
533 if (isset($this->_extensioncache[$key]) && $this->_extensioncache[$key]) {
534 if ($this->_nativegettext) {
535 textdomain($this->_extensioncache[$key]);
536 }
537 else {
538 $this->_phpgettext = $this->_extensioncache[$key];
539 }
540
541 return TRUE;
542 }
543
544 return FALSE;
545 }
546
547
548 /**
549 * Is the CiviCRM in multilingual mode.
550 *
551 * @return Bool
552 * True if CiviCRM is in multilingual mode.
553 */
554 public static function isMultilingual() {
555 $domain = new CRM_Core_DAO_Domain();
556 $domain->find(TRUE);
557 return (bool) $domain->locales;
558 }
559
560 /**
561 * Is the language written "right-to-left"?
562 *
563 * @param $language
564 * Language (for example 'en_US', or 'fr_CA').
565 *
566 * @return Bool
567 * True if it is an RTL language.
568 */
569 public static function isLanguageRTL($language) {
570 $rtl = CRM_Core_I18n_PseudoConstant::getRTLlanguages();
571 $short = CRM_Core_I18n_PseudoConstant::shortForLong($language);
572
573 return (in_array($short, $rtl));
574 }
575
576 /**
577 * Change the processing language without changing the current user language
578 *
579 * @param $locale
580 * Locale (for example 'en_US', or 'fr_CA').
581 * True if the domain was changed for an extension.
582 */
583 public function setLocale($locale) {
584
585 // Change the language of the CMS as well, for URLs.
586 CRM_Utils_System::setUFLocale($locale);
587
588 // change the gettext ressources
589 if ($this->_nativegettext) {
590 $this->setNativeGettextLocale($locale);
591 }
592 else {
593 // phpgettext
594 $this->setPhpGettextLocale($locale);
595 }
596
597 // for sql queries
598 global $dbLocale;
599 $dbLocale = "_{$locale}";
600
601 }
602
603 /**
604 * Static instance provider - return the instance for the current locale.
605 *
606 * @return CRM_Core_I18n
607 */
608 public static function &singleton() {
609 static $singleton = array();
610
611 $tsLocale = CRM_Core_I18n::getLocale();
612 if (!isset($singleton[$tsLocale])) {
613 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
614 }
615
616 return $singleton[$tsLocale];
617 }
618
619 /**
620 * Set the LC_TIME locale if it's not set already (for a given language choice).
621 *
622 * @return string
623 * the final LC_TIME that got set
624 */
625 public static function setLcTime() {
626 static $locales = array();
627
628 $tsLocale = CRM_Core_I18n::getLocale();
629 if (!isset($locales[$tsLocale])) {
630 // with the config being set to pl_PL: try pl_PL.UTF-8,
631 // then pl_PL, if neither present fall back to C
632 $locales[$tsLocale] = setlocale(LC_TIME, $tsLocale . '.UTF-8', $tsLocale, 'C');
633 }
634
635 return $locales[$tsLocale];
636 }
637
638 /**
639 * Get the default language for contacts where no language is provided.
640 *
641 * Note that NULL is a valid option so be careful with checking for empty etc.
642 *
643 * NULL would mean 'we don't know & we don't want to hazard a guess'.
644 *
645 * @return string
646 */
647 public static function getContactDefaultLanguage() {
648 $language = Civi::settings()->get('contact_default_language');
649 if ($language == 'undefined') {
650 return NULL;
651 }
652 if (empty($language) || $language === '*default*') {
653 $language = civicrm_api3('setting', 'getvalue', array(
654 'name' => 'lcMessages',
655 'group' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
656 ));
657 }
658 elseif ($language == 'current_site_language') {
659 return CRM_Core_I18n::getLocale();
660 }
661
662 return $language;
663 }
664
665 /**
666 * Get the current locale
667 *
668 * @return string
669 */
670 public static function getLocale() {
671 global $tsLocale;
672 return $tsLocale;
673 }
674
675 }
676
677 /**
678 * Short-named function for string translation, defined in global scope so it's available everywhere.
679 *
680 * @param string $text
681 * String string for translating.
682 * @param array $params
683 * Array an array of additional parameters.
684 *
685 * @return string
686 * the translated string
687 */
688 function ts($text, $params = array()) {
689 static $config = NULL;
690 static $locale = NULL;
691 static $i18n = NULL;
692 static $function = NULL;
693
694 if ($text == '') {
695 return '';
696 }
697
698 if (!$config) {
699 $config = CRM_Core_Config::singleton();
700 }
701
702 $tsLocale = CRM_Core_I18n::getLocale();
703 if (!$i18n or $locale != $tsLocale) {
704 $i18n = CRM_Core_I18n::singleton();
705 $locale = $tsLocale;
706 if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
707 $function = $config->customTranslateFunction;
708 }
709 }
710
711 if ($function) {
712 return $function($text, $params);
713 }
714 else {
715 return $i18n->crm_translate($text, $params);
716 }
717 }