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