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