9f1a8381739f3cd9203784cab32f234a0b2c0598
[fa-stable.git] / includes / lang / gettext.inc
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 //  
4 //  Copyright (c) 2003 Laurent Bedubourg
5 //  
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.
10 //  
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.
15 //  
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
19 //  
20 //  Authors: Laurent Bedubourg <laurent.bedubourg@free.fr>
21 //  
22
23 define('GETTEXT_NATIVE', 1);
24 define('GETTEXT_PHP', 2);
25
26 function get_text_init($managerType = GETTEXT_NATIVE) {
27         global $GetText;
28         if (!isset($GetText)) {
29
30         if ($managerType == GETTEXT_NATIVE) 
31         {
32             if (function_exists('gettext')) 
33             {
34                 $GetText = new gettext_native_support();
35                 return;
36             }
37         }
38         // fail back to php support 
39                 $GetText = new gettext_php_support();
40         }
41 }
42
43 function raise_error($str) {
44         error_log($str);
45         return 1;
46 }
47
48 function is_error($err) {
49     return $err > 0;
50 }
51
52 /**
53 * Interface to gettext native support.
54 *
55 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
56 * @access private
57 */
58 class gettext_native_support 
59 {
60     var $_interpolation_vars = array();
61     var $domain_path;
62
63     /**
64      * Set gettext language code.
65      * @throws GetText_Error
66      */
67     function set_language($lang_code, $encoding)
68     {
69         putenv("LANG=$lang_code");
70         putenv("LC_ALL=$lang_code");
71         putenv("LANGUAGE=$lang_code");
72
73                 // cover a couple of country/encoding variants 
74                 $up = strtoupper($encoding);
75                 $low = strtolower($encoding);
76                 $lshort = strtr($up, '-','');
77                 $ushort = strtr($low, '-','');
78
79                 if ($lang_code == 'C')
80                         $set = setlocale(LC_ALL,'C');
81                 else
82                 $set = setlocale(LC_ALL, $lang_code.".".$encoding, 
83                                 $lang_code.".".$up, $lang_code.".".$low,
84                                 $lang_code.".".$ushort, $lang_code.".".$lshort);
85
86         setlocale(LC_NUMERIC, 'C'); // important for numeric presentation etc.
87         if ($set === false) 
88         {
89                         if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
90                                 return 0;
91             $str = sprintf('language code "%s", encoding "%s" not supported by your system',
92                 $lang_code, $encoding);
93                         return raise_error("1 " . $str);
94         }
95     }
96     /**
97          *      Check system support for given language nedded for gettext.
98          */
99         function check_support($lang_code, $encoding)
100     {
101                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') // don't do this test if server is WIN
102                         return true;
103                 $old = setlocale(LC_CTYPE, '0'); // LC_MESSAGES does not exist on Win
104                 $up = strtoupper($encoding);
105                 $low = strtolower($encoding);
106                 $lshort = strtr($up, '-','');
107                 $ushort = strtr($low, '-','');
108
109         $test = setlocale(LC_ALL,
110                         $lang_code.".".$encoding, 
111                         $lang_code.".".$up,
112                         $lang_code.".".$low,
113                         $lang_code.".".$ushort,
114                         $lang_code.".".$lshort) !== false;
115                 setlocale(LC_ALL, $old);
116                 setlocale(LC_NUMERIC, 'C');
117                 return $test;
118         }
119     /**
120      * Add a translation domain.
121      */
122     function add_domain($domain, $path=false, $version='')
123     {
124         if ($path === false) 
125                 $path = $this->domain_path;
126         if ($path === false) 
127                 $path = "./locale";
128             if ($domain == "")
129                 $domain = "?";
130                 if ($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;
135                 }
136         bindtextdomain($domain, $path);
137         //bind_textdomain_codeset($domain, $encoding);
138         textdomain($domain);
139     }
140
141     /**
142      * Retrieve translation for specified key.
143      *
144      * @access private
145      */
146     function _get_translation($key)
147     {
148         return gettext($key);
149     }
150     
151
152     /**
153      * Reset interpolation variables.
154      */
155     function reset()
156     {
157         $this->_interpolation_vars = array();
158     }
159     
160     /**
161      * Set an interpolation variable.
162      */
163     function set_var($key, $value)
164     {
165         $this->_interpolation_vars[$key] = $value;
166     }
167
168     /**
169      * Set an associative array of interpolation variables.
170      */
171     function set_vars($hash)
172     {
173         $this->_interpolation_vars = array_merge($this->_interpolation_vars,
174                                                 $hash);
175     }
176     
177     /**
178      * Retrieve translation for specified key.
179      *
180      * @param  string $key  -- gettext msgid
181      * @throws GetText_Error
182      */
183     function gettext($key)
184     {
185         $value = $this->_get_translation($key);
186         if ($value === false) {
187             $str = sprintf('Unable to locate gettext key "%s"', $key);
188                         return raise_error("2 " . $str);
189         }
190         
191         while (preg_match('/\$\{(.*?)\}/sm', $value, $m)) {
192             list($src, $var) = $m;
193
194             // retrieve variable to interpolate in context, throw an exception
195             // if not found.
196             $var2 = $this->_get_var($var);
197             if ($var2 === false) {
198                 $str = sprintf('Interpolation error, var "%s" not set', $var);
199                 //$err = new GetText_Error($str);
200                 //return PEAR::raise_error($err);
201                 return raise_error("3 " . $str);
202             }
203             $value = str_replace($src, $var2, $value);
204         }
205         return $value;
206     }
207
208     /**
209      * Retrieve an interpolation variable value.
210      * 
211      * @return mixed
212      * @access private
213      */
214     function _get_var($name)
215     {
216         if (!array_key_exists($name, $this->_interpolation_vars)) {
217             return false;
218         }
219         return $this->_interpolation_vars[$name];
220     }
221 }
222
223
224 /**
225 * Implementation of get_text support for PHP.
226 *
227 * This implementation is abble to cache .po files into php files returning the
228 * domain translation hashtable.
229 *
230 * @access private
231 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
232 */
233 class gettext_php_support extends gettext_native_support
234 {
235     var $_path     = 'locale/';
236     var $_lang_code = false;
237     var $_domains  = array();
238     var $_end      = -1;
239     var $_jobs     = array();
240
241     /**
242      * Set the translation domain.
243      *
244      * @param  string $lang_code -- language code
245      * @throws GetText_Error
246      */
247     function set_language($lang_code, $encoding)
248     {
249         // if language already set, try to reload domains
250         if ($this->_lang_code !== false and $this->_lang_code != $lang_code) 
251         {
252             foreach ($this->_domains as $domain) 
253             {
254                 $this->_jobs[] = array($domain->name, $domain->path);
255             }
256             $this->_domains = array();
257             $this->_end = -1;
258         }
259         
260         $this->_lang_code = $lang_code;
261
262         // this allow us to set the language code after 
263         // domain list.
264         while (count($this->_jobs) > 0) 
265         {
266             list($domain, $path) = array_shift($this->_jobs);
267             $err = $this->add_domain($domain, $path);
268             // error raised, break jobs
269                         if (is_error($err)) 
270                         {
271                 return $err;
272             }            
273         }
274     }
275     /**
276          *      Check system support for given language (dummy).
277          */
278         function check_support($lang_code, $encoding)
279     {
280                 return true;
281     }
282     /**
283      * Add a translation domain.
284      *
285      * @param string $domain        -- Domain name
286      * @param string $path optional -- Repository path
287      * @throws GetText_Error
288      */
289     function add_domain($domain, $path = false, $version ='')
290     {   
291         if ($path === false) 
292               $path = $this->domain_path;
293         if ($path === false) 
294                 $path = "./locale";
295
296         if ($version) {
297                         $domain .= '-'.$version;
298                 }
299
300         if (array_key_exists($domain, $this->_domains)) 
301         { 
302             return; 
303         }
304         
305         if (!$this->_lang_code) 
306         { 
307             $this->_jobs[] = array($domain, $path); 
308             return;
309         }
310         // Don't fill the domains with false data, it increased the error.log
311         if (strpos($domain, $this->_lang_code) === false)
312                 return;
313  
314         $err = $this->_load_domain($domain, $path);
315         if ($err != 0) 
316         {
317             return $err;
318         }
319
320         $this->_end++;
321     }
322
323     /**
324      * Load a translation domain file.
325      *
326      * This method cache the translation hash into a php file unless
327      * GETTEXT_NO_CACHE is defined.
328      * 
329      * @param  string $domain        -- Domain name
330      * @param  string $path optional -- Repository
331      * @throws GetText_Error
332      * @access private
333      */
334     function _load_domain($domain, $path = "./locale")
335     {
336         $src_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.po";
337         $php_domain = $path . "/$this->_lang_code/LC_MESSAGES/$domain.php";
338         
339         if (!file_exists($src_domain)) 
340         {
341             $str = sprintf('Domain file "%s" not found.', $src_domain);
342                         return raise_error("4 " . $str);
343         }
344         
345         $d = new gettext_domain();
346         $d->name = $domain;
347         $d->path = $path;
348         if (!file_exists($php_domain) || (filemtime($php_domain) < filemtime($src_domain))) 
349         {
350             
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')) 
355             {
356                 $comp = new gettext_php_support_compiler();
357                 $err  = $comp->compile($hash, $src_domain);
358                         if (is_error($err)) 
359                         {
360                     return $err;
361                 } 
362             }
363             $d->_keys = $hash;
364         } 
365         else 
366         {
367             $d->_keys = include $php_domain;
368         }
369         $this->_domains[] = &$d;
370     }
371     
372     /**
373      * Implementation of gettext message retrieval.
374      */
375     function _get_translation($key)
376     {
377         for ($i = $this->_end; $i >= 0; $i--) 
378         {
379             if ($this->_domains[$i]->has_key($key)) 
380             {
381                 return $this->_domains[$i]->get($key);
382             }
383         }
384         return $key;
385     }
386 }
387
388 /**
389 * Class representing a domain file for a specified language.
390 *
391 * @access private
392 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
393 */
394 class gettext_domain
395 {
396     var $name;
397     var $path;
398
399     var $_keys = array();
400
401     function has_key($key)
402     {
403         return array_key_exists($key, $this->_keys);
404     }
405
406     function get($key)
407     {
408         return $this->_keys[$key];
409     }
410 }
411
412 /**
413 * This class is used to parse gettext '.po' files into php associative arrays.
414 *
415 * @access private
416 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
417 */
418 class gettext_php_support_parser 
419 {
420     var $_hash = array();
421     var $_current_key;
422     var $_current_value;
423     
424     /**
425      * Parse specified .po file.
426      *
427      * @return hashtable
428      * @throws GetText_Error
429      */
430     function parse($file)
431     {
432         $this->_hash = array();
433         $this->_current_key = false;
434         $this->_current_value = "";
435         
436         if (!file_exists($file)) 
437         {
438             $str = sprintf('Unable to locate file "%s"', $file);
439                         return raise_error($str);
440         }
441         $i = 0;
442         $lines = file($file);
443         foreach ($lines as $line) 
444         {
445             $this->_parse_line($line, ++$i);
446         }
447         $this->_store_key();
448
449         return $this->_hash;
450     }
451
452     /**
453      * Parse one po line.
454      *
455      * @access private
456      */
457     function _parse_line($line, $nbr)
458     {
459         $line = str_replace("\\\"", "'", $line); // Should be inside preg_match, but I couldn't find the solution. This works.
460         if (preg_match('/^\s*?#/', $line)) { return; }
461         if (preg_match('/^\s*?msgid \"(.*?)(?!<\\\)\"/', $line, $m)) {
462             $this->_store_key();
463             $this->_current_key = $m[1];
464             return;
465         }
466         if (preg_match('/^\s*?msgstr \"(.*?)(?!<\\\)\"/', $line, $m)) {
467             $this->_current_value .= $m[1];
468             return;
469         }
470         if (preg_match('/^\s*?\"(.*?)(?!<\\\)\"/', $line, $m)) {
471             $this->_current_value .= $m[1];
472             return;
473         }
474     }
475
476     /**
477      * Store last key/value pair into building hashtable.
478      *
479      * @access private
480      */
481     function _store_key()
482     {
483         if ($this->_current_key === false) return;
484         $this->_current_value = str_replace('\\n', "\n", $this->_current_value);
485         $this->_hash[$this->_current_key] = $this->_current_value;
486         $this->_current_key = false;
487         $this->_current_value = "";
488     }
489 }
490
491
492 /**
493 * This class write a php file from a gettext hashtable.
494 *
495 * The produced file return the translation hashtable on include.
496
497 * @throws GetText_Error
498 * @access private
499 * @author Laurent Bedubourg <laurent.bedubourg@free.fr>
500 */
501 class gettext_php_support_compiler 
502 {
503     /**
504      * Write hash in an includable php file.
505      */
506     function compile(&$hash, $source_path)
507     {
508         $dest_path = preg_replace('/\.po$/', '.php', $source_path);
509         $fp = @fopen($dest_path, "w");
510         if (!$fp) 
511         {
512             $str = sprintf('Unable to open "%s" in write mode.', $dest_path);
513                         return raise_error($str);
514         }
515         fwrite($fp, '<?php' . "\n");
516         fwrite($fp, 'return array(' . "\n");
517         foreach ($hash as $key => $value) 
518         {
519             $key   = str_replace("'", "\\'", $key);
520             $value = str_replace("'", "\\'", $value);
521             fwrite($fp, '    \'' . $key . '\' => \'' . $value . "',\n");
522         }
523         fwrite($fp, ');' . "\n");
524         fclose($fp);
525     }
526 }
527
528 /*
529         Set current gettext domain path
530 */
531 function set_ext_domain($path='') {
532         global $path_to_root, $GetText;
533         static $domain_stack = array('');
534
535         if ($path)      // save path on domain stack
536                 array_unshift($domain_stack,  $path);
537         else
538         {
539                 array_shift($domain_stack);
540                 $path = $domain_stack[0];
541         }
542
543         $lang_path = $path_to_root . ($path ? '/' : '') .$path.'/lang';
544         // ignore change when extension does not provide translation structure and test for valid gettext.
545         if (file_exists($lang_path) && isset($GetText))
546                 $GetText->add_domain($_SESSION['language']->code,
547                         $lang_path, $path ? '' : $_SESSION['language']->version);
548 }