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($GetText)) {
32 if ($managerType == GETTEXT_NATIVE)
34 if (function_exists('gettext'))
36 $GetText = new gettext_native_support();
40 // fail back to php support
41 $GetText = 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);
323 // Don't fill the domains with false data, it increased the error.log
324 if (strpos($domain, $this->_lang_code) === false)
327 $err = $this->_load_domain($domain, $path);
337 * Load a translation domain file.
339 * This method cache the translation hash into a php file unless
340 * GETTEXT_NO_CACHE is defined.
342 * @param string $domain -- Domain name
343 * @param string $path optional -- Repository
344 * @throws GetText_Error
347 function _load_domain($domain, $path = "./locale")
349 $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
350 $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
352 if (!file_exists($src_domain))
354 $str = sprintf('Domain file "%s" not found.', $src_domain);
355 //$err = new GetText_Error($str);
356 //return PEAR::raise_error($err);
357 return raise_error("4 " . $str);
360 $d = new gettext_domain();
363 if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain)))
366 // parse and compile translation table
367 $parser = new gettext_php_support_parser();
368 $hash = $parser->parse($src_domain);
369 if (!defined('GETTEXT_NO_CACHE'))
371 $comp = new gettext_php_support_compiler();
372 $err = $comp->compile($hash, $src_domain);
373 /*if (PEAR::is_error($err)) {
385 $d->_keys = include $php_domain;
387 $this->_domains[] = &$d;
391 * Implementation of gettext message retrieval.
393 function _get_translation($key)
395 for ($i = $this->_end; $i >= 0; $i--)
397 if ($this->_domains[$i]->has_key($key))
399 return $this->_domains[$i]->get($key);
407 * Class representing a domain file for a specified language.
410 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
417 var $_keys = array();
419 function has_key($key)
421 return array_key_exists($key, $this->_keys);
426 return $this->_keys[$key];
431 * This class is used to parse gettext '.po' files into php associative arrays.
434 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
436 class gettext_php_support_parser
438 var $_hash = array();
443 * Parse specified .po file.
446 * @throws GetText_Error
448 function parse($file)
450 $this->_hash = array();
451 $this->_current_key = false;
452 $this->_current_value = "";
454 if (!file_exists($file))
456 $str = sprintf('Unable to locate file "%s"', $file);
457 //$err = new GetText_Error($str);
458 //return PEAR::raise_error($err);
459 return raise_error($str);
462 $lines = file($file);
463 foreach ($lines as $line)
465 $this->_parse_line($line, ++$i);
477 function _parse_line($line, $nbr)
479 $line = str_replace("\\\"", "'", $line); // Should be inside preg_match, but I couldn't find the solution. This works.
480 if (preg_match('/^\s*?#/', $line)) { return; }
481 if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
483 $this->_current_key = $m[1];
486 if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
487 $this->_current_value .= $m[1];
490 if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
491 $this->_current_value .= $m[1];
497 * Store last key/value pair into building hashtable.
501 function _store_key()
503 if ($this->_current_key === false) return;
504 $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
505 $this->_hash[$this->_current_key] = $this->_current_value;
506 $this->_current_key = false;
507 $this->_current_value = "";
513 * This class write a php file from a gettext hashtable.
515 * The produced file return the translation hashtable on include.
517 * @throws GetText_Error
519 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
521 class gettext_php_support_compiler
524 * Write hash in an includable php file.
526 function compile(&$hash, $source_path)
528 $dest_path = preg_replace('/\.po$/', '.php', $source_path);
529 $fp = @fopen($dest_path, "w");
532 $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
533 //$err = new GetText_Error($str);
534 //return PEAR::raise_error($err);
535 return raise_error($str);
537 fwrite($fp, '<?php' . "\n");
538 fwrite($fp, 'return array(' . "\n");
539 foreach ($hash as $key => $value)
541 $key = str_replace("'", "\\'", $key);
542 $value = str_replace("'", "\\'", $value);
543 fwrite($fp, ' \'' . $key . '\' => \'' . $value . "',\n");
545 fwrite($fp, ');' . "\n");
552 Set current gettext domain path
554 function set_ext_domain($path='') {
555 global $path_to_root, $GetText;
556 static $domain_stack = array('');
558 if ($path) // save path on domain stack
559 array_unshift($domain_stack, $path);
562 array_shift($domain_stack);
563 $path = $domain_stack[0];
566 $lang_path = $path_to_root . ($path ? '/' : '') .$path.'/lang';
567 // ignore change when extension does not provide translation structure and test for valid gettext.
568 if (file_exists($lang_path) && isset($GetText))
569 $GetText->add_domain($_SESSION['language']->code,
570 $lang_path, $path ? '' : $_SESSION['language']->version);