xref: /webtrees/app/I18N.php (revision 1d1f373cc23093682b1736881f66a527f62ccc46)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Collator;
23use Exception;
24use Fisharebest\Localization\Locale;
25use Fisharebest\Localization\Locale\LocaleEnUs;
26use Fisharebest\Localization\Locale\LocaleInterface;
27use Fisharebest\Localization\Translation;
28use Fisharebest\Localization\Translator;
29use Fisharebest\Webtrees\Module\ModuleCustomInterface;
30use Fisharebest\Webtrees\Module\ModuleLanguageInterface;
31use Fisharebest\Webtrees\Services\ModuleService;
32use Illuminate\Support\Collection;
33
34use function array_merge;
35use function class_exists;
36use function html_entity_decode;
37use function in_array;
38use function mb_strtolower;
39use function mb_strtoupper;
40use function mb_substr;
41use function ord;
42use function sprintf;
43use function str_replace;
44use function strcmp;
45use function strip_tags;
46use function strlen;
47use function strpos;
48use function strtr;
49
50/**
51 * Internationalization (i18n) and localization (l10n).
52 */
53class I18N
54{
55    // MO files use special characters for plurals and context.
56    public const PLURAL  = "\x00";
57    public const CONTEXT = "\x04";
58    private const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹';
59    private const DOTLESS_I_LOCALES = [
60        'az',
61        'tr',
62    ];
63    private const DOTLESS_I_TOLOWER = [
64        'I' => 'ı',
65        'İ' => 'i',
66    ];
67
68    // Digits are always rendered LTR, even in RTL text.
69    private const DOTLESS_I_TOUPPER = [
70        'ı' => 'I',
71        'i' => 'İ',
72    ];
73
74    // These locales need special handling for the dotless letter I.
75    private const SCRIPT_CHARACTER_RANGES = [
76        [
77            'Latn',
78            0x0041,
79            0x005A,
80        ],
81        [
82            'Latn',
83            0x0061,
84            0x007A,
85        ],
86        [
87            'Latn',
88            0x0100,
89            0x02AF,
90        ],
91        [
92            'Grek',
93            0x0370,
94            0x03FF,
95        ],
96        [
97            'Cyrl',
98            0x0400,
99            0x052F,
100        ],
101        [
102            'Hebr',
103            0x0590,
104            0x05FF,
105        ],
106        [
107            'Arab',
108            0x0600,
109            0x06FF,
110        ],
111        [
112            'Arab',
113            0x0750,
114            0x077F,
115        ],
116        [
117            'Arab',
118            0x08A0,
119            0x08FF,
120        ],
121        [
122            'Deva',
123            0x0900,
124            0x097F,
125        ],
126        [
127            'Taml',
128            0x0B80,
129            0x0BFF,
130        ],
131        [
132            'Sinh',
133            0x0D80,
134            0x0DFF,
135        ],
136        [
137            'Thai',
138            0x0E00,
139            0x0E7F,
140        ],
141        [
142            'Geor',
143            0x10A0,
144            0x10FF,
145        ],
146        [
147            'Grek',
148            0x1F00,
149            0x1FFF,
150        ],
151        [
152            'Deva',
153            0xA8E0,
154            0xA8FF,
155        ],
156        [
157            'Hans',
158            0x3000,
159            0x303F,
160        ],
161        // Mixed CJK, not just Hans
162        [
163            'Hans',
164            0x3400,
165            0xFAFF,
166        ],
167        // Mixed CJK, not just Hans
168        [
169            'Hans',
170            0x20000,
171            0x2FA1F,
172        ],
173        // Mixed CJK, not just Hans
174    ];
175    private const MIRROR_CHARACTERS = [
176        '('  => ')',
177        ')'  => '(',
178        '['  => ']',
179        ']'  => '[',
180        '{'  => '}',
181        '}'  => '{',
182        '<'  => '>',
183        '>'  => '<',
184        '‹ ' => '›',
185        '› ' => '‹',
186        '«'  => '»',
187        '»'  => '«',
188        '﴾ ' => '﴿',
189        '﴿ ' => '﴾',
190        '“ ' => '”',
191        '” ' => '“',
192        '‘ ' => '’',
193        '’ ' => '‘',
194    ];
195    /** @var string Punctuation used to separate list items, typically a comma */
196    public static $list_separator;
197
198    // The ranges of characters used by each script.
199    /** @var LocaleInterface The current locale (e.g. LocaleEnGb) */
200    private static $locale;
201
202    // Characters that are displayed in mirror form in RTL text.
203    /** @var Translator An object that performs translation */
204    private static $translator;
205    /** @var  Collator|null From the php-intl library */
206    private static $collator;
207
208    /**
209     * The preferred locales for this site, or a default list if no preference.
210     *
211     * @return LocaleInterface[]
212     */
213    public static function activeLocales(): array
214    {
215        /** @var Collection $locales */
216        $locales = app(ModuleService::class)
217            ->findByInterface(ModuleLanguageInterface::class, false, true)
218            ->map(static function (ModuleLanguageInterface $module): LocaleInterface {
219                return $module->locale();
220            });
221
222        if ($locales->isEmpty()) {
223            return [new LocaleEnUs()];
224        }
225
226        return $locales->all();
227    }
228
229    /**
230     * Which MySQL collation should be used for this locale?
231     *
232     * @return string
233     */
234    public static function collation(): string
235    {
236        $collation = self::$locale->collation();
237        switch ($collation) {
238            case 'croatian_ci':
239            case 'german2_ci':
240            case 'vietnamese_ci':
241                // Only available in MySQL 5.6
242                return 'utf8_unicode_ci';
243            default:
244                return 'utf8_' . $collation;
245        }
246    }
247
248    /**
249     * What format is used to display dates in the current locale?
250     *
251     * @return string
252     */
253    public static function dateFormat(): string
254    {
255        /* I18N: This is the format string for full dates. See http://php.net/date for codes */
256        return self::$translator->translate('%j %F %Y');
257    }
258
259    /**
260     * Convert the digits 0-9 into the local script
261     * Used for years, etc., where we do not want thousands-separators, decimals, etc.
262     *
263     * @param string|int $n
264     *
265     * @return string
266     */
267    public static function digits($n): string
268    {
269        return self::$locale->digits((string) $n);
270    }
271
272    /**
273     * What is the direction of the current locale
274     *
275     * @return string "ltr" or "rtl"
276     */
277    public static function direction(): string
278    {
279        return self::$locale->direction();
280    }
281
282    /**
283     * What is the first day of the week.
284     *
285     * @return int Sunday=0, Monday=1, etc.
286     */
287    public static function firstDay(): int
288    {
289        return self::$locale->territory()->firstDay();
290    }
291
292    /**
293     * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl"
294     *
295     * @return string
296     */
297    public static function htmlAttributes(): string
298    {
299        return self::$locale->htmlAttributes();
300    }
301
302    /**
303     * Initialise the translation adapter with a locale setting.
304     *
305     * @param string    $code  Use this locale/language code, or choose one automatically
306     * @param Tree|null $tree
307     * @param bool      $setup During setup, we cannot access the database.
308     *
309     * @return string $string
310     */
311    public static function init(string $code = '', Tree $tree = null, $setup = false): string
312    {
313        if ($code !== '') {
314            // Create the specified locale
315            self::$locale = Locale::create($code);
316        } elseif (Session::has('language')) {
317            // Select a previously used locale
318            self::$locale = Locale::create(Session::get('language'));
319        } else {
320            if ($tree instanceof Tree) {
321                $default_locale = Locale::create($tree->getPreference('LANGUAGE', 'en-US'));
322            } else {
323                $default_locale = new LocaleEnUs();
324            }
325
326            // Negotiate with the browser.
327            // Search engines don't negotiate.  They get the default locale of the tree.
328            if ($setup) {
329                $installed_locales = app(ModuleService::class)->setupLanguages()
330                    ->map(static function (ModuleLanguageInterface $module): LocaleInterface {
331                        return $module->locale();
332                    });
333            } else {
334                $installed_locales = self::installedLocales();
335            }
336
337            self::$locale = Locale::httpAcceptLanguage($_SERVER, $installed_locales->all(), $default_locale);
338        }
339
340        // Load the translation file
341        $translation_file = Webtrees::ROOT_DIR . 'resources/lang/' . self::$locale->languageTag() . '/messages.php';
342
343        try {
344            $translation  = new Translation($translation_file);
345            $translations = $translation->asArray();
346        } catch (Exception $ex) {
347            // The translations files are created during the build process, and are
348            // not included in the source code.
349            // Assuming we are using dev code, and build (or rebuild) the files.
350            $po_file      = Webtrees::ROOT_DIR . 'resources/lang/' . self::$locale->languageTag() . '/messages.po';
351            $translation  = new Translation($po_file);
352            $translations = $translation->asArray();
353            file_put_contents($translation_file, '<?php return ' . var_export($translations, true) . ';');
354        }
355
356        // Add translations from custom modules (but not during setup, as we have no database/modules)
357        if (!$setup) {
358            $translations = app(ModuleService::class)
359                ->findByInterface(ModuleCustomInterface::class)
360                ->reduce(static function (array $carry, ModuleCustomInterface $item): array {
361                    return array_merge($carry, $item->customTranslations(self::$locale->languageTag()));
362                }, $translations);
363        }
364
365        // Create a translator
366        self::$translator = new Translator($translations, self::$locale->pluralRule());
367
368        /* I18N: This punctuation is used to separate lists of items */
369        self::$list_separator = self::translate(', ');
370
371        // Create a collator
372        try {
373            if (class_exists('Collator')) {
374                // Symfony provides a very incomplete polyfill - which cannot be used.
375                self::$collator = new Collator(self::$locale->code());
376                // Ignore upper/lower case differences
377                self::$collator->setStrength(Collator::SECONDARY);
378            }
379        } catch (Exception $ex) {
380            // PHP-INTL is not installed?  We'll use a fallback later.
381            self::$collator = null;
382        }
383
384        return self::$locale->languageTag();
385    }
386
387    /**
388     * All locales for which a translation file exists.
389     *
390     * @return Collection
391     */
392    public static function installedLocales(): Collection
393    {
394        return app(ModuleService::class)
395            ->findByInterface(ModuleLanguageInterface::class, true)
396            ->map(static function (ModuleLanguageInterface $module): LocaleInterface {
397                return $module->locale();
398            });
399    }
400
401    /**
402     * Translate a string, and then substitute placeholders
403     * echo I18N::translate('Hello World!');
404     * echo I18N::translate('The %s sat on the mat', 'cat');
405     *
406     * @param string $message
407     * @param string ...$args
408     *
409     * @return string
410     */
411    public static function translate(string $message, ...$args): string
412    {
413        $message = self::$translator->translate($message);
414
415        return sprintf($message, ...$args);
416    }
417
418    /**
419     * Return the endonym for a given language - as per http://cldr.unicode.org/
420     *
421     * @param string $locale
422     *
423     * @return string
424     */
425    public static function languageName(string $locale): string
426    {
427        return Locale::create($locale)->endonym();
428    }
429
430    /**
431     * Return the script used by a given language
432     *
433     * @param string $locale
434     *
435     * @return string
436     */
437    public static function languageScript(string $locale): string
438    {
439        return Locale::create($locale)->script()->code();
440    }
441
442    /**
443     * Translate a number into the local representation.
444     * e.g. 12345.67 becomes
445     * en: 12,345.67
446     * fr: 12 345,67
447     * de: 12.345,67
448     *
449     * @param float $n
450     * @param int   $precision
451     *
452     * @return string
453     */
454    public static function number(float $n, int $precision = 0): string
455    {
456        return self::$locale->number(round($n, $precision));
457    }
458
459    /**
460     * Translate a fraction into a percentage.
461     * e.g. 0.123 becomes
462     * en: 12.3%
463     * fr: 12,3 %
464     * de: 12,3%
465     *
466     * @param float $n
467     * @param int   $precision
468     *
469     * @return string
470     */
471    public static function percentage(float $n, int $precision = 0): string
472    {
473        return self::$locale->percent(round($n, $precision + 2));
474    }
475
476    /**
477     * Translate a plural string
478     * echo self::plural('There is an error', 'There are errors', $num_errors);
479     * echo self::plural('There is one error', 'There are %s errors', $num_errors);
480     * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour);
481     *
482     * @param string $singular
483     * @param string $plural
484     * @param int    $count
485     * @param string ...$args
486     *
487     * @return string
488     */
489    public static function plural(string $singular, string $plural, int $count, ...$args): string
490    {
491        $message = self::$translator->translatePlural($singular, $plural, $count);
492
493        return sprintf($message, ...$args);
494    }
495
496    /**
497     * UTF8 version of PHP::strrev()
498     * Reverse RTL text for third-party libraries such as GD2 and googlechart.
499     * These do not support UTF8 text direction, so we must mimic it for them.
500     * Numbers are always rendered LTR, even in RTL text.
501     * The visual direction of characters such as parentheses should be reversed.
502     *
503     * @param string $text Text to be reversed
504     *
505     * @return string
506     */
507    public static function reverseText($text): string
508    {
509        // Remove HTML markup - we can't display it and it is LTR.
510        $text = strip_tags($text);
511        // Remove HTML entities.
512        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
513
514        // LTR text doesn't need reversing
515        if (self::scriptDirection(self::textScript($text)) === 'ltr') {
516            return $text;
517        }
518
519        // Mirrored characters
520        $text = strtr($text, self::MIRROR_CHARACTERS);
521
522        $reversed = '';
523        $digits   = '';
524        while ($text !== '') {
525            $letter = mb_substr($text, 0, 1);
526            $text   = mb_substr($text, 1);
527            if (strpos(self::DIGITS, $letter) !== false) {
528                $digits .= $letter;
529            } else {
530                $reversed = $letter . $digits . $reversed;
531                $digits   = '';
532            }
533        }
534
535        return $digits . $reversed;
536    }
537
538    /**
539     * Return the direction (ltr or rtl) for a given script
540     * The PHP/intl library does not provde this information, so we need
541     * our own lookup table.
542     *
543     * @param string $script
544     *
545     * @return string
546     */
547    public static function scriptDirection($script): string
548    {
549        switch ($script) {
550            case 'Arab':
551            case 'Hebr':
552            case 'Mong':
553            case 'Thaa':
554                return 'rtl';
555            default:
556                return 'ltr';
557        }
558    }
559
560    /**
561     * Identify the script used for a piece of text
562     *
563     * @param string $string
564     *
565     * @return string
566     */
567    public static function textScript($string): string
568    {
569        $string = strip_tags($string); // otherwise HTML tags show up as latin
570        $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin
571        $string = str_replace([
572            '@N.N.',
573            '@P.N.',
574        ], '', $string); // otherwise unknown names show up as latin
575        $pos    = 0;
576        $strlen = strlen($string);
577        while ($pos < $strlen) {
578            // get the Unicode Code Point for the character at position $pos
579            $byte1 = ord($string[$pos]);
580            if ($byte1 < 0x80) {
581                $code_point = $byte1;
582                $chrlen     = 1;
583            } elseif ($byte1 < 0xC0) {
584                // Invalid continuation character
585                return 'Latn';
586            } elseif ($byte1 < 0xE0) {
587                $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F);
588                $chrlen     = 2;
589            } elseif ($byte1 < 0xF0) {
590                $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F);
591                $chrlen     = 3;
592            } elseif ($byte1 < 0xF8) {
593                $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F);
594                $chrlen     = 3;
595            } else {
596                // Invalid UTF
597                return 'Latn';
598            }
599
600            foreach (self::SCRIPT_CHARACTER_RANGES as $range) {
601                if ($code_point >= $range[1] && $code_point <= $range[2]) {
602                    return $range[0];
603                }
604            }
605            // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking.
606            $pos += $chrlen;
607        }
608
609        return 'Latn';
610    }
611
612    /**
613     * Perform a case-insensitive comparison of two strings.
614     *
615     * @param string $string1
616     * @param string $string2
617     *
618     * @return int
619     */
620    public static function strcasecmp($string1, $string2): int
621    {
622        if (self::$collator instanceof Collator) {
623            return self::$collator->compare($string1, $string2);
624        }
625
626        return strcmp(self::strtolower($string1), self::strtolower($string2));
627    }
628
629    /**
630     * Convert a string to lower case.
631     *
632     * @param string $string
633     *
634     * @return string
635     */
636    public static function strtolower($string): string
637    {
638        if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES, true)) {
639            $string = strtr($string, self::DOTLESS_I_TOLOWER);
640        }
641
642        return mb_strtolower($string);
643    }
644
645    /**
646     * Convert a string to upper case.
647     *
648     * @param string $string
649     *
650     * @return string
651     */
652    public static function strtoupper($string): string
653    {
654        if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES, true)) {
655            $string = strtr($string, self::DOTLESS_I_TOUPPER);
656        }
657
658        return mb_strtoupper($string);
659    }
660
661    /**
662     * What format is used to display dates in the current locale?
663     *
664     * @return string
665     */
666    public static function timeFormat(): string
667    {
668        /* I18N: This is the format string for the time-of-day. See http://php.net/date for codes */
669        return self::$translator->translate('%H:%i:%s');
670    }
671
672    /**
673     * Context sensitive version of translate.
674     * echo I18N::translateContext('NOMINATIVE', 'January');
675     * echo I18N::translateContext('GENITIVE', 'January');
676     *
677     * @param string $context
678     * @param string $message
679     * @param string ...$args
680     *
681     * @return string
682     */
683    public static function translateContext(string $context, string $message, ...$args): string
684    {
685        $message = self::$translator->translateContext($context, $message);
686
687        return sprintf($message, ...$args);
688    }
689}
690