File: Gettext_PHP.php

package info (click to toggle)
spotweb 20130826%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 5,132 kB
  • ctags: 11,281
  • sloc: php: 31,367; xml: 1,009; sh: 148; makefile: 83
file content (325 lines) | stat: -rwxr-xr-x 10,464 bytes parent folder | download | duplicates (2)
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
<?php
/*
 * Copyright (c) 2009 David Soria Parra
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */


/**
 * Gettext implementation in PHP
 *
 * @copyright (c) 2009 David Soria Parra <sn_@gmx.net>
 * @author David Soria Parra <sn_@gmx.net>
 */
class Gettext_PHP extends SpotGettext
{
    /**
     * First magic word in the MO header
     */
    const MAGIC1 = 0xde120495;

    /**
     * First magic word in the MO header
     */
    const MAGIC2 = 0x950412de;

    protected $dir;
    protected $domain;
    protected $locale;
    protected $translationTable = array();
    protected $parsed = array();

    /**
     * Initialize a new gettext class
     *
     * @param String $mofile The file to parse
     */
    public function __construct($directory, $domain, $locale)
    {
        $this->dir = $directory;
        $this->domain = $domain;
        $this->locale = $locale;
    }

    /**
     * Parse the MO file header and returns the table
     * offsets as described in the file header.
     *
     * If an exception occured, null is returned. This is intentionally
     * as we need to get close to ext/gettexts beahvior.
     *
     * @oaram Ressource $fp The open file handler to the MO file
     *
     * @return An array of offset
     */
    private function parseHeader($fp)
    {
        $data   = fread($fp, 8);
        $header = unpack("lmagic/lrevision", $data);

        if ((int) self::MAGIC1 != $header['magic']
           && (int) self::MAGIC2 != $header['magic']) {
            return null;
        }

        if (0 != $header['revision']) {
            return null;
        }

        $data    = fread($fp, 4 * 5);
        $offsets = unpack("lnum_strings/lorig_offset/"
                          . "ltrans_offset/lhash_size/lhash_offset", $data);
        return $offsets;
    }

    /**
     * Parse and reutnrs the string offsets in a a table. Two table can be found in
     * a mo file. The table with the translations and the table with the original
     * strings. Both contain offsets to the strings in the file.
     *
     * If an exception occured, null is returned. This is intentionally
     * as we need to get close to ext/gettexts beahvior.
     *
     * @param Ressource $fp     The open file handler to the MO file
     * @param Integer   $offset The offset to the table that should be parsed
     * @param Integer   $num    The number of strings to parse
     *
     * @return Array of offsets
     */
    private function parseOffsetTable($fp, $offset, $num)
    {
        if (fseek($fp, $offset, SEEK_SET) < 0) {
            return null;
        }

        $table = array();
        for ($i = 0; $i < $num; $i++) {
            $data    = fread($fp, 8);
            $table[] = unpack("lsize/loffset", $data);
        }

        return $table;
    }

    /**
     * Parse a string as referenced by an table. Returns an
     * array with the actual string.
     *
     * @param Ressource $fp    The open file handler to the MO fie
     * @param Array     $entry The entry as parsed by parseOffsetTable()
     *
     * @return Parsed string
     */
    private function parseEntry($fp, $entry)
    {
        if (fseek($fp, $entry['offset'], SEEK_SET) < 0) {
            return null;
        }
        if ($entry['size'] > 0) {
            return fread($fp, $entry['size']);
        }

       return '';
    }

    /**
     * Parse the MO file
     *
     * @return void
     */
    private function parse($locale, $domain)
    {
        $this->translationTable[$locale][$domain] = array();
        $mofile = sprintf("%s/%s/LC_MESSAGES/%s.mo", $this->dir, $locale, $domain);
        $cachefile = sprintf("%s/%s/LC_MESSAGES/%s.ser", $this->dir, $locale, $domain);

        if (!file_exists($mofile)) {
            $this->parsed[$locale][$domain] = true;
            return;
        }

        $filesize = filesize($mofile);
        if ($filesize < 4 * 7) {
            $this->parsed[$locale][$domain] = true;
            return;
        }

        if (($tmpobj = @file_get_contents($cachefile)) === FALSE || @filemtime($cachefile) < filemtime($mofile)) {
            /* check for filesize */
            $fp = fopen($mofile, "rb");

            $offsets = $this->parseHeader($fp);
            if (null == $offsets || $filesize < 4 * ($offsets['num_strings'] + 7)) {
                fclose($fp);
                return;
            }

            $transTable = array();
            $table = $this->parseOffsetTable($fp, $offsets['trans_offset'],
                        $offsets['num_strings']);
            if (null == $table) {
                fclose($fp);
                return;
            }

            foreach ($table as $idx => $entry) {
                $transTable[$idx] = $this->parseEntry($fp, $entry);
            }

            $table = $this->parseOffsetTable($fp, $offsets['orig_offset'],
                        $offsets['num_strings']);
            foreach ($table as $idx => $entry) {
                $entry = $this->parseEntry($fp, $entry);

                $formes      = explode(chr(0), $entry);
                $translation = explode(chr(0), $transTable[$idx]);
                foreach($formes as $form) {
                    $this->translationTable[$locale][$domain][$form] = $translation;
                }
            }
            @file_put_contents($cachefile, serialize($this->translationTable[$locale][$domain]) );

            fclose($fp);
        } else {
            $this->translationTable[$locale][$domain] = unserialize($tmpobj);
        }
        $this->parsed[$locale][$domain] = true;
    }

    /**
     * Return a translated string
     *
     * If the translation is not found, the original passed message
     * will be returned.
     *
     * @return Translated message
     */
    public function gettext($msg)
    {
        if (!@$this->parsed[$this->locale][$this->domain]) {
            $this->parse($this->locale, $this->domain);
        }

        if (array_key_exists($msg, $this->translationTable[$this->locale][$this->domain])) {
            return $this->translationTable[$this->locale][$this->domain][$msg][0];
        }
        return $msg;
    }

    /**
     * Overrides the domain for a single lookup
     *
     * If the translation is not found, the original passed message
     * will be returned.
     *
     * @param String $domain The domain to search in
     * @param String $msg The message to search for
     *
     * @return Translated string
     */
    public function dgettext($domain, $msg)
    {
        if (!@$this->parsed[$this->locale][$domain]) {
            $this->parse($this->locale, $domain);
        }

        if (array_key_exists($msg, $this->translationTable[$this->locale][$domain])) {
            return $this->translationTable[$this->locale][$domain][$msg][0];
        }
        return $msg;
    }

    /**
     * Return a translated string in it's plural form
     *
     * Returns the given $count (e.g second, third,...) plural form of the
     * given string. If the id is not found and $num == 1 $msg is returned,
     * otherwise $msg_plural
     *
     * @param String $msg The message to search for
     * @param String $msg_plural A fallback plural form
     * @param Integer $count Which plural form
     *
     * @return Translated string
     */
    public function ngettext($msg, $msg_plural, $count)
    {
        if (!@$this->parsed[$this->locale][$this->domain]) {
            $this->parse($this->locale, $this->domain);
        }

        $msg = (string) $msg;

        if (array_key_exists($msg, $this->translationTable[$this->locale][$this->domain])) {
            $translation = $this->translationTable[$this->locale][$this->domain][$msg];
            /* the gettext api expect an unsigned int, so we just fake 'cast' */
            if ($count <= 0 || count($translation) < $count) {
                $count = count($translation);
            }
            return $translation[$count - 1];
        }

        /* not found, handle count */
        if (1 == $count) {
            return $msg;
        } else {
            return $msg_plural;
        }
    }

    /**
     * Override the current domain for a single plural message lookup
     *
     * Returns the given $count (e.g second, third,...) plural form of the
     * given string. If the id is not found and $num == 1 $msg is returned,
     * otherwise $msg_plural
     *
     * @param String $domain The domain to search in
     * @param String $msg The message to search for
     * @param String $msg_plural A fallback plural form
     * @param Integer $count Which plural form
     *
     * @return Translated string
     */
    public function dngettext($domain, $msg, $msg_plural, $count)
    {
        if (!@$this->parsed[$this->locale][$domain]) {
            $this->parse($this->locale, $domain);
        }

        $msg = (string) $msg;

        if (array_key_exists($msg, $this->translationTable[$this->locale][$domain])) {
            $translation = $this->translationTable[$this->locale][$domain][$msg];
            /* the gettext api expect an unsigned int, so we just fake 'cast' */
            if ($count <= 0 || count($translation) < $count) {
                $count = count($translation);
            }
            return $translation[$count - 1];
        }

        /* not found, handle count */
        if (1 == $count) {
            return $msg;
        } else {
            return $msg_plural;
        }
    }
}