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 if ($lang_code == 'C')
84 $set = setlocale(LC_ALL,'C');
86 $set = setlocale(LC_ALL, $lang_code.".".$encoding,
87 $lang_code.".".$up, $lang_code.".".$low,
88 $lang_code.".".$ushort, $lang_code.".".$lshort);
90 setlocale(LC_NUMERIC, 'C'); // important for numeric presentation etc.
93 $str = sprintf('language code "%s", encoding "%s" not supported by your system',
94 $lang_code, $encoding);
95 //$err = new GetText_Error($str);
96 //return PEAR::raise_error($err);
97 return raise_error("1 " . $str);
102 * Check system support for given language nedded for gettext.
104 function check_support($lang_code, $encoding)
107 $old = setlocale(LC_CTYPE, '0'); // LC_MESSAGES does not exist on Win
108 $up = strtoupper($encoding);
109 $low = strtolower($encoding);
110 $lshort = strtr($up, '-','');
111 $ushort = strtr($low, '-','');
113 $test = setlocale(LC_ALL,
114 $lang_code.".".$encoding,
117 $lang_code.".".$ushort,
118 $lang_code.".".$lshort) !== false;
119 setlocale(LC_ALL, $old);
120 setlocale(LC_NUMERIC, 'C');
124 * Add a translation domain.
126 function add_domain($domain, $path=false, $version='')
131 // To avoid need for apache server restart after change of *.mo file
132 // we have to include file version as part of filename.
133 // This is alternative naming convention: $domain = $version.'/'.$domain;
134 $domain .= '-'.$version;
136 bindtextdomain($domain, $path);
137 //bind_textdomain_codeset($domain, $encoding);
142 * Retrieve translation for specified key.
146 function _get_translation($key)
148 return gettext($key);
153 * Reset interpolation variables.
157 $this->_interpolation_vars = array();
161 * Set an interpolation variable.
163 function set_var($key, $value)
165 $this->_interpolation_vars[$key] = $value;
169 * Set an associative array of interpolation variables.
171 function set_vars($hash)
173 $this->_interpolation_vars = array_merge($this->_interpolation_vars,
178 * Retrieve translation for specified key.
180 * @param string $key -- gettext msgid
181 * @throws GetText_Error
183 function gettext($key)
185 $value = $this->_get_translation($key);
186 if ($value === false) {
187 $str = sprintf('Unable to locate gettext key "%s"', $key);
188 //$err = new GetText_Error($str);
189 //return PEAR::raise_error($err);
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
271 /*if (PEAR::is_error($err)) {
281 * Check system support for given language (dummy).
283 function check_support($lang_code, $encoding)
288 * Add a translation domain.
290 * @param string $domain -- Domain name
291 * @param string $path optional -- Repository path
292 * @throws GetText_Error
294 function add_domain($domain, $path = "./locale/", $version ='')
297 $domain .= '-'.$version;
300 if (array_key_exists($domain, $this->_domains))
305 if (!$this->_lang_code)
307 $this->_jobs[] = array($domain, $path);
311 $err = $this->_load_domain($domain, $path);
321 * Load a translation domain file.
323 * This method cache the translation hash into a php file unless
324 * GETTEXT_NO_CACHE is defined.
326 * @param string $domain -- Domain name
327 * @param string $path optional -- Repository
328 * @throws GetText_Error
331 function _load_domain($domain, $path = "./locale")
333 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
334 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
336 if (!file_exists($src_domain))
338 $str = sprintf('Domain file "%s" not found.', $src_domain);
339 //$err = new GetText_Error($str);
340 //return PEAR::raise_error($err);
341 return raise_error("4 " . $str);
344 $d = new gettext_domain();
348 if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain)))
351 // parse and compile translation table
352 $parser = new gettext_php_support_parser();
353 $hash = $parser->parse($src_domain);
354 if (!defined('GETTEXT_NO_CACHE'))
356 $comp = new gettext_php_support_compiler();
357 $err = $comp->compile($hash, $src_domain);
358 /*if (PEAR::is_error($err)) {
370 $d->_keys = include $php_domain;
372 $this->_domains[] = &$d;
376 * Implementation of gettext message retrieval.
378 function _get_translation($key)
380 for ($i = $this->_end; $i >= 0; $i--)
382 if ($this->_domains[$i]->has_key($key))
384 return $this->_domains[$i]->get($key);
392 * Class representing a domain file for a specified language.
395 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
402 var $_keys = array();
404 function has_key($key)
406 return array_key_exists($key, $this->_keys);
411 return $this->_keys[$key];
416 * This class is used to parse gettext '.po' files into php associative arrays.
419 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
421 class gettext_php_support_parser
423 var $_hash = array();
428 * Parse specified .po file.
431 * @throws GetText_Error
433 function parse($file)
435 $this->_hash = array();
436 $this->_current_key = false;
437 $this->_current_value = "";
439 if (!file_exists($file))
441 $str = sprintf('Unable to locate file "%s"', $file);
442 //$err = new GetText_Error($str);
443 //return PEAR::raise_error($err);
444 return raise_error($str);
447 $lines = file($file);
448 foreach ($lines as $line)
450 $this->_parse_line($line, ++$i);
462 function _parse_line($line, $nbr)
464 if (preg_match('/^\s*?#/', $line)) { return; }
465 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
467 $this->_current_key = $m[1];
470 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
471 $this->_current_value .= $m[1];
474 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
475 $this->_current_value .= $m[1];
481 * Store last key/value pair into building hashtable.
485 function _store_key()
487 if ($this->_current_key === false) return;
488 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
489 $this->_hash[$this->_current_key] = $this->_current_value;
490 $this->_current_key = false;
491 $this->_current_value = "";
497 * This class write a php file from a gettext hashtable.
499 * The produced file return the translation hashtable on include.
501 * @throws GetText_Error
503 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
505 class gettext_php_support_compiler
508 * Write hash in an includable php file.
510 function compile(&$hash, $source_path)
512 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
513 $fp = @fopen($dest_path, "w");
516 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
517 //$err = new GetText_Error($str);
518 //return PEAR::raise_error($err);
519 return raise_error($str);
521 fwrite($fp, '<?php' . "\n");
522 fwrite($fp, 'return array(' . "\n");
523 foreach ($hash as $key => $value)
525 $key = str_replace("'", "\\'", $key);
526 $value = str_replace("'", "\\'", $value);
527 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
529 fwrite($fp, ');' . "\n");
536 * get_text related error.
538 //class GetText_Error extends PEAR_Error {}