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();
66 * Set gettext language code.
67 * @throws GetText_Error
69 function set_language($lang_code, $encoding)
71 putenv("LANG=$lang_code");
72 putenv("LC_ALL=$lang_code");
73 putenv("LANGUAGE=$lang_code");
75 //$set = setlocale(LC_ALL, "$lang_code");
76 //$set = setlocale(LC_ALL, "$encoding");
78 // cover a couple of country/encoding variants
79 $up = strtoupper($encoding);
80 $low = strtolower($encoding);
81 $lshort = strtr($up, '-','');
82 $ushort = strtr($low, '-','');
84 if ($lang_code == 'C')
85 $set = setlocale(LC_ALL,'C');
87 $set = setlocale(LC_ALL, $lang_code.".".$encoding,
88 $lang_code.".".$up, $lang_code.".".$low,
89 $lang_code.".".$ushort, $lang_code.".".$lshort);
91 setlocale(LC_NUMERIC, 'C'); // important for numeric presentation etc.
94 $str = sprintf('language code "%s", encoding "%s" not supported by your system',
95 $lang_code, $encoding);
96 //$err = new GetText_Error($str);
97 //return PEAR::raise_error($err);
98 return raise_error("1 " . $str);
103 * Check system support for given language nedded for gettext.
105 function check_support($lang_code, $encoding)
107 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
109 $old = setlocale(LC_CTYPE, '0'); // LC_MESSAGES does not exist on Win
110 $up = strtoupper($encoding);
111 $low = strtolower($encoding);
112 $lshort = strtr($up, '-','');
113 $ushort = strtr($low, '-','');
115 $test = setlocale(LC_ALL,
116 $lang_code.".".$encoding,
119 $lang_code.".".$ushort,
120 $lang_code.".".$lshort) !== false;
121 setlocale(LC_ALL, $old);
122 setlocale(LC_NUMERIC, 'C');
126 * Add a translation domain.
128 function add_domain($domain, $path=false, $version='')
131 $path = $this->domain_path;
137 // To avoid need for apache server restart after change of *.mo file
138 // we have to include file version as part of filename.
139 // This is alternative naming convention: $domain = $version.'/'.$domain;
140 $domain .= '-'.$version;
142 bindtextdomain($domain, $path);
143 //bind_textdomain_codeset($domain, $encoding);
148 * Retrieve translation for specified key.
152 function _get_translation($key)
154 return gettext($key);
159 * Reset interpolation variables.
163 $this->_interpolation_vars = array();
167 * Set an interpolation variable.
169 function set_var($key, $value)
171 $this->_interpolation_vars[$key] = $value;
175 * Set an associative array of interpolation variables.
177 function set_vars($hash)
179 $this->_interpolation_vars = array_merge($this->_interpolation_vars,
184 * Retrieve translation for specified key.
186 * @param string $key -- gettext msgid
187 * @throws GetText_Error
189 function gettext($key)
191 $value = $this->_get_translation($key);
192 if ($value === false) {
193 $str = sprintf('Unable to locate gettext key "%s"', $key);
194 //$err = new GetText_Error($str);
195 //return PEAR::raise_error($err);
196 return raise_error("2 " . $str);
199 while (preg_match('/\$\{(.*?)\}/sm', $value, $m)) {
200 list($src, $var) = $m;
202 // retrieve variable to interpolate in context, throw an exception
204 $var2 = $this->_get_var($var);
205 if ($var2 === false) {
206 $str = sprintf('Interpolation error, var "%s" not set', $var);
207 //$err = new GetText_Error($str);
208 //return PEAR::raise_error($err);
209 return raise_error("3 " . $str);
211 $value = str_replace($src, $var2, $value);
217 * Retrieve an interpolation variable value.
222 function _get_var($name)
224 if (!array_key_exists($name, $this->_interpolation_vars)) {
227 return $this->_interpolation_vars[$name];
233 * Implementation of get_text support for PHP.
235 * This implementation is abble to cache .po files into php files returning the
236 * domain translation hashtable.
239 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
241 class gettext_php_support extends gettext_native_support
243 var $_path = 'locale/';
244 var $_lang_code = false;
245 var $_domains = array();
247 var $_jobs = array();
250 * Set the translation domain.
252 * @param string $lang_code -- language code
253 * @throws GetText_Error
255 function set_language($lang_code, $encoding)
257 // if language already set, try to reload domains
258 if ($this->_lang_code !== false and $this->_lang_code != $lang_code)
260 foreach ($this->_domains as $domain)
262 $this->_jobs[] = array($domain->name, $domain->path);
264 $this->_domains = array();
268 $this->_lang_code = $lang_code;
270 // this allow us to set the language code after
272 while (count($this->_jobs) > 0)
274 list($domain, $path) = array_shift($this->_jobs);
275 $err = $this->add_domain($domain, $path);
276 // error raised, break jobs
277 /*if (PEAR::is_error($err)) {
287 * Check system support for given language (dummy).
289 function check_support($lang_code, $encoding)
294 * Add a translation domain.
296 * @param string $domain -- Domain name
297 * @param string $path optional -- Repository path
298 * @throws GetText_Error
300 function add_domain($domain, $path = false, $version ='')
303 $path = $this->domain_path;
308 $domain .= '-'.$version;
311 if (array_key_exists($domain, $this->_domains))
316 if (!$this->_lang_code)
318 $this->_jobs[] = array($domain, $path);
322 $err = $this->_load_domain($domain, $path);
332 * Load a translation domain file.
334 * This method cache the translation hash into a php file unless
335 * GETTEXT_NO_CACHE is defined.
337 * @param string $domain -- Domain name
338 * @param string $path optional -- Repository
339 * @throws GetText_Error
342 function _load_domain($domain, $path = "./locale")
344 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
345 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
347 if (!file_exists($src_domain))
349 $str = sprintf('Domain file "%s" not found.', $src_domain);
350 //$err = new GetText_Error($str);
351 //return PEAR::raise_error($err);
352 return raise_error("4 " . $str);
355 $d = new gettext_domain();
359 if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain)))
362 // parse and compile translation table
363 $parser = new gettext_php_support_parser();
364 $hash = $parser->parse($src_domain);
365 if (!defined('GETTEXT_NO_CACHE'))
367 $comp = new gettext_php_support_compiler();
368 $err = $comp->compile($hash, $src_domain);
369 /*if (PEAR::is_error($err)) {
381 $d->_keys = include $php_domain;
383 $this->_domains[] = &$d;
387 * Implementation of gettext message retrieval.
389 function _get_translation($key)
391 for ($i = $this->_end; $i >= 0; $i--)
393 if ($this->_domains[$i]->has_key($key))
395 return $this->_domains[$i]->get($key);
403 * Class representing a domain file for a specified language.
406 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
413 var $_keys = array();
415 function has_key($key)
417 return array_key_exists($key, $this->_keys);
422 return $this->_keys[$key];
427 * This class is used to parse gettext '.po' files into php associative arrays.
430 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
432 class gettext_php_support_parser
434 var $_hash = array();
439 * Parse specified .po file.
442 * @throws GetText_Error
444 function parse($file)
446 $this->_hash = array();
447 $this->_current_key = false;
448 $this->_current_value = "";
450 if (!file_exists($file))
452 $str = sprintf('Unable to locate file "%s"', $file);
453 //$err = new GetText_Error($str);
454 //return PEAR::raise_error($err);
455 return raise_error($str);
458 $lines = file($file);
459 foreach ($lines as $line)
461 $this->_parse_line($line, ++$i);
473 function _parse_line($line, $nbr)
475 if (preg_match('/^\s*?#/', $line)) { return; }
476 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
478 $this->_current_key = $m[1];
481 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
482 $this->_current_value .= $m[1];
485 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
486 $this->_current_value .= $m[1];
492 * Store last key/value pair into building hashtable.
496 function _store_key()
498 if ($this->_current_key === false) return;
499 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
500 $this->_hash[$this->_current_key] = $this->_current_value;
501 $this->_current_key = false;
502 $this->_current_value = "";
508 * This class write a php file from a gettext hashtable.
510 * The produced file return the translation hashtable on include.
512 * @throws GetText_Error
514 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
516 class gettext_php_support_compiler
519 * Write hash in an includable php file.
521 function compile(&$hash, $source_path)
523 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
524 $fp = @fopen($dest_path, "w");
527 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
528 //$err = new GetText_Error($str);
529 //return PEAR::raise_error($err);
530 return raise_error($str);
532 fwrite($fp, '<?php' . "\n");
533 fwrite($fp, 'return array(' . "\n");
534 foreach ($hash as $key => $value)
536 $key = str_replace("'", "\\'", $key);
537 $value = str_replace("'", "\\'", $value);
538 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
540 fwrite($fp, ');' . "\n");
547 Set current gettext domain path
549 function set_ext_domain($path='') {
550 global $path_to_root;
552 $lang_path = $path_to_root . ($path ? '/' : '') .$path.'/lang';
553 // ignore change when extension does not provide translation structure
554 if (file_exists($lang_path))
555 $_SESSION['get_text']->add_domain($_SESSION['language']->code,
556 $lang_path, $path ? '' : $_SESSION['language']->version);