2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
4 // Copyright (c) 2003 Laurent Bedubourg
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // Authors: Laurent Bedubourg <laurent.bedubourg@free.fr>
23 define('GETTEXT_NATIVE', 1);
24 define('GETTEXT_PHP', 2);
26 function get_text_init($managerType = GETTEXT_NATIVE) {
28 if (!isset($GetText)) {
30 if ($managerType == GETTEXT_NATIVE)
32 if (function_exists('gettext'))
34 $GetText = new gettext_native_support();
38 // fail back to php support
39 $GetText = new gettext_php_support();
43 function raise_error($str) {
48 function is_error($err) {
53 * Interface to gettext native support.
55 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
58 class gettext_native_support
60 var $_interpolation_vars = array();
64 * Set gettext language code.
65 * @throws GetText_Error
67 function set_language($lang_code, $encoding)
69 putenv("LANG=$lang_code");
70 putenv("LC_ALL=$lang_code");
71 putenv("LANGUAGE=$lang_code");
73 // cover a couple of country/encoding variants
74 $up = strtoupper($encoding);
75 $low = strtolower($encoding);
76 $lshort = strtr($up, '-','');
77 $ushort = strtr($low, '-','');
79 if ($lang_code == 'C')
80 $set = setlocale(LC_ALL,'C');
82 $set = setlocale(LC_ALL, $lang_code.".".$encoding,
83 $lang_code.".".$up, $lang_code.".".$low,
84 $lang_code.".".$ushort, $lang_code.".".$lshort);
86 setlocale(LC_NUMERIC, 'C'); // important for numeric presentation etc.
89 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
91 $str = sprintf('language code "%s", encoding "%s" not supported by your system',
92 $lang_code, $encoding);
93 return raise_error("1 " . $str);
97 * Check system support for given language nedded for gettext.
99 function check_support($lang_code, $encoding)
101 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
103 $old = setlocale(LC_CTYPE, '0'); // LC_MESSAGES does not exist on Win
104 $up = strtoupper($encoding);
105 $low = strtolower($encoding);
106 $lshort = strtr($up, '-','');
107 $ushort = strtr($low, '-','');
109 $test = setlocale(LC_ALL,
110 $lang_code.".".$encoding,
113 $lang_code.".".$ushort,
114 $lang_code.".".$lshort) !== false;
115 setlocale(LC_ALL, $old);
116 setlocale(LC_NUMERIC, 'C');
120 * Add a translation domain.
122 function add_domain($domain, $path=false, $version='')
127 $path = $this->domain_path;
133 // To avoid need for apache server restart after change of *.mo file
134 // we have to include file version as part of filename.
135 // This is alternative naming convention: $domain = $version.'/'.$domain;
136 $domain .= '-'.$version;
138 bindtextdomain($domain, $path);
139 //bind_textdomain_codeset($domain, $encoding);
144 * Retrieve translation for specified key.
148 function _get_translation($key)
150 return gettext($key);
155 * Reset interpolation variables.
159 $this->_interpolation_vars = array();
163 * Set an interpolation variable.
165 function set_var($key, $value)
167 $this->_interpolation_vars[$key] = $value;
171 * Set an associative array of interpolation variables.
173 function set_vars($hash)
175 $this->_interpolation_vars = array_merge($this->_interpolation_vars,
180 * Retrieve translation for specified key.
182 * @param string $key -- gettext msgid
183 * @throws GetText_Error
185 function gettext($key)
187 $value = $this->_get_translation($key);
188 if ($value === false) {
189 $str = sprintf('Unable to locate gettext key "%s"', $key);
190 return raise_error("2 " . $str);
193 while (preg_match('/\$\{(.*?)\}/sm', $value, $m)) {
194 list($src, $var) = $m;
196 // retrieve variable to interpolate in context, throw an exception
198 $var2 = $this->_get_var($var);
199 if ($var2 === false) {
200 $str = sprintf('Interpolation error, var "%s" not set', $var);
201 //$err = new GetText_Error($str);
202 //return PEAR::raise_error($err);
203 return raise_error("3 " . $str);
205 $value = str_replace($src, $var2, $value);
211 * Retrieve an interpolation variable value.
216 function _get_var($name)
218 if (!array_key_exists($name, $this->_interpolation_vars)) {
221 return $this->_interpolation_vars[$name];
227 * Implementation of get_text support for PHP.
229 * This implementation is abble to cache .po files into php files returning the
230 * domain translation hashtable.
233 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
235 class gettext_php_support extends gettext_native_support
237 var $_path = 'locale/';
238 var $_lang_code = false;
239 var $_domains = array();
241 var $_jobs = array();
244 * Set the translation domain.
246 * @param string $lang_code -- language code
247 * @throws GetText_Error
249 function set_language($lang_code, $encoding)
251 // if language already set, try to reload domains
252 if ($this->_lang_code !== false and $this->_lang_code != $lang_code)
254 foreach ($this->_domains as $domain)
256 $this->_jobs[] = array($domain->name, $domain->path);
258 $this->_domains = array();
262 $this->_lang_code = $lang_code;
264 // this allow us to set the language code after
266 while (count($this->_jobs) > 0)
268 list($domain, $path) = array_shift($this->_jobs);
269 $err = $this->add_domain($domain, $path);
270 // error raised, break jobs
278 * Check system support for given language (dummy).
280 function check_support($lang_code, $encoding)
285 * Add a translation domain.
287 * @param string $domain -- Domain name
288 * @param string $path optional -- Repository path
289 * @throws GetText_Error
291 function add_domain($domain, $path = false, $version ='')
294 $path = $this->domain_path;
299 $domain .= '-'.$version;
302 if (array_key_exists($domain, $this->_domains))
307 if (!$this->_lang_code)
309 $this->_jobs[] = array($domain, $path);
312 // Don't fill the domains with false data, it increased the error.log
313 if (strpos($domain, $this->_lang_code) === false)
316 $err = $this->_load_domain($domain, $path);
326 * Load a translation domain file.
328 * This method cache the translation hash into a php file unless
329 * GETTEXT_NO_CACHE is defined.
331 * @param string $domain -- Domain name
332 * @param string $path optional -- Repository
333 * @throws GetText_Error
336 function _load_domain($domain, $path = "./locale")
338 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
339 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
341 if (!file_exists($src_domain))
343 $str = sprintf('Domain file "%s" not found.', $src_domain);
344 return raise_error("4 " . $str);
347 $d = new gettext_domain();
350 if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain)))
353 // parse and compile translation table
354 $parser = new gettext_php_support_parser();
355 $hash = $parser->parse($src_domain);
356 if (!defined('GETTEXT_NO_CACHE'))
358 $comp = new gettext_php_support_compiler();
359 $err = $comp->compile($hash, $src_domain);
369 $d->_keys = include $php_domain;
371 $this->_domains[] = &$d;
375 * Implementation of gettext message retrieval.
377 function _get_translation($key)
379 for ($i = $this->_end; $i >= 0; $i--)
381 if ($this->_domains[$i]->has_key($key))
383 return $this->_domains[$i]->get($key);
391 * Class representing a domain file for a specified language.
394 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
401 var $_keys = array();
403 function has_key($key)
405 return array_key_exists($key, $this->_keys);
410 return $this->_keys[$key];
415 * This class is used to parse gettext '.po' files into php associative arrays.
418 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
420 class gettext_php_support_parser
422 var $_hash = array();
427 * Parse specified .po file.
430 * @throws GetText_Error
432 function parse($file)
434 $this->_hash = array();
435 $this->_current_key = false;
436 $this->_current_value = "";
438 if (!file_exists($file))
440 $str = sprintf('Unable to locate file "%s"', $file);
441 return raise_error($str);
444 $lines = file($file);
445 foreach ($lines as $line)
447 $this->_parse_line($line, ++$i);
459 function _parse_line($line, $nbr)
461 $line = str_replace("\\\"", "'", $line); // Should be inside preg_match, but I couldn't find the solution. This works.
462 if (preg_match('/^\s*?#/', $line)) { return; }
463 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
465 $this->_current_key = $m[1];
468 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
469 $this->_current_value .= $m[1];
472 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
473 $this->_current_value .= $m[1];
479 * Store last key/value pair into building hashtable.
483 function _store_key()
485 if ($this->_current_key === false) return;
486 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
487 $this->_hash[$this->_current_key] = $this->_current_value;
488 $this->_current_key = false;
489 $this->_current_value = "";
495 * This class write a php file from a gettext hashtable.
497 * The produced file return the translation hashtable on include.
499 * @throws GetText_Error
501 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
503 class gettext_php_support_compiler
506 * Write hash in an includable php file.
508 function compile(&$hash, $source_path)
510 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
511 $fp = @fopen($dest_path, "w");
514 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
515 return raise_error($str);
517 fwrite($fp, '<?php' . "\n");
518 fwrite($fp, 'return array(' . "\n");
519 foreach ($hash as $key => $value)
521 $key = str_replace("'", "\\'", $key);
522 $value = str_replace("'", "\\'", $value);
523 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
525 fwrite($fp, ');' . "\n");
531 Set current gettext domain path
533 function set_ext_domain($path='') {
534 global $path_to_root, $GetText;
535 static $domain_stack = array('');
537 if ($path) // save path on domain stack
538 array_unshift($domain_stack, $path);
541 array_shift($domain_stack);
542 $path = $domain_stack[0];
545 $lang_path = $path_to_root . ($path ? '/' : '') .$path.'/lang';
546 // ignore change when extension does not provide translation structure and test for valid gettext.
547 if (file_exists($lang_path) && isset($GetText))
548 $GetText->add_domain($_SESSION['language']->code,
549 $lang_path, $path ? '' : $_SESSION['language']->version);