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