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 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
96 $str = sprintf('language code "%s", encoding "%s" not supported by your system',
97 $lang_code, $encoding);
98 //$err = new GetText_Error($str);
99 //return PEAR::raise_error($err);
100 return raise_error("1 " . $str);
105 * Check system support for given language nedded for gettext.
107 function check_support($lang_code, $encoding)
109 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
111 $old = setlocale(LC_CTYPE, '0'); // LC_MESSAGES does not exist on Win
112 $up = strtoupper($encoding);
113 $low = strtolower($encoding);
114 $lshort = strtr($up, '-','');
115 $ushort = strtr($low, '-','');
117 $test = setlocale(LC_ALL,
118 $lang_code.".".$encoding,
121 $lang_code.".".$ushort,
122 $lang_code.".".$lshort) !== false;
123 setlocale(LC_ALL, $old);
124 setlocale(LC_NUMERIC, 'C');
128 * Add a translation domain.
130 function add_domain($domain, $path=false, $version='')
133 $path = $this->domain_path;
139 // To avoid need for apache server restart after change of *.mo file
140 // we have to include file version as part of filename.
141 // This is alternative naming convention: $domain = $version.'/'.$domain;
142 $domain .= '-'.$version;
144 bindtextdomain($domain, $path);
145 //bind_textdomain_codeset($domain, $encoding);
150 * Retrieve translation for specified key.
154 function _get_translation($key)
156 return gettext($key);
161 * Reset interpolation variables.
165 $this->_interpolation_vars = array();
169 * Set an interpolation variable.
171 function set_var($key, $value)
173 $this->_interpolation_vars[$key] = $value;
177 * Set an associative array of interpolation variables.
179 function set_vars($hash)
181 $this->_interpolation_vars = array_merge($this->_interpolation_vars,
186 * Retrieve translation for specified key.
188 * @param string $key -- gettext msgid
189 * @throws GetText_Error
191 function gettext($key)
193 $value = $this->_get_translation($key);
194 if ($value === false) {
195 $str = sprintf('Unable to locate gettext key "%s"', $key);
196 //$err = new GetText_Error($str);
197 //return PEAR::raise_error($err);
198 return raise_error("2 " . $str);
201 while (preg_match('/\$\{(.*?)\}/sm', $value, $m)) {
202 list($src, $var) = $m;
204 // retrieve variable to interpolate in context, throw an exception
206 $var2 = $this->_get_var($var);
207 if ($var2 === false) {
208 $str = sprintf('Interpolation error, var "%s" not set', $var);
209 //$err = new GetText_Error($str);
210 //return PEAR::raise_error($err);
211 return raise_error("3 " . $str);
213 $value = str_replace($src, $var2, $value);
219 * Retrieve an interpolation variable value.
224 function _get_var($name)
226 if (!array_key_exists($name, $this->_interpolation_vars)) {
229 return $this->_interpolation_vars[$name];
235 * Implementation of get_text support for PHP.
237 * This implementation is abble to cache .po files into php files returning the
238 * domain translation hashtable.
241 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
243 class gettext_php_support extends gettext_native_support
245 var $_path = 'locale/';
246 var $_lang_code = false;
247 var $_domains = array();
249 var $_jobs = array();
252 * Set the translation domain.
254 * @param string $lang_code -- language code
255 * @throws GetText_Error
257 function set_language($lang_code, $encoding)
259 // if language already set, try to reload domains
260 if ($this->_lang_code !== false and $this->_lang_code != $lang_code)
262 foreach ($this->_domains as $domain)
264 $this->_jobs[] = array($domain->name, $domain->path);
266 $this->_domains = array();
270 $this->_lang_code = $lang_code;
272 // this allow us to set the language code after
274 while (count($this->_jobs) > 0)
276 list($domain, $path) = array_shift($this->_jobs);
277 $err = $this->add_domain($domain, $path);
278 // error raised, break jobs
279 /*if (PEAR::is_error($err)) {
289 * Check system support for given language (dummy).
291 function check_support($lang_code, $encoding)
296 * Add a translation domain.
298 * @param string $domain -- Domain name
299 * @param string $path optional -- Repository path
300 * @throws GetText_Error
302 function add_domain($domain, $path = false, $version ='')
305 $path = $this->domain_path;
310 $domain .= '-'.$version;
313 if (array_key_exists($domain, $this->_domains))
318 if (!$this->_lang_code)
320 $this->_jobs[] = array($domain, $path);
324 $err = $this->_load_domain($domain, $path);
334 * Load a translation domain file.
336 * This method cache the translation hash into a php file unless
337 * GETTEXT_NO_CACHE is defined.
339 * @param string $domain -- Domain name
340 * @param string $path optional -- Repository
341 * @throws GetText_Error
344 function _load_domain($domain, $path = "./locale")
346 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
347 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
349 if (!file_exists($src_domain))
351 $str = sprintf('Domain file "%s" not found.', $src_domain);
352 //$err = new GetText_Error($str);
353 //return PEAR::raise_error($err);
354 return raise_error("4 " . $str);
357 $d = new gettext_domain();
361 if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain)))
364 // parse and compile translation table
365 $parser = new gettext_php_support_parser();
366 $hash = $parser->parse($src_domain);
367 if (!defined('GETTEXT_NO_CACHE'))
369 $comp = new gettext_php_support_compiler();
370 $err = $comp->compile($hash, $src_domain);
371 /*if (PEAR::is_error($err)) {
383 $d->_keys = include $php_domain;
385 $this->_domains[] = &$d;
389 * Implementation of gettext message retrieval.
391 function _get_translation($key)
393 for ($i = $this->_end; $i >= 0; $i--)
395 if ($this->_domains[$i]->has_key($key))
397 return $this->_domains[$i]->get($key);
405 * Class representing a domain file for a specified language.
408 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
415 var $_keys = array();
417 function has_key($key)
419 return array_key_exists($key, $this->_keys);
424 return $this->_keys[$key];
429 * This class is used to parse gettext '.po' files into php associative arrays.
432 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
434 class gettext_php_support_parser
436 var $_hash = array();
441 * Parse specified .po file.
444 * @throws GetText_Error
446 function parse($file)
448 $this->_hash = array();
449 $this->_current_key = false;
450 $this->_current_value = "";
452 if (!file_exists($file))
454 $str = sprintf('Unable to locate file "%s"', $file);
455 //$err = new GetText_Error($str);
456 //return PEAR::raise_error($err);
457 return raise_error($str);
460 $lines = file($file);
461 foreach ($lines as $line)
463 $this->_parse_line($line, ++$i);
475 function _parse_line($line, $nbr)
477 if (preg_match('/^\s*?#/', $line)) { return; }
478 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
480 $this->_current_key = $m[1];
483 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
484 $this->_current_value .= $m[1];
487 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
488 $this->_current_value .= $m[1];
494 * Store last key/value pair into building hashtable.
498 function _store_key()
500 if ($this->_current_key === false) return;
501 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
502 $this->_hash[$this->_current_key] = $this->_current_value;
503 $this->_current_key = false;
504 $this->_current_value = "";
510 * This class write a php file from a gettext hashtable.
512 * The produced file return the translation hashtable on include.
514 * @throws GetText_Error
516 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
518 class gettext_php_support_compiler
521 * Write hash in an includable php file.
523 function compile(&$hash, $source_path)
525 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
526 $fp = @fopen($dest_path, "w");
529 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
530 //$err = new GetText_Error($str);
531 //return PEAR::raise_error($err);
532 return raise_error($str);
534 fwrite($fp, '<?php' . "\n");
535 fwrite($fp, 'return array(' . "\n");
536 foreach ($hash as $key => $value)
538 $key = str_replace("'", "\\'", $key);
539 $value = str_replace("'", "\\'", $value);
540 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
542 fwrite($fp, ');' . "\n");
549 Set current gettext domain path
551 function set_ext_domain($path='') {
552 global $path_to_root;
553 static $domain_stack = array('');
555 if ($path) // save path on domain stack
556 array_unshift($domain_stack, $path);
559 array_shift($domain_stack);
560 $path = $domain_stack[0];
562 $lang_path = $path_to_root . ($path ? '/' : '') .$path.'/lang';
565 $lang_path = $path_to_root . ($path ? '/' : '') .$path.'/lang';
566 // ignore change when extension does not provide translation structure
567 if (file_exists($lang_path))
568 $_SESSION['get_text']->add_domain($_SESSION['language']->code,
569 $lang_path, $path ? '' : $_SESSION['language']->version);