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='')
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 //$err = new GetText_Error($str);
191 //return PEAR::raise_error($err);
192 return raise_error("2 " . $str);
195 while (preg_match('/\$\{(.*?)\}/sm', $value, $m)) {
196 list($src, $var) = $m;
198 // retrieve variable to interpolate in context, throw an exception
200 $var2 = $this->_get_var($var);
201 if ($var2 === false) {
202 $str = sprintf('Interpolation error, var "%s" not set', $var);
203 //$err = new GetText_Error($str);
204 //return PEAR::raise_error($err);
205 return raise_error("3 " . $str);
207 $value = str_replace($src, $var2, $value);
213 * Retrieve an interpolation variable value.
218 function _get_var($name)
220 if (!array_key_exists($name, $this->_interpolation_vars)) {
223 return $this->_interpolation_vars[$name];
229 * Implementation of get_text support for PHP.
231 * This implementation is abble to cache .po files into php files returning the
232 * domain translation hashtable.
235 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
237 class gettext_php_support extends gettext_native_support
239 var $_path = 'locale/';
240 var $_lang_code = false;
241 var $_domains = array();
243 var $_jobs = array();
246 * Set the translation domain.
248 * @param string $lang_code -- language code
249 * @throws GetText_Error
251 function set_language($lang_code, $encoding)
253 // if language already set, try to reload domains
254 if ($this->_lang_code !== false and $this->_lang_code != $lang_code)
256 foreach ($this->_domains as $domain)
258 $this->_jobs[] = array($domain->name, $domain->path);
260 $this->_domains = array();
264 $this->_lang_code = $lang_code;
266 // this allow us to set the language code after
268 while (count($this->_jobs) > 0)
270 list($domain, $path) = array_shift($this->_jobs);
271 $err = $this->add_domain($domain, $path);
272 // error raised, break jobs
273 /*if (PEAR::is_error($err)) {
283 * Check system support for given language (dummy).
285 function check_support($lang_code, $encoding)
290 * Add a translation domain.
292 * @param string $domain -- Domain name
293 * @param string $path optional -- Repository path
294 * @throws GetText_Error
296 function add_domain($domain, $path = "./locale/", $version ='')
299 $domain .= '-'.$version;
302 if (array_key_exists($domain, $this->_domains))
307 if (!$this->_lang_code)
309 $this->_jobs[] = array($domain, $path);
313 $err = $this->_load_domain($domain, $path);
323 * Load a translation domain file.
325 * This method cache the translation hash into a php file unless
326 * GETTEXT_NO_CACHE is defined.
328 * @param string $domain -- Domain name
329 * @param string $path optional -- Repository
330 * @throws GetText_Error
333 function _load_domain($domain, $path = "./locale")
335 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
336 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
338 if (!file_exists($src_domain))
340 $str = sprintf('Domain file "%s" not found.', $src_domain);
341 //$err = new GetText_Error($str);
342 //return PEAR::raise_error($err);
343 return raise_error("4 " . $str);
346 $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);
360 /*if (PEAR::is_error($err)) {
372 $d->_keys = include $php_domain;
374 $this->_domains[] = &$d;
378 * Implementation of gettext message retrieval.
380 function _get_translation($key)
382 for ($i = $this->_end; $i >= 0; $i--)
384 if ($this->_domains[$i]->has_key($key))
386 return $this->_domains[$i]->get($key);
394 * Class representing a domain file for a specified language.
397 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
404 var $_keys = array();
406 function has_key($key)
408 return array_key_exists($key, $this->_keys);
413 return $this->_keys[$key];
418 * This class is used to parse gettext '.po' files into php associative arrays.
421 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
423 class gettext_php_support_parser
425 var $_hash = array();
430 * Parse specified .po file.
433 * @throws GetText_Error
435 function parse($file)
437 $this->_hash = array();
438 $this->_current_key = false;
439 $this->_current_value = "";
441 if (!file_exists($file))
443 $str = sprintf('Unable to locate file "%s"', $file);
444 //$err = new GetText_Error($str);
445 //return PEAR::raise_error($err);
446 return raise_error($str);
449 $lines = file($file);
450 foreach ($lines as $line)
452 $this->_parse_line($line, ++$i);
464 function _parse_line($line, $nbr)
466 if (preg_match('/^\s*?#/', $line)) { return; }
467 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
469 $this->_current_key = $m[1];
472 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
473 $this->_current_value .= $m[1];
476 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
477 $this->_current_value .= $m[1];
483 * Store last key/value pair into building hashtable.
487 function _store_key()
489 if ($this->_current_key === false) return;
490 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
491 $this->_hash[$this->_current_key] = $this->_current_value;
492 $this->_current_key = false;
493 $this->_current_value = "";
499 * This class write a php file from a gettext hashtable.
501 * The produced file return the translation hashtable on include.
503 * @throws GetText_Error
505 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
507 class gettext_php_support_compiler
510 * Write hash in an includable php file.
512 function compile(&$hash, $source_path)
514 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
515 $fp = @fopen($dest_path, "w");
518 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
519 //$err = new GetText_Error($str);
520 //return PEAR::raise_error($err);
521 return raise_error($str);
523 fwrite($fp, '<?php' . "\n");
524 fwrite($fp, 'return array(' . "\n");
525 foreach ($hash as $key => $value)
527 $key = str_replace("'", "\\'", $key);
528 $value = str_replace("'", "\\'", $value);
529 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
531 fwrite($fp, ');' . "\n");
538 * get_text related error.
540 //class GetText_Error extends PEAR_Error {}