Passed
Push — master ( cea13f...16712b )
by William
14:23 queued 04:25
created

Translator::getTranslations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
ccs 0
cts 0
cp 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
    Copyright (c) 2003, 2009 Danilo Segan <[email protected]>.
7
    Copyright (c) 2005 Nico Kaiser <[email protected]>
8
    Copyright (c) 2016 Michal Čihař <[email protected]>
9
10
    This file is part of MoTranslator.
11
12
    This program is free software; you can redistribute it and/or modify
13
    it under the terms of the GNU General Public License as published by
14
    the Free Software Foundation; either version 2 of the License, or
15
    (at your option) any later version.
16
17
    This program is distributed in the hope that it will be useful,
18
    but WITHOUT ANY WARRANTY; without even the implied warranty of
19
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
    GNU General Public License for more details.
21
22
    You should have received a copy of the GNU General Public License along
23
    with this program; if not, write to the Free Software Foundation, Inc.,
24
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25
*/
26
27
namespace PhpMyAdmin\MoTranslator;
28
29
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
30
use Throwable;
31
use function array_key_exists;
32
use function chr;
33
use function count;
34
use function explode;
35
use function implode;
36
use function intval;
37
use function is_readable;
38
use function ltrim;
39
use function preg_replace;
40
use function rtrim;
41
use function strcmp;
42
use function stripos;
43
use function strpos;
44
use function strtolower;
45
use function substr;
46
use function trim;
47
48
/**
49
 * Provides a simple gettext replacement that works independently from
50
 * the system's gettext abilities.
51
 * It can read MO files and use them for translating strings.
52
 *
53
 * It caches ll strings and translations to speed up the string lookup.
54
 */
55
class Translator
56
{
57
    /**
58
     * None error.
59
     */
60
    public const ERROR_NONE = 0;
61
    /**
62
     * File does not exist.
63
     */
64
    public const ERROR_DOES_NOT_EXIST = 1;
65
    /**
66
     * File has bad magic number.
67
     */
68
    public const ERROR_BAD_MAGIC = 2;
69
    /**
70
     * Error while reading file, probably too short.
71
     */
72
    public const ERROR_READING = 3;
73
74
    /**
75
     * Big endian mo file magic bytes.
76
     */
77
    public const MAGIC_BE = "\x95\x04\x12\xde";
78
    /**
79
     * Little endian mo file magic bytes.
80
     */
81
    public const MAGIC_LE = "\xde\x12\x04\x95";
82
83
    /**
84
     * Parse error code (0 if no error).
85
     *
86
     * @var int
87
     */
88
    public $error = self::ERROR_NONE;
89
90
    /**
91
     * Cache header field for plural forms.
92
     *
93
     * @var string|null
94
     */
95
    private $pluralEquation = null;
96
97
    /** @var ExpressionLanguage|null Evaluator for plurals */
98
    private $pluralExpression = null;
99
100
    /** @var int|null number of plurals */
101
    private $pluralCount = null;
102
103
    /**
104
     * Array with original -> translation mapping.
105
     *
106
     * @var array<string,string>
107
     */
108
    private $cacheTranslations = [];
109
110
    /**
111
     * @param string|null $filename Name of mo file to load (null to not load a file)
112 180
     */
113
    public function __construct(?string $filename)
114 180
    {
115 24
        // The user can load the translations manually
116
        if ($filename === null) {
117 24
            return;
118
        }
119
120 156
        $this->loadTranslationsFromFile($filename);
121
    }
122
123 156
    /**
124 152
     * Load a Mo file translations
125 120
     *
126 32
     * @param string $filename Name of mo file to load
127 28
     */
128
    private function loadTranslationsFromFile(string $filename): void
129 4
    {
130
        if (! is_readable($filename)) {
131 4
            $this->error = self::ERROR_DOES_NOT_EXIST;
132
133
            return;
134
        }
135 148
136 148
        $stream = new StringReader($filename);
137 136
138
        try {
139
            $magic = $stream->read(0, 4);
140 136
            if (strcmp($magic, self::MAGIC_LE) === 0) {
141 132
                $unpack = 'V';
142
            } elseif (strcmp($magic, self::MAGIC_BE) === 0) {
143
                $unpack = 'N';
144 132
            } else {
145 132
                $this->error = self::ERROR_BAD_MAGIC;
146 132
147 132
                return;
148
            }
149 20
150 20
            /* Parse header */
151
            $total = $stream->readint($unpack, 8);
152 20
            $originals = $stream->readint($unpack, 12);
153
            $translations = $stream->readint($unpack, 16);
154 132
155
            /* get original and translations tables */
156
            $totalTimesTwo = (int) ($total * 2);// Fix for issue #36 on ARM
157
            $tableOriginals = $stream->readintarray($unpack, $originals, $totalTimesTwo);
158
            $tableTranslations = $stream->readintarray($unpack, $translations, $totalTimesTwo);
159
160
            /* read all strings to the cache */
161
            for ($i = 0; $i < $total; ++$i) {
162
                $iTimesTwo = $i * 2;
163 120
                $iPlusOne = $iTimesTwo + 1;
164
                $iPlusTwo = $iTimesTwo + 2;
165 120
                $original = $stream->read($tableOriginals[$iPlusTwo], $tableOriginals[$iPlusOne]);
166 84
                $translation = $stream->read($tableTranslations[$iPlusTwo], $tableTranslations[$iPlusOne]);
167
                $this->cacheTranslations[$original] = $translation;
168
            }
169 60
        } catch (ReaderException $e) {
170
            $this->error = self::ERROR_READING;
171
172
            return;
173
        }
174
    }
175
176
    /**
177 24
     * Translates a string.
178
     *
179 24
     * @param string $msgid String to be translated
180
     *
181
     * @return string translated string (or original, if not found)
182
     */
183
    public function gettext(string $msgid): string
184
    {
185
        if (array_key_exists($msgid, $this->cacheTranslations)) {
186
            return $this->cacheTranslations[$msgid];
187
        }
188
189 56
        return $msgid;
190
    }
191
192 56
    /**
193 56
     * Check if a string is translated.
194 44
     *
195
     * @param string $msgid String to be checked
196 12
     */
197
    public function exists(string $msgid): bool
198
    {
199 56
        return array_key_exists($msgid, $this->cacheTranslations);
200
    }
201 56
202 48
    /**
203
     * Sanitize plural form expression for use in ExpressionLanguage.
204
     *
205
     * @param string $expr Expression to sanitize
206 56
     *
207 48
     * @return string sanitized plural form expression
208
     */
209
    public static function sanitizePluralExpression(string $expr): string
210
    {
211 56
        // Parse equation
212
        $expr = explode(';', $expr);
213 56
        if (count($expr) >= 2) {
214
            $expr = $expr[1];
215
        } else {
216
            $expr = $expr[0];
217
        }
218
219
        $expr = trim(strtolower($expr));
220
        // Strip plural prefix
221
        if (substr($expr, 0, 6) === 'plural') {
222
            $expr = ltrim(substr($expr, 6));
223 52
        }
224
225 52
        // Strip equals
226 52
        if (substr($expr, 0, 1) === '=') {
227 52
            $expr = ltrim(substr($expr, 1));
228 8
        }
229
230
        // Cleanup from unwanted chars
231 44
        $expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr);
232 4
233
        return (string) $expr;
234
    }
235 40
236
    /**
237
     * Extracts number of plurals from plurals form expression.
238
     *
239
     * @param string $expr Expression to process
240
     *
241
     * @return int Total number of plurals
242
     */
243
    public static function extractPluralCount(string $expr): int
244
    {
245 44
        $parts = explode(';', $expr, 2);
246
        $nplurals = explode('=', trim($parts[0]), 2);
247 44
        if (strtolower(rtrim($nplurals[0])) !== 'nplurals') {
248 44
            return 1;
249 44
        }
250 44
251 44
        if (count($nplurals) === 1) {
252
            return 1;
253
        }
254 28
255
        return intval($nplurals[1]);
256
    }
257 44
258
    /**
259
     * Parse full PO header and extract only plural forms line.
260
     *
261
     * @param string $header Gettext header
262
     *
263
     * @return string verbatim plural form header field
264
     */
265 32
    public static function extractPluralsForms(string $header): string
266
    {
267
        $headers = explode("\n", $header);
268
        $expr = 'nplurals=2; plural=n == 1 ? 0 : 1;';
269
        foreach ($headers as $header) {
270
            if (stripos($header, 'Plural-Forms:') !== 0) {
271 32
                continue;
272 28
            }
273 20
274
            $expr = substr($header, 13);
275 8
        }
276
277
        return $expr;
278 28
    }
279 28
280 28
    /**
281
     * Get possible plural forms from MO header.
282
     *
283 32
     * @return string plural form header
284
     */
285
    private function getPluralForms(): string
286
    {
287
        // lets assume message number 0 is header
288
        // this is true, right?
289
290
        // cache header field for plural forms
291
        if ($this->pluralEquation === null) {
292
            if (isset($this->cacheTranslations[''])) {
293 32
                $header = $this->cacheTranslations[''];
294
            } else {
295 32
                $header = '';
296 28
            }
297
298
            $expr = $this->extractPluralsForms($header);
299
            $this->pluralEquation = $this->sanitizePluralExpression($expr);
300 32
            $this->pluralCount = $this->extractPluralCount($expr);
301 32
        }
302 32
303
        return $this->pluralEquation;
304 4
    }
305 4
306
    /**
307
     * Detects which plural form to take.
308 32
     *
309 4
     * @param int $n count of objects
310
     *
311
     * @return int array index of the right plural form
312 32
     */
313
    private function selectString(int $n): int
314
    {
315
        if ($this->pluralExpression === null) {
316
            $this->pluralExpression = new ExpressionLanguage();
317
        }
318
319
        try {
320
            $plural = $this->pluralExpression->evaluate(
321
                $this->getPluralForms(),
322
                ['n' => $n]
323
            );
324 72
            if ($plural === false) {
0 ignored issues
show
introduced by
The condition $plural === false is always false.
Loading history...
325
                $plural = 0;
326
            }
327 72
        } catch (Throwable $e) {
328 72
            $plural = 0;
329 72
        }
330
331
        if ($plural >= $this->pluralCount) {
332
            $plural = $this->pluralCount - 1;
333 32
        }
334
335 32
        return $plural;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $plural could return the type array which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
336 32
    }
337 32
338
    /**
339
     * Plural version of gettext.
340
     *
341 32
     * @param string $msgid       Single form
342 4
     * @param string $msgidPlural Plural form
343
     * @param int    $number      Number of objects
344
     *
345 32
     * @return string translated plural form
346
     */
347
    public function ngettext(string $msgid, string $msgidPlural, int $number): string
348
    {
349
        // this should contains all strings separated by NULLs
350
        $key = implode(chr(0), [$msgid, $msgidPlural]);
351
        if (! array_key_exists($key, $this->cacheTranslations)) {
352
            return $number !== 1 ? $msgidPlural : $msgid;
353
        }
354
355
        // find out the appropriate form
356 56
        $select = $this->selectString($number);
357
358 56
        $result = $this->cacheTranslations[$key];
359 56
        $list = explode(chr(0), $result);
360 56
        // @codeCoverageIgnoreStart
361 24
        if ($list === false) {
362
            // This was added in 3ff2c63bcf85f81b3a205ce7222de11b33e2bf56 for phpstan
363
            // But according to the php manual it should never happen
364 32
            return '';
365
        }
366
        // @codeCoverageIgnoreEnd
367
368
        if (! isset($list[$select])) {
369
            return $list[0];
370
        }
371
372
        return $list[$select];
373
    }
374
375
    /**
376
     * Translate with context.
377 16
     *
378
     * @param string $msgctxt Context
379 16
     * @param string $msgid   String to be translated
380 16
     *
381 16
     * @return string translated plural form
382 4
     */
383
    public function pgettext(string $msgctxt, string $msgid): string
384
    {
385 12
        $key = implode(chr(4), [$msgctxt, $msgid]);
386
        $ret = $this->gettext($key);
387
        if (strpos($ret, chr(4)) !== false) {
388
            return $msgid;
389
        }
390
391
        return $ret;
392
    }
393
394 4
    /**
395
     * Plural version of pgettext.
396 4
     *
397 4
     * @param string $msgctxt     Context
398
     * @param string $msgid       Single form
399
     * @param string $msgidPlural Plural form
400
     * @param int    $number      Number of objects
401
     *
402
     * @return string translated plural form
403
     */
404
    public function npgettext(string $msgctxt, string $msgid, string $msgidPlural, int $number): string
405
    {
406
        $key = implode(chr(4), [$msgctxt, $msgid]);
407
        $ret = $this->ngettext($key, $msgidPlural, $number);
408
        if (strpos($ret, chr(4)) !== false) {
409
            return $msgid;
410
        }
411
412
        return $ret;
413
    }
414
415
    /**
416
     * Set translation in place
417
     *
418
     * @param string $msgid  String to be set
419
     * @param string $msgstr Translation
420
     */
421
    public function setTranslation(string $msgid, string $msgstr): void
422
    {
423
        $this->cacheTranslations[$msgid] = $msgstr;
424
    }
425
426
    /**
427
     * Set the translations
428
     *
429
     * @param array<string,string> $translations The translations "key => value" array
430
     */
431
    public function setTranslations(array $translations): void
432
    {
433
        $this->cacheTranslations = $translations;
434
    }
435
436
    /**
437
     * Get the translations
438
     *
439
     * @return array<string,string> The translations "key => value" array
440
     */
441
    public function getTranslations(): array
442
    {
443
        return $this->cacheTranslations;
444
    }
445
}
446