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 //require_once "PEAR.php";
25 define('GETTEXT_NATIVE', 1);
26 define('GETTEXT_PHP', 2);
28 function get_text_init($managerType = GETTEXT_NATIVE) {
30 if (!isset($_SESSION['get_text'])) {
32 if ($managerType == GETTEXT_NATIVE)
34 if (function_exists('gettext'))
36 $_SESSION['get_text'] = new gettext_native_support();
40 // fail back to php support
41 $_SESSION['get_text'] = new gettext_php_support();
45 function raise_error($str) {
50 function is_error($err) {
55 * Interface to gettext native support.
57 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
60 class gettext_native_support
62 var $_interpolation_vars = array();
65 * Set gettext language code.
66 * @throws GetText_Error
68 function set_language($lang_code, $encoding)
70 putenv("LANG=$lang_code");
71 putenv("LC_ALL=$lang_code");
72 putenv("LANGUAGE=$lang_code");
74 //$set = setlocale(LC_ALL, "$lang_code");
75 //$set = setlocale(LC_ALL, "$encoding");
77 // cover a couple of country/encoding variants
78 $up = strtoupper($encoding);
79 $low = strtolower($encoding);
80 $lshort = strtr($up, '-','');
81 $ushort = strtr($low, '-','');
83 $set = setlocale(LC_ALL, $lang_code.".".$encoding,
84 $lang_code.".".$up, $lang_code.".".$low,
85 $lang_code.".".$ushort, $lang_code.".".$lshort);
87 setlocale(LC_NUMERIC, 'C'); // important for numeric presentation etc.
90 $str = sprintf('language code "%s", encoding "%s" not supported by your system',
91 $lang_code, $encoding);
92 //$err = new GetText_Error($str);
93 //return PEAR::raise_error($err);
94 return raise_error("1 " . $str);
99 * Check system support for given language nedded for gettext.
101 function check_support($lang_code, $encoding)
104 $old = setlocale(LC_CTYPE, '0'); // LC_MESSAGES does not exist on Win
105 $up = strtoupper($encoding);
106 $low = strtolower($encoding);
107 $lshort = strtr($up, '-','');
108 $ushort = strtr($low, '-','');
110 $test = setlocale(LC_ALL,
111 $lang_code.".".$encoding,
114 $lang_code.".".$ushort,
115 $lang_code.".".$lshort) !== false;
116 setlocale(LC_ALL, $old);
117 setlocale(LC_NUMERIC, 'C');
121 * Add a translation domain.
123 function add_domain($domain, $path=false, $version='')
128 // To avoid need for apache server restart after change of *.mo file
129 // we have to include file version as part of filename.
130 // This is alternative naming convention: $domain = $version.'/'.$domain;
131 $domain .= '-'.$version;
133 bindtextdomain($domain, $path);
134 //bind_textdomain_codeset($domain, $encoding);
139 * Retrieve translation for specified key.
143 function _get_translation($key)
145 return gettext($key);
150 * Reset interpolation variables.
154 $this->_interpolation_vars = array();
158 * Set an interpolation variable.
160 function set_var($key, $value)
162 $this->_interpolation_vars[$key] = $value;
166 * Set an associative array of interpolation variables.
168 function set_vars($hash)
170 $this->_interpolation_vars = array_merge($this->_interpolation_vars,
175 * Retrieve translation for specified key.
177 * @param string $key -- gettext msgid
178 * @throws GetText_Error
180 function gettext($key)
182 $value = $this->_get_translation($key);
183 if ($value === false) {
184 $str = sprintf('Unable to locate gettext key "%s"', $key);
185 //$err = new GetText_Error($str);
186 //return PEAR::raise_error($err);
187 return raise_error("2 " . $str);
190 while (preg_match('/\$\{(.*?)\}/sm', $value, $m)) {
191 list($src, $var) = $m;
193 // retrieve variable to interpolate in context, throw an exception
195 $var2 = $this->_get_var($var);
196 if ($var2 === false) {
197 $str = sprintf('Interpolation error, var "%s" not set', $var);
198 //$err = new GetText_Error($str);
199 //return PEAR::raise_error($err);
200 return raise_error("3 " . $str);
202 $value = str_replace($src, $var2, $value);
208 * Retrieve an interpolation variable value.
213 function _get_var($name)
215 if (!array_key_exists($name, $this->_interpolation_vars)) {
218 return $this->_interpolation_vars[$name];
224 * Implementation of get_text support for PHP.
226 * This implementation is abble to cache .po files into php files returning the
227 * domain translation hashtable.
230 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
232 class gettext_php_support extends gettext_native_support
234 var $_path = 'locale/';
235 var $_lang_code = false;
236 var $_domains = array();
238 var $_jobs = array();
241 * Set the translation domain.
243 * @param string $lang_code -- language code
244 * @throws GetText_Error
246 function set_language($lang_code, $encoding)
248 // if language already set, try to reload domains
249 if ($this->_lang_code !== false and $this->_lang_code != $lang_code)
251 foreach ($this->_domains as $domain)
253 $this->_jobs[] = array($domain->name, $domain->path);
255 $this->_domains = array();
259 $this->_lang_code = $lang_code;
261 // this allow us to set the language code after
263 while (count($this->_jobs) > 0)
265 list($domain, $path) = array_shift($this->_jobs);
266 $err = $this->add_domain($domain, $path);
267 // error raised, break jobs
268 /*if (PEAR::is_error($err)) {
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 = "./locale/", $version ='')
294 $domain .= '-'.$version;
297 if (array_key_exists($domain, $this->_domains))
302 if (!$this->_lang_code)
304 $this->_jobs[] = array($domain, $path);
308 $err = $this->_load_domain($domain, $path);
318 * Load a translation domain file.
320 * This method cache the translation hash into a php file unless
321 * GETTEXT_NO_CACHE is defined.
323 * @param string $domain -- Domain name
324 * @param string $path optional -- Repository
325 * @throws GetText_Error
328 function _load_domain($domain, $path = "./locale")
330 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
331 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
333 if (!file_exists($src_domain))
335 $str = sprintf('Domain file "%s" not found.', $src_domain);
336 //$err = new GetText_Error($str);
337 //return PEAR::raise_error($err);
338 return raise_error("4 " . $str);
341 $d = new gettext_domain();
345 if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain)))
348 // parse and compile translation table
349 $parser = new gettext_php_support_parser();
350 $hash = $parser->parse($src_domain);
351 if (!defined('GETTEXT_NO_CACHE'))
353 $comp = new gettext_php_support_compiler();
354 $err = $comp->compile($hash, $src_domain);
355 /*if (PEAR::is_error($err)) {
367 $d->_keys = include $php_domain;
369 $this->_domains[] = &$d;
373 * Implementation of gettext message retrieval.
375 function _get_translation($key)
377 for ($i = $this->_end; $i >= 0; $i--)
379 if ($this->_domains[$i]->has_key($key))
381 return $this->_domains[$i]->get($key);
389 * Class representing a domain file for a specified language.
392 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
399 var $_keys = array();
401 function has_key($key)
403 return array_key_exists($key, $this->_keys);
408 return $this->_keys[$key];
413 * This class is used to parse gettext '.po' files into php associative arrays.
416 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
418 class gettext_php_support_parser
420 var $_hash = array();
425 * Parse specified .po file.
428 * @throws GetText_Error
430 function parse($file)
432 $this->_hash = array();
433 $this->_current_key = false;
434 $this->_current_value = "";
436 if (!file_exists($file))
438 $str = sprintf('Unable to locate file "%s"', $file);
439 //$err = new GetText_Error($str);
440 //return PEAR::raise_error($err);
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 if (preg_match('/^\s*?#/', $line)) { return; }
462 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
464 $this->_current_key = $m[1];
467 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
468 $this->_current_value .= $m[1];
471 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
472 $this->_current_value .= $m[1];
478 * Store last key/value pair into building hashtable.
482 function _store_key()
484 if ($this->_current_key === false) return;
485 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
486 $this->_hash[$this->_current_key] = $this->_current_value;
487 $this->_current_key = false;
488 $this->_current_value = "";
494 * This class write a php file from a gettext hashtable.
496 * The produced file return the translation hashtable on include.
498 * @throws GetText_Error
500 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
502 class gettext_php_support_compiler
505 * Write hash in an includable php file.
507 function compile(&$hash, $source_path)
509 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
510 $fp = @fopen($dest_path, "w");
513 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
514 //$err = new GetText_Error($str);
515 //return PEAR::raise_error($err);
516 return raise_error($str);
518 fwrite($fp, '<?php' . "\n");
519 fwrite($fp, 'return array(' . "\n");
520 foreach ($hash as $key => $value)
522 $key = str_replace("'", "\\'", $key);
523 $value = str_replace("'", "\\'", $value);
524 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
526 fwrite($fp, ');' . "\n");
533 * get_text related error.
535 //class GetText_Error extends PEAR_Error {}