speedmax / h2o-php

A beautiful template engine for PHP in Django style

This URL has Read+Write access

h2o-php / ext / i18n.php
100644 422 lines (364 sloc) 15.648 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<?php
h2o::addTag('trans');
h2o::addTag('blocktrans');
h2o::addLookup(array('H2o_I18n', 'gettext'));
 
class Trans_Tag extends H2o_Node {
    var $text = null;
    function __construct($argstring, $parser, $position = 0) {
        $this->text = stripcslashes(substr($argstring, 1, -1));
    }
    
    function render($context, $stream) {
        if ($this->text) {
            $gettext = H2o_I18n::$gettext;
            $stream->write(call_user_func($gettext, $this->text));
        }
    }
}
 
class Blocktrans_Tag extends H2o_Node {
    private $singular, $plural;
    private $vars = array();
    private $aliases = array();
    private $count;
 
    function __construct($argstring, $parser, $position = 0) {
        # get all aliases alias
        if (!empty($argstring)) {
            $arguments = array_map('trim', explode(',', $argstring));
            foreach($arguments as $argument) {
                if (strpos($argument, '=')) {
                    list($alias, $variable) = explode('=', $argument);
                } else {
                    $variable = $alias = $argument;
                }
                $this->aliases[trim($alias)] = H2o_Parser::parseArguments($variable);
            }
        }
 
        # Parse singular and plural block
        $this->singular = $parser->parse('plural', 'endblocktrans');
        
        if ($parser->token->content === 'plural') {
            $this->plural = $parser->parse('endblocktrans');
        }
        
        # compile nodes into string format
        if ($this->singular)
            $this->singular = $this->compile_nodes($this->singular);
 
        if ($this->plural)
            $this->plural = $this->compile_nodes($this->plural);
    }
    
    function render($context, $stream) {
        $context->push();
        $this->count = false;
        $cache = array();
        foreach($this->aliases as $alias => $data) {
            $variable = array_shift($data);
            $filters = $data;
            $object = $context->resolve($variable);
            
            if (is_null($object)) continue;
            
            if (!empty($filters))
                $object = $context->applyFilters($object, $filters);
 
            $cache[$alias] = $object;
            if ($this->count === false)
                $this->count = $object;
        }
        
        # Implicit object count lookup
        if (!is_integer($this->count))
            $this->count = count($this->count);
            
        # Get translation
        $ngettext = H2o_I18n::$ngettext;
        $gettext = H2o_I18n::$gettext;
        if ($this->plural)
            $output = call_user_func($ngettext, $this->singular, $this->plural, $this->count);
        else
            $output = call_user_func($gettext, $this->singular);
 
        # Variable in output
        foreach(array_keys($this->vars) as $var) {
            $object = isset($cache[$var])? $cache[$var]: $context->resolve($var);
            if (!is_null($object)) {
                $output = str_replace("%({$var})", $object, $output);
            }
        }
        $context->pop();
        $stream->write($output);
    }
    
    function compile_nodes($nodes) {
        $output = array();
        foreach ($nodes as $node) {
            if ($node instanceOf VariableNode) {
                if (is_sym($node->variable))
                    $var = sym_to_str($node->variable);
                else
                    $var = $node->variable;
                $output[] = "%({$var})";
                $this->vars[$var] = 1;
            } elseif ($node instanceOf TextNode) {
                $output[] = str_replace("\r", '', $node->content);
            }
        }
        return join('', $output);
    }
}
 
class H2o_I18n {
    var $locale;
    var $charset = 'UTF-8';
    var $locale_dir;
    var $tmp_dir;
    var $extensions = array('html','tpl');
    var $gettext_path = '';
    var $gettext_setup = false;
    static $gettext = 'gettext';
    static $ngettext = 'ngettext';
    
    function __construct($path, $options = array()) {
        if (is_file($path))
            $path = dirname($path) . DS;
 
        $this->searchpath = realpath($path).DS;
        $this->locale_dir = $this->searchpath .'locale'.DS;
        $this->options = $options;
        
        if (isset($options['tmp_dir']))
            $this->tmp_dir = $options['tmp_dir'];
        else
            $this->tmp_dir = $this->searchpath.'tmp' .DS;
        
        if (isset($options['ext']))
            $this->extensions = $options['ext'];
            
        if (isset($options['charset']))
            $this->charset = $options['charset'];
            
        if (isset($options['locale']) && $options['locale'])
            $this->setLocale($options['locale']);
        
        if (isset($options['extract_message']) && $options['extract_message'])
            $this->extract();
        
        if (isset($options['compile_message']) && $options['compile_message'])
            $this->compile();
        
        if (!is_dir($this->locale_dir) && !mkdir($this->locale_dir))
            throw new Exception('locale directory not found and failed to created '.$this->searchpath);
    }
    
    function gettext($name, $context) {
        $gettext = self::$gettext;
        if (!is_string($name)) return ;
        $syntax = '/_\(((?:".*?")|(?:\'.*?\'))\)/';
        if (preg_match($syntax, $name, $match)) {
            $text = stripcslashes(substr($match[1], 1, -1));
            return call_user_func($gettext, $text);
        }
    }
    
    function setupGettext() {
        if (isset($this->options['gettext_path']))
            $this->gettext_path = $this->options['gettext_path'];
 
        if (!file_exists($this->gettext_path))
            $this->gettext_path = $this->searchpath.$this->gettext_path;
 
        $this->gettext_path = realpath($this->gettext_path).DS;
 
        if (!exec($this->gettext_path."xgettext -V")) {
            throw new Exception(
                "xgettext binary cannot be found, if you are using Windows system either install through cygwin
or read instruction here http://docs.djangoproject.com/en/dev/topics/i18n/#gettext-on-windows"
            );
        }
        
        $this->gettext_setup = true;
    }
    
    function extract() {
        if (!$this->gettext_setup)
            $this->setupGettext();
 
        if (!class_exists('H2o_Lexer'))
            require H2O_ROOT.'h2o/parser.php';
        # get all tempaltes
        $templates = $this->getTemplates($this->searchpath, $this->extensions, array(dirname(dirname($this->gettext_path))));
        # Get all locales in translation path
        if (!is_dir($this->tmp_dir))
            mkdir($this->tmp_dir);
        
        # foreach locale
        foreach(glob($this->locale_dir.'*') as $dir) {
            if (!is_dir($dir)) continue;
            $locale = basename($dir);
            $lc_messages = $dir . DS . 'LC_MESSAGES'. DS;
            $pot_file = $lc_messages."messages.pot";
            $po_file = $lc_messages."messages.po";
    
            if (!is_dir($lc_messages))
                mkdir($lc_messages);
            
            if (is_file($pot_file))
                unlink($pot_file);
            
            # Compile messages into php file
            $sourcecode = array();
            foreach ($templates as $file) {
                # compile template into php code
                $compiled_src = templize(file_get_contents($file));
                if (!$compiled_src)
                  continue;
                $sourcecode[] = $compiled_src;
            }
            $compiled_file = $this->tmp_dir. 'template_source.php';
            file_put_contents($compiled_file, "<?php ". join(";\n", $sourcecode) ." ?>" );
 
            # run xgettext to extract all translation string
            $return = '';
            $extra_arg = '';
            if (is_file($pot_file))
                $extra_arg = "--omit-header";
 
            $cmd = "{$this->gettext_path}xgettext -L PHP {$extra_arg} --from-code UTF-8 -o - \"{$compiled_file}\"";
            if (!exec($cmd, $return)){
                throw new Exception('Failed to parse template file');
            }
            list($nplurals, $plural) = $this->getPluralForm($locale);
            $replace = array(
                'charset=CHARSET' => 'charset=UTF-8',
                "#: {$compiled_file}" => "#: {$file}",
                "INTEGER" => $nplurals,
                "EXPRESSION" => $plural,
                "PACKAGE VERSION" => "template translation",
                "\"Language-Team: LANGUAGE <LL@li.org>\\n\"\n" => ""
            );
            $return = join("\n", $return);
            $return = str_replace(array_keys($replace), $replace , $return ."\n");
            file_put_contents($pot_file, $return, FILE_APPEND);
            
            # merge messages for each language
            if (is_file($pot_file)) {
                $return = $error = '';
                $cmd = $this->gettext_path."msguniq --to-code=utf-8 \"{$pot_file}\"";
                
                if (!exec($cmd, $return))
                    throw new Exception('Msgunique failed');
                
                file_put_contents($pot_file, join("\n", $return));
                if (is_file($po_file) && trim(file_get_contents($po_file)) !== '') {
                    $return = '';
                    $cmd = sprintf($this->gettext_path.'msgmerge -q "%s" "%s"', $po_file, $pot_file);
                    exec($cmd, $return);
                    file_put_contents($po_file, join("\n", $return));
                } else {
                    copy($pot_file, $po_file);
                }
            }
            @unlink($pot_file);
        }
        @unlink($compiled_file);
        @rmdir($this->tmp_dir);
    }
 
    function compile() {
        if (!$this->gettext_setup)
            $this->setupGettext();
        
        foreach(glob($this->locale_dir.'*') as $dir) {
          if (!is_dir($dir)) continue;
          $locale = basename($dir);
          $lc_messages = $dir.DS.'LC_MESSAGES'.DS;
          $po_file = $lc_messages."messages.po";
          $mo_file = $lc_messages."messages.mo";
    
          if (!is_dir($lc_messages))
              mkdir($lc_messages);
    
          $cmd = $this->gettext_path."msgfmt --check-format -o {$mo_file} {$po_file}";
          exec($cmd, $return);
      }
    }
    
    function setLocale($locale, $charset = null) {
        $this->locale = $locale;
        if (!$charset)
            $charset = $this->charset;
        
        putenv("LC_ALL={$locale}");
        setlocale(LC_ALL, $locale);
        if (!is_dir($this->locale_dir))
            throw new Exception('Cannot find Locale message path');
        bindtextdomain("messages", $this->locale_dir);
        bind_textdomain_codeset('messages', $charset);
        textdomain("messages");
    }
    
    function getPluralForm($locale = 'en') {
        $default= array("2", "(n != 1)");
        $default_locale = array(
            'en', 'fi', 'de', 'da', 'el', 'eo', 'es', 'et', 'eu', 'af', 'az', 'bg', 'bn', 'ca', 'nn', 'no', 'pt', 'sv'
        );
        // In-regular plural forms
        $map = array(
            'fr' => array("2", "(n >= 1)"),
            'ja' => array("1", "0"), 'zh' => array("1", "0"),
            'pl' => array("3", "(n==1 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)"),
            'ro' => array("3", "(n==1 ? 0 : (n==0 or (n%100 > 0 && n%100 < 20)) ? 1 : 2)"),
            'ru' => array("3", "(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)"),
        );
        $locale = current(explode('-', $locale));
        if (isset($map[$locale])) {
            return $map[$locale];
        }
        return $default;
    }
    
    function getTemplates($path, $exts, $exclude = array()) {
        $results = array();
        foreach(new DirectoryIterator($path) as $f) {
            if ($f->isDot()) continue;
    
            if ($f->isFile()) {
                $ext = end(explode(".", $f->getFilename()));
                if ($ext && in_array($ext, $exts) ) {
                    $results[] = $f->getPathname();
                }
            } elseif ($f->isDir() && !in_array($f->getPathname(), $exclude)) {
                $results = array_merge($results, $this->getTemplates($f->getPathname(), $exts, $exclude));
            }
        }
        return $results;
    }
}
 
/*
Compile
*/
function templize($source) {
    $output = array();
    $inline_re = '/^\s*trans\s+("(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'(?:[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')\s*/';
    $block_re = "/^\s*blocktrans(?:\s+|$)/";
    $endblock_re = "/^\s*endblocktrans$/";
    $plural_re = "/^\s*plural$/";
    $var_re = '{
_\(
(
"[^"\\\\]*(?:\\\\.[^"\\\\]*)*" | # Double Quote string
\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' # Single Quote String
)
\)
}x';
    
    $lexer = new H2o_Lexer(h2o::getOptions());
    $tokenstream = $lexer->tokenize($source);
    
    $in_block = false;
    $is_plural = false;
    
    $singulars = array();
    $plurals = array();
    
    while($t = $tokenstream->next()) {
        if ($in_block) {
            if ($t->type == 'block' && $t->content == 'endblocktrans') {
                if ($is_plural) {
                    $output[] = sprintf(
                        " ngettext('%s', '%s', \$count)", join('', $singulars), join('', $plurals)
                    );
                } else {
                    $output[] = sprintf(" gettext('%s')", join('', $singulars));
                }
                $singulars = $plurals = array();
                $in_block = $is_plural = false ;
            }
            elseif ($t->type == 'block' && $t->content == 'plural') {
                $is_plural = true;
            }
            elseif ($t->type == 'text') {
                if ($is_plural)
                    $plurals[] = addslashes($t->content);
                else
                    $singulars[] = addslashes($t->content);
            }
            elseif ($t->type == 'variable') {
                @list($var, $filters ) = explode('|', $t->content);
                if ($is_plural)
                    $plurals[] = sprintf("%%(%s)", $var);
                else
                    $singulars[] = sprintf("%%(%s)", $var);
            }
            elseif ($t->type == 'block') {
                throw new Exception('No block tag is allowed in translation block');
            }
        } else {
            if ($t->type == 'block') {
                if (preg_match($inline_re, $t->content, $matches)) {
                    $output[] = sprintf(" gettext(%s)", $matches[1]);
                }
                elseif (preg_match($block_re, $t->content, $matches)) {
                    $in_block = true;
                }
            } elseif ($t->type == 'variable') {
                if (preg_match($var_re, $t->content, $matches)) {
                    $output[] = sprintf(" gettext(%s)", ($matches[1]));
                }
            }
        }
    }
    $result = str_replace("\r", '', implode(";\n", $output));
    if ($result)
    return "\n".$result . ";\n";
}
 
?>