Merge pull request #5048 from totten/master-mailing-misc
[civicrm-core.git] / CRM / Core / I18n.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Core_I18n {
36
37 /**
38 * A PHP-gettext instance for string translation;
39 * should stay null if the strings are not to be translated (en_US).
40 */
41 private $_phpgettext = NULL;
42
43 /**
44 * Whether we are using native gettext or not.
45 */
46 private $_nativegettext = FALSE;
47
48 /**
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.
52 */
53 private $_extensioncache = array();
54
55 /**
56 * A locale-based constructor that shouldn't be called from outside of this class (use singleton() instead).
57 *
58 * @param string $locale
59 * the base of this certain object's existence.
60 *
61 * @return \CRM_Core_I18n
62 */
63 public function __construct($locale) {
64 if ($locale != '' and $locale != 'en_US') {
65 $config = CRM_Core_Config::singleton();
66
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
69
70 $this->_nativegettext = TRUE;
71
72 $locale .= '.utf8';
73 putenv("LANG=$locale");
74
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);
79
80 bindtextdomain('civicrm', $config->gettextResourceDir);
81 bind_textdomain_codeset('civicrm', 'UTF-8');
82 textdomain('civicrm');
83
84 $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
85 $this->_extensioncache['civicrm'] = 'civicrm';
86 return;
87 }
88
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';
95
96 $mo_file = $config->gettextResourceDir . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
97
98 if (!file_exists($mo_file)) {
99 // fallback to pre-4.5 mode
100 $mo_file = $config->gettextResourceDir . $locale . DIRECTORY_SEPARATOR . 'civicrm.mo';
101 }
102
103 $streamer = new FileReader($mo_file);
104 $this->_phpgettext = new gettext_reader($streamer);
105 $this->_extensioncache['civicrm'] = $this->_phpgettext;
106 }
107 }
108
109 /**
110 * Returns whether gettext is running natively or using PHP-Gettext.
111 *
112 * @return bool
113 * True if gettext is native
114 */
115 public function isNative() {
116 return $this->_nativegettext;
117 }
118
119 /**
120 * Return languages available in this instance of CiviCRM.
121 *
122 * @param bool $justEnabled
123 * whether to return all languages or just the enabled ones.
124 *
125 * @return array
126 * Array of code/language name mappings
127 */
128 public static function languages($justEnabled = FALSE) {
129 static $all = NULL;
130 static $enabled = NULL;
131
132 if (!$all) {
133 $all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
134
135 // check which ones are available; add them to $all if not there already
136 $config = CRM_Core_Config::singleton();
137 $codes = array();
138 if (is_dir($config->gettextResourceDir) && $dir = opendir($config->gettextResourceDir)) {
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;
144 }
145 }
146 }
147 closedir($dir);
148 }
149
150 // drop the unavailable languages (except en_US)
151 foreach (array_keys($all) as $code) {
152 if ($code == 'en_US') {
153 continue;
154 }
155 if (!in_array($code, $codes)) {
156 unset($all[$code]);
157 }
158 }
159 }
160
161 if ($enabled === NULL) {
162 $config = CRM_Core_Config::singleton();
163 $enabled = array();
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;
168 }
169 }
170 }
171 }
172
173 return $justEnabled ? $enabled : $all;
174 }
175
176 /**
177 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
178 *
179 * @param string $str
180 * source string.
181 *
182 * @return string
183 * modified string
184 */
185 public function strarg($str) {
186 $tr = array();
187 $p = 0;
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;
193 }
194 }
195 else {
196 $tr['%' . ++$p] = $arg;
197 }
198 }
199 return strtr($str, $tr);
200 }
201
202 /**
203 * Smarty block function, provides gettext support for smarty.
204 *
205 * The block content is the text that should be translated.
206 *
207 * Any parameter that is sent to the function will be represented as %n in the translation text,
208 * where n is 1 for the first parameter. The following parameters are reserved:
209 * - escape - sets escape mode:
210 * - 'html' for HTML escaping, this is the default.
211 * - 'js' for javascript escaping.
212 * - 'no'/'off'/0 - turns off escaping
213 * - plural - The plural version of the text (2nd parameter of ngettext())
214 * - count - The item count for plural mode (3rd parameter of ngettext())
215 * - context - gettext context of that string (for homonym handling)
216 *
217 * @param string $text
218 * the original string.
219 * @param array $params
220 * The params of the translation (if any).
221 * - domain: string|array a list of translation domains to search (in order)
222 * - context: string
223 * @return string
224 * the translated string
225 */
226 public function crm_translate($text, $params = array()) {
227 if (isset($params['escape'])) {
228 $escape = $params['escape'];
229 unset($params['escape']);
230 }
231
232 // sometimes we need to {ts}-tag a string, but don’t want to
233 // translate it in the template (like civicrm_navigation.tpl),
234 // because we handle the translation in a different way (CRM-6998)
235 // in such cases we return early, only doing SQL/JS escaping
236 if (isset($params['skip']) and $params['skip']) {
237 if (isset($escape) and ($escape == 'sql')) {
238 $text = CRM_Core_DAO::escapeString($text);
239 }
240 if (isset($escape) and ($escape == 'js')) {
241 $text = addcslashes($text, "'");
242 }
243 return $text;
244 }
245
246 $plural = $count = NULL;
247 if (isset($params['plural'])) {
248 $plural = $params['plural'];
249 unset($params['plural']);
250 if (isset($params['count'])) {
251 $count = $params['count'];
252 }
253 }
254
255 if (isset($params['context'])) {
256 $context = $params['context'];
257 unset($params['context']);
258 }
259 else {
260 $context = NULL;
261 }
262
263 if (isset($params['domain'])) {
264 $domain = $params['domain'];
265 unset($params['domain']);
266 }
267 else {
268 $domain = NULL;
269 }
270
271 if (!empty($domain)) {
272 // It might be prettier to cast to an array, but this is high-traffic stuff.
273 if (is_array($domain)) {
274 foreach ($domain as $d) {
275 $candidate = $this->crm_translate_raw($text, $d, $count, $plural, $context);
276 if ($candidate != $text) {
277 $text = $candidate;
278 break;
279 }
280 }
281 }
282 else {
283 $text = $this->crm_translate_raw($text, $domain, $count, $plural, $context);
284 }
285 }
286 else {
287 $text = $this->crm_translate_raw($text, NULL, $count, $plural, $context);
288 }
289
290 // replace the numbered %1, %2, etc. params if present
291 if (count($params)) {
292 $text = $this->strarg($text, $params);
293 }
294
295 // escape SQL if we were asked for it
296 if (isset($escape) and ($escape == 'sql')) {
297 $text = CRM_Core_DAO::escapeString($text);
298 }
299
300 // escape for JavaScript (if requested)
301 if (isset($escape) and ($escape == 'js')) {
302 $text = addcslashes($text, "'");
303 }
304
305 return $text;
306 }
307
308 /**
309 * Lookup the raw translation of a string (without any extra escaping or interpolation).
310 *
311 * @param string $text
312 * @param string|NULL $domain
313 * @param int|NULL $count
314 * @param string $plural
315 * @param string $context
316 * @return mixed|string|translated
317 */
318 protected function crm_translate_raw($text, $domain, $count, $plural, $context) {
319 // gettext domain for extensions
320 $domain_changed = FALSE;
321 if (!empty($domain) && $this->_phpgettext) {
322 if ($this->setGettextDomain($domain)) {
323 $domain_changed = TRUE;
324 }
325 }
326
327 // do all wildcard translations first
328 $config = CRM_Core_Config::singleton();
329 $stringTable = CRM_Utils_Array::value(
330 $config->lcMessages,
331 $config->localeCustomStrings
332 );
333
334 $exactMatch = FALSE;
335 if (isset($stringTable['enabled']['exactMatch'])) {
336 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
337 if ($search === $text) {
338 $exactMatch = TRUE;
339 $text = $replace;
340 break;
341 }
342 }
343 }
344
345 if (
346 !$exactMatch &&
347 isset($stringTable['enabled']['wildcardMatch'])
348 ) {
349 $search = array_keys($stringTable['enabled']['wildcardMatch']);
350 $replace = array_values($stringTable['enabled']['wildcardMatch']);
351 $text = str_replace($search, $replace, $text);
352 }
353
354 // dont translate if we've done exactMatch already
355 if (!$exactMatch) {
356 // use plural if required parameters are set
357 if (isset($count) && isset($plural)) {
358
359 if ($this->_phpgettext) {
360 $text = $this->_phpgettext->ngettext($text, $plural, $count);
361 }
362 else {
363 // if the locale's not set, we do ngettext work by hand
364 // if $count == 1 then $text = $text, else $text = $plural
365 if ($count != 1) {
366 $text = $plural;
367 }
368 }
369
370 // expand %count in translated string to $count
371 $text = strtr($text, array('%count' => $count));
372
373 // if not plural, but the locale's set, translate
374 }
375 elseif ($this->_phpgettext) {
376 if ($context) {
377 $text = $this->_phpgettext->pgettext($context, $text);
378 }
379 else {
380 $text = $this->_phpgettext->translate($text);
381 }
382 }
383 }
384
385 if ($domain_changed) {
386 $this->setGettextDomain('civicrm');
387 }
388
389 return $text;
390 }
391
392 /**
393 * Translate a string to the current locale.
394 *
395 * @param string $string
396 * this string should be translated.
397 *
398 * @return string
399 * the translated string
400 */
401 public function translate($string) {
402 return ($this->_phpgettext) ? $this->_phpgettext->translate($string) : $string;
403 }
404
405 /**
406 * Localize (destructively) array values.
407 *
408 * @param array $array
409 * the array for localization (in place).
410 * @param array $params
411 * an array of additional parameters.
412 *
413 * @return void
414 */
415 public function localizeArray(
416 &$array,
417 $params = array()
418 ) {
419 global $tsLocale;
420
421 if ($tsLocale == 'en_US') {
422 return;
423 }
424
425 foreach ($array as & $value) {
426 if ($value) {
427 $value = ts($value, $params);
428 }
429 }
430 }
431
432 /**
433 * Localize (destructively) array elements with keys of 'title'.
434 *
435 * @param array $array
436 * the array for localization (in place).
437 *
438 * @return void
439 */
440 public function localizeTitles(&$array) {
441 foreach ($array as $key => $value) {
442 if (is_array($value)) {
443 $this->localizeTitles($value);
444 $array[$key] = $value;
445 }
446 elseif ((string ) $key == 'title') {
447 $array[$key] = ts($value, array('context' => 'menu'));
448 }
449 }
450 }
451
452 /**
453 * Binds a gettext domain, wrapper over bindtextdomain().
454 *
455 * @param $key
456 * Key of the extension (can be 'civicrm', or 'org.example.foo').
457 *
458 * @return Bool
459 * True if the domain was changed for an extension.
460 */
461 public function setGettextDomain($key) {
462 /* No domain changes for en_US */
463 if (!$this->_phpgettext) {
464 return FALSE;
465 }
466
467 // It's only necessary to find/bind once
468 if (!isset($this->_extensioncache[$key])) {
469 $config = CRM_Core_Config::singleton();
470
471 try {
472 $mapper = CRM_Extension_System::singleton()->getMapper();
473 $path = $mapper->keyToBasePath($key);
474 $info = $mapper->keyToInfo($key);
475 $domain = $info->file;
476
477 if ($this->_nativegettext) {
478 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR . 'l10n');
479 bind_textdomain_codeset($domain, 'UTF-8');
480 $this->_extensioncache[$key] = $domain;
481 }
482 else {
483 // phpgettext
484 $mo_file = $path . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR . $config->lcMessages . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $domain . '.mo';
485 $streamer = new FileReader($mo_file);
486 $this->_extensioncache[$key] = new gettext_reader($streamer);
487 }
488 }
489 catch (CRM_Extension_Exception $e) {
490 // Intentionally not translating this string to avoid possible infinit loops
491 // Only developers should see this string, if they made a mistake in their ts() usage.
492 CRM_Core_Session::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
493 $this->_extensioncache[$key] = FALSE;
494 }
495 }
496
497 if (isset($this->_extensioncache[$key]) && $this->_extensioncache[$key]) {
498 if ($this->_nativegettext) {
499 textdomain($this->_extensioncache[$key]);
500 }
501 else {
502 $this->_phpgettext = $this->_extensioncache[$key];
503 }
504
505 return TRUE;
506 }
507
508 return FALSE;
509 }
510
511 /**
512 * Static instance provider - return the instance for the current locale.
513 */
514 public static function &singleton() {
515 static $singleton = array();
516
517 global $tsLocale;
518 if (!isset($singleton[$tsLocale])) {
519 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
520 }
521
522 return $singleton[$tsLocale];
523 }
524
525 /**
526 * Set the LC_TIME locale if it's not set already (for a given language choice).
527 *
528 * @return string
529 * the final LC_TIME that got set
530 */
531 public static function setLcTime() {
532 static $locales = array();
533
534 global $tsLocale;
535 if (!isset($locales[$tsLocale])) {
536 // with the config being set to pl_PL: try pl_PL.UTF-8,
537 // then pl_PL, if neither present fall back to C
538 $locales[$tsLocale] = setlocale(LC_TIME, $tsLocale . '.UTF-8', $tsLocale, 'C');
539 }
540
541 return $locales[$tsLocale];
542 }
543
544 }
545
546 /**
547 * Short-named function for string translation, defined in global scope so it's available everywhere.
548 *
549 * @param $text
550 * String string for translating.
551 * @param array $params
552 * Array an array of additional parameters.
553 *
554 * @return string
555 * the translated string
556 */
557 function ts($text, $params = array()) {
558 static $config = NULL;
559 static $locale = NULL;
560 static $i18n = NULL;
561 static $function = NULL;
562
563 if ($text == '') {
564 return '';
565 }
566
567 if (!$config) {
568 $config = CRM_Core_Config::singleton();
569 }
570
571 global $tsLocale;
572 if (!$i18n or $locale != $tsLocale) {
573 $i18n = CRM_Core_I18n::singleton();
574 $locale = $tsLocale;
575 if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
576 $function = $config->customTranslateFunction;
577 }
578 }
579
580 if ($function) {
581 return $function($text, $params);
582 }
583 else {
584 return $i18n->crm_translate($text, $params);
585 }
586 }