Merge pull request #4812 from colemanw/CRM-15495
[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 $locale string the base of this certain object's existence
59 *
60 * @return \CRM_Core_I18n
61 */
62 public function __construct($locale) {
63 if ($locale != '' and $locale != 'en_US') {
64 $config = CRM_Core_Config::singleton();
65
66 if (defined('CIVICRM_GETTEXT_NATIVE') && CIVICRM_GETTEXT_NATIVE && function_exists('gettext')) {
67 // Note: the file hierarchy for .po must be, for example: l10n/fr_FR/LC_MESSAGES/civicrm.mo
68
69 $this->_nativegettext = TRUE;
70
71 $locale .= '.utf8';
72 putenv("LANG=$locale");
73
74 // CRM-11833 Avoid LC_ALL because of LC_NUMERIC and potential DB error.
75 setlocale(LC_TIME, $locale);
76 setlocale(LC_MESSAGES, $locale);
77 setlocale(LC_CTYPE, $locale);
78
79 bindtextdomain('civicrm', $config->gettextResourceDir);
80 bind_textdomain_codeset('civicrm', 'UTF-8');
81 textdomain('civicrm');
82
83 $this->_phpgettext = new CRM_Core_I18n_NativeGettext();
84 $this->_extensioncache['civicrm'] = 'civicrm';
85 return;
86 }
87
88 // Otherwise, use PHP-gettext
89 // we support both the old file hierarchy format and the new:
90 // pre-4.5: civicrm/l10n/xx_XX/civicrm.mo
91 // post-4.5: civicrm/l10n/xx_XX/LC_MESSAGES/civicrm.mo
92 require_once 'PHPgettext/streams.php';
93 require_once 'PHPgettext/gettext.php';
94
95 $mo_file = $config->gettextResourceDir . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . 'civicrm.mo';
96
97 if (! file_exists($mo_file)) {
98 // fallback to pre-4.5 mode
99 $mo_file = $config->gettextResourceDir . $locale . DIRECTORY_SEPARATOR . 'civicrm.mo';
100 }
101
102 $streamer = new FileReader($mo_file);
103 $this->_phpgettext = new gettext_reader($streamer);
104 $this->_extensioncache['civicrm'] = $this->_phpgettext;
105 }
106 }
107
108 /**
109 * Returns whether gettext is running natively or using PHP-Gettext.
110 *
111 * @return bool True if gettext is native
112 */
113 public function isNative() {
114 return $this->_nativegettext;
115 }
116
117 /**
118 * Return languages available in this instance of CiviCRM.
119 *
120 * @param $justEnabled boolean whether to return all languages or just the enabled ones
121 *
122 * @return array of code/language name mappings
123 */
124 public static function languages($justEnabled = FALSE) {
125 static $all = NULL;
126 static $enabled = NULL;
127
128 if (!$all) {
129 $all = CRM_Contact_BAO_Contact::buildOptions('preferred_language');
130
131 // check which ones are available; add them to $all if not there already
132 $config = CRM_Core_Config::singleton();
133 $codes = array();
134 if (is_dir($config->gettextResourceDir) && $dir = opendir($config->gettextResourceDir)) {
135 while ($filename = readdir($dir)) {
136 if (preg_match('/^[a-z][a-z]_[A-Z][A-Z]$/', $filename)) {
137 $codes[] = $filename;
138 if (!isset($all[$filename])) {
139 $all[$filename] = $filename;
140 }
141 }
142 }
143 closedir($dir);
144 }
145
146 // drop the unavailable languages (except en_US)
147 foreach (array_keys($all) as $code) {
148 if ($code == 'en_US') {
149 continue;
150 }
151 if (!in_array($code, $codes))unset($all[$code]);
152 }
153 }
154
155 if ($enabled === NULL) {
156 $config = CRM_Core_Config::singleton();
157 $enabled = array();
158 if (isset($config->languageLimit) and $config->languageLimit) {
159 foreach ($all as $code => $name) {
160 if (in_array($code, array_keys($config->languageLimit))) {
161 $enabled[$code] = $name;
162 }
163 }
164 }
165 }
166
167 return $justEnabled ? $enabled : $all;
168 }
169
170 /**
171 * Replace arguments in a string with their values. Arguments are represented by % followed by their number.
172 *
173 * @param $str string source string
174 * @param mixed arguments, can be passed in an array or through single variables
175 *
176 * @return string modified string
177 */
178 public function strarg($str) {
179 $tr = array();
180 $p = 0;
181 for ($i = 1; $i < func_num_args(); $i++) {
182 $arg = func_get_arg($i);
183 if (is_array($arg)) {
184 foreach ($arg as $aarg) {
185 $tr['%' . ++$p] = $aarg;
186 }
187 }
188 else {
189 $tr['%' . ++$p] = $arg;
190 }
191 }
192 return strtr($str, $tr);
193 }
194
195 /**
196 * Smarty block function, provides gettext support for smarty.
197 *
198 * The block content is the text that should be translated.
199 *
200 * Any parameter that is sent to the function will be represented as %n in the translation text,
201 * where n is 1 for the first parameter. The following parameters are reserved:
202 * - escape - sets escape mode:
203 * - 'html' for HTML escaping, this is the default.
204 * - 'js' for javascript escaping.
205 * - 'no'/'off'/0 - turns off escaping
206 * - plural - The plural version of the text (2nd parameter of ngettext())
207 * - count - The item count for plural mode (3rd parameter of ngettext())
208 * - context - gettext context of that string (for homonym handling)
209 *
210 * @param $text string the original string
211 * @param $params array the params of the translation (if any)
212 *
213 * @return string the translated string
214 */
215 public function crm_translate($text, $params = array()) {
216 if (isset($params['escape'])) {
217 $escape = $params['escape'];
218 unset($params['escape']);
219 }
220
221 // sometimes we need to {ts}-tag a string, but don’t want to
222 // translate it in the template (like civicrm_navigation.tpl),
223 // because we handle the translation in a different way (CRM-6998)
224 // in such cases we return early, only doing SQL/JS escaping
225 if (isset($params['skip']) and $params['skip']) {
226 if (isset($escape) and ($escape == 'sql')) {
227 $text = CRM_Core_DAO::escapeString($text);
228 }
229 if (isset($escape) and ($escape == 'js')) {
230 $text = addcslashes($text, "'");
231 }
232 return $text;
233 }
234
235 if (isset($params['plural'])) {
236 $plural = $params['plural'];
237 unset($params['plural']);
238 if (isset($params['count'])) {
239 $count = $params['count'];
240 }
241 }
242
243 if (isset($params['context'])) {
244 $context = $params['context'];
245 unset($params['context']);
246 }
247 else {
248 $context = NULL;
249 }
250
251 // gettext domain for extensions
252 $domain_changed = FALSE;
253 if (! empty($params['domain']) && $this->_phpgettext) {
254 if ($this->setGettextDomain($params['domain'])) {
255 $domain_changed = TRUE;
256 }
257 }
258
259 // do all wildcard translations first
260 $config = CRM_Core_Config::singleton();
261 $stringTable = CRM_Utils_Array::value(
262 $config->lcMessages,
263 $config->localeCustomStrings
264 );
265
266 $exactMatch = FALSE;
267 if (isset($stringTable['enabled']['exactMatch'])) {
268 foreach ($stringTable['enabled']['exactMatch'] as $search => $replace) {
269 if ($search === $text) {
270 $exactMatch = TRUE;
271 $text = $replace;
272 break;
273 }
274 }
275 }
276
277 if (
278 !$exactMatch &&
279 isset($stringTable['enabled']['wildcardMatch'])
280 ) {
281 $search = array_keys($stringTable['enabled']['wildcardMatch']);
282 $replace = array_values($stringTable['enabled']['wildcardMatch']);
283 $text = str_replace($search, $replace, $text);
284 }
285
286 // dont translate if we've done exactMatch already
287 if (!$exactMatch) {
288 // use plural if required parameters are set
289 if (isset($count) && isset($plural)) {
290
291 if ($this->_phpgettext) {
292 $text = $this->_phpgettext->ngettext($text, $plural, $count);
293 }
294 else {
295 // if the locale's not set, we do ngettext work by hand
296 // if $count == 1 then $text = $text, else $text = $plural
297 if ($count != 1) {
298 $text = $plural;
299 }
300 }
301
302 // expand %count in translated string to $count
303 $text = strtr($text, array('%count' => $count));
304
305 // if not plural, but the locale's set, translate
306 }
307 elseif ($this->_phpgettext) {
308 if ($context) {
309 $text = $this->_phpgettext->pgettext($context, $text);
310 }
311 else {
312 $text = $this->_phpgettext->translate($text);
313 }
314 }
315 }
316
317 // replace the numbered %1, %2, etc. params if present
318 if (count($params)) {
319 $text = $this->strarg($text, $params);
320 }
321
322 // escape SQL if we were asked for it
323 if (isset($escape) and ($escape == 'sql')) {
324 $text = CRM_Core_DAO::escapeString($text);
325 }
326
327 // escape for JavaScript (if requested)
328 if (isset($escape) and ($escape == 'js')) {
329 $text = addcslashes($text, "'");
330 }
331
332 if ($domain_changed) {
333 $this->setGettextDomain('civicrm');
334 }
335
336 return $text;
337 }
338
339 /**
340 * Translate a string to the current locale.
341 *
342 * @param $string string this string should be translated
343 *
344 * @return string the translated string
345 */
346 public function translate($string) {
347 return ($this->_phpgettext) ? $this->_phpgettext->translate($string) : $string;
348 }
349
350 /**
351 * Localize (destructively) array values.
352 *
353 * @param $array array the array for localization (in place)
354 * @param $params array an array of additional parameters
355 *
356 * @return void
357 */
358 function localizeArray(
359 &$array,
360 $params = array()
361 ) {
362 global $tsLocale;
363
364 if ($tsLocale == 'en_US') {
365 return;
366 }
367
368 foreach ($array as & $value) {
369 if ($value) {
370 $value = ts($value, $params);
371 }
372 }
373 }
374
375 /**
376 * Localize (destructively) array elements with keys of 'title'.
377 *
378 * @param $array array the array for localization (in place)
379 *
380 * @return void
381 */
382 public function localizeTitles(&$array) {
383 foreach ($array as $key => $value) {
384 if (is_array($value)) {
385 $this->localizeTitles($value);
386 $array[$key] = $value;
387 }
388 elseif ((string ) $key == 'title') {
389 $array[$key] = ts($value, array('context' => 'menu'));
390 }
391 }
392 }
393
394 /**
395 * Binds a gettext domain, wrapper over bindtextdomain().
396 *
397 * @param $key Key of the extension (can be 'civicrm', or 'org.example.foo').
398 *
399 * @return Boolean True if the domain was changed for an extension.
400 */
401 public function setGettextDomain($key) {
402 /* No domain changes for en_US */
403 if (! $this->_phpgettext) {
404 return FALSE;
405 }
406
407 // It's only necessary to find/bind once
408 if (! isset($this->_extensioncache[$key])) {
409 $config = CRM_Core_Config::singleton();
410
411 try {
412 $mapper = CRM_Extension_System::singleton()->getMapper();
413 $path = $mapper->keyToBasePath($key);
414 $info = $mapper->keyToInfo($key);
415 $domain = $info->file;
416
417 if ($this->_nativegettext) {
418 bindtextdomain($domain, $path . DIRECTORY_SEPARATOR . 'l10n');
419 bind_textdomain_codeset($domain, 'UTF-8');
420 $this->_extensioncache[$key] = $domain;
421 }
422 else {
423 // phpgettext
424 $mo_file = $path . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR . $config->lcMessages . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $domain . '.mo';
425 $streamer = new FileReader($mo_file);
426 $this->_extensioncache[$key] = new gettext_reader($streamer);
427 }
428 }
429 catch (CRM_Extension_Exception $e) {
430 // Intentionally not translating this string to avoid possible infinit loops
431 // Only developers should see this string, if they made a mistake in their ts() usage.
432 CRM_Core_Session::setStatus('Unknown extension key in a translation string: ' . $key, '', 'error');
433 $this->_extensioncache[$key] = FALSE;
434 }
435 }
436
437 if (isset($this->_extensioncache[$key]) && $this->_extensioncache[$key]) {
438 if ($this->_nativegettext) {
439 textdomain($this->_extensioncache[$key]);
440 }
441 else {
442 $this->_phpgettext = $this->_extensioncache[$key];
443 }
444
445 return TRUE;
446 }
447
448 return FALSE;
449 }
450
451 /**
452 * Static instance provider - return the instance for the current locale.
453 */
454 public static function &singleton() {
455 static $singleton = array();
456
457 global $tsLocale;
458 if (!isset($singleton[$tsLocale])) {
459 $singleton[$tsLocale] = new CRM_Core_I18n($tsLocale);
460 }
461
462 return $singleton[$tsLocale];
463 }
464
465 /**
466 * Set the LC_TIME locale if it's not set already (for a given language choice).
467 *
468 * @return string the final LC_TIME that got set
469 */
470 public static function setLcTime() {
471 static $locales = array();
472
473 global $tsLocale;
474 if (!isset($locales[$tsLocale])) {
475 // with the config being set to pl_PL: try pl_PL.UTF-8,
476 // then pl_PL, if neither present fall back to C
477 $locales[$tsLocale] = setlocale(LC_TIME, $tsLocale . '.UTF-8', $tsLocale, 'C');
478 }
479
480 return $locales[$tsLocale];
481 }
482 }
483
484 /**
485 * Short-named function for string translation, defined in global scope so it's available everywhere.
486 *
487 * @param $text string string for translating
488 * @param $params array an array of additional parameters
489 *
490 * @return string the translated string
491 */
492 function ts($text, $params = array()) {
493 static $config = NULL;
494 static $locale = NULL;
495 static $i18n = NULL;
496 static $function = NULL;
497
498 if ($text == '') {
499 return '';
500 }
501
502 if (!$config) {
503 $config = CRM_Core_Config::singleton();
504 }
505
506 global $tsLocale;
507 if (!$i18n or $locale != $tsLocale) {
508 $i18n = CRM_Core_I18n::singleton();
509 $locale = $tsLocale;
510 if (isset($config->customTranslateFunction) and function_exists($config->customTranslateFunction)) {
511 $function = $config->customTranslateFunction;
512 }
513 }
514
515 if ($function) {
516 return $function($text, $params);
517 }
518 else {
519 return $i18n->crm_translate($text, $params);
520 }
521 }