xref: /webtrees/app/I18N.php (revision fbb7c24ea6b5eba4bded9beab647f831ac6850b5)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18use Collator;
19use Exception;
20use Fisharebest\Localization\Locale;
21use Fisharebest\Localization\Locale\LocaleEnUs;
22use Fisharebest\Localization\Locale\LocaleInterface;
23use Fisharebest\Localization\Translation;
24use Fisharebest\Localization\Translator;
25use Fisharebest\Webtrees\Functions\FunctionsEdit;
26
27/**
28 * Internationalization (i18n) and localization (l10n).
29 */
30class I18N
31{
32    /** @var LocaleInterface The current locale (e.g. LocaleEnGb) */
33    private static $locale;
34
35    /** @var Translator An object that performs translation */
36    private static $translator;
37
38    /** @var  Collator From the php-intl library */
39    private static $collator;
40
41    // Digits are always rendered LTR, even in RTL text.
42    const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹';
43
44    // These locales need special handling for the dotless letter I.
45    const DOTLESS_I_LOCALES = [
46        'az',
47        'tr',
48    ];
49    const DOTLESS_I_TOLOWER = [
50        'I' => 'ı',
51        'İ' => 'i',
52    ];
53    const DOTLESS_I_TOUPPER = [
54        'ı' => 'I',
55        'i' => 'İ',
56    ];
57
58    // The ranges of characters used by each script.
59    const SCRIPT_CHARACTER_RANGES = [
60        [
61            'Latn',
62            0x0041,
63            0x005A,
64        ],
65        [
66            'Latn',
67            0x0061,
68            0x007A,
69        ],
70        [
71            'Latn',
72            0x0100,
73            0x02AF,
74        ],
75        [
76            'Grek',
77            0x0370,
78            0x03FF,
79        ],
80        [
81            'Cyrl',
82            0x0400,
83            0x052F,
84        ],
85        [
86            'Hebr',
87            0x0590,
88            0x05FF,
89        ],
90        [
91            'Arab',
92            0x0600,
93            0x06FF,
94        ],
95        [
96            'Arab',
97            0x0750,
98            0x077F,
99        ],
100        [
101            'Arab',
102            0x08A0,
103            0x08FF,
104        ],
105        [
106            'Deva',
107            0x0900,
108            0x097F,
109        ],
110        [
111            'Taml',
112            0x0B80,
113            0x0BFF,
114        ],
115        [
116            'Sinh',
117            0x0D80,
118            0x0DFF,
119        ],
120        [
121            'Thai',
122            0x0E00,
123            0x0E7F,
124        ],
125        [
126            'Geor',
127            0x10A0,
128            0x10FF,
129        ],
130        [
131            'Grek',
132            0x1F00,
133            0x1FFF,
134        ],
135        [
136            'Deva',
137            0xA8E0,
138            0xA8FF,
139        ],
140        [
141            'Hans',
142            0x3000,
143            0x303F,
144        ],
145        // Mixed CJK, not just Hans
146        [
147            'Hans',
148            0x3400,
149            0xFAFF,
150        ],
151        // Mixed CJK, not just Hans
152        [
153            'Hans',
154            0x20000,
155            0x2FA1F,
156        ],
157        // Mixed CJK, not just Hans
158    ];
159
160    // Characters that are displayed in mirror form in RTL text.
161    const MIRROR_CHARACTERS = [
162        '('  => ')',
163        ')'  => '(',
164        '['  => ']',
165        ']'  => '[',
166        '{'  => '}',
167        '}'  => '{',
168        '<'  => '>',
169        '>'  => '<',
170        '‹ ' => '›',
171        '› ' => '‹',
172        '«'  => '»',
173        '»'  => '«',
174        '﴾ ' => '﴿',
175        '﴿ ' => '﴾',
176        '“ ' => '”',
177        '” ' => '“',
178        '‘ ' => '’',
179        '’ ' => '‘',
180    ];
181
182    // Default list of locales to show in the menu.
183    const DEFAULT_LOCALES = [
184        'ar',
185        'bg',
186        'bs',
187        'ca',
188        'cs',
189        'da',
190        'de',
191        'el',
192        'en-GB',
193        'en-US',
194        'es',
195        'et',
196        'fi',
197        'fr',
198        'he',
199        'hr',
200        'hu',
201        'is',
202        'it',
203        'ka',
204        'kk',
205        'lt',
206        'mr',
207        'nb',
208        'nl',
209        'nn',
210        'pl',
211        'pt',
212        'ru',
213        'sk',
214        'sv',
215        'tr',
216        'uk',
217        'vi',
218        'zh-Hans',
219    ];
220
221    /** @var string Punctuation used to separate list items, typically a comma */
222    public static $list_separator;
223
224    /**
225     * The prefered locales for this site, or a default list if no preference.
226     *
227     * @return LocaleInterface[]
228     */
229    public static function activeLocales(): array
230    {
231        $code_list = Site::getPreference('LANGUAGES');
232
233        if ($code_list === '') {
234            $codes = self::DEFAULT_LOCALES;
235        } else {
236            $codes = explode(',', $code_list);
237        }
238
239        $locales = [];
240        foreach ($codes as $code) {
241            if (file_exists(WT_ROOT . 'language/' . $code . '.mo')) {
242                try {
243                    $locales[] = Locale::create($code);
244                } catch (\Exception $ex) {
245                    DebugBar::addThrowable($ex);
246
247                    // No such locale exists?
248                }
249            }
250        }
251        usort($locales, '\Fisharebest\Localization\Locale::compare');
252
253        return $locales;
254    }
255
256    /**
257     * Which MySQL collation should be used for this locale?
258     *
259     * @return string
260     */
261    public static function collation()
262    {
263        $collation = self::$locale->collation();
264        switch ($collation) {
265            case 'croatian_ci':
266            case 'german2_ci':
267            case 'vietnamese_ci':
268                // Only available in MySQL 5.6
269                return 'utf8_unicode_ci';
270            default:
271                return 'utf8_' . $collation;
272        }
273    }
274
275    /**
276     * What format is used to display dates in the current locale?
277     *
278     * @return string
279     */
280    public static function dateFormat(): string
281    {
282        /* I18N: This is the format string for full dates. See http://php.net/date for codes */
283        return self::$translator->translate('%j %F %Y');
284    }
285
286    /**
287     * Generate consistent I18N for datatables.js
288     *
289     * @param int[] $lengths An optional array of page lengths
290     *
291     * @return string
292     */
293    public static function datatablesI18N(array $lengths = [
294        10,
295        20,
296        30,
297        50,
298        100,
299        -1,
300    ]): string
301    {
302        $length_options = Bootstrap4::select(FunctionsEdit::numericOptions($lengths), '10');
303
304        return
305            '"formatNumber": function(n) { return String(n).replace(/[0-9]/g, function(w) { return ("' . self::$locale->digits('0123456789') . '")[+w]; }); },' .
306            '"language": {' .
307            ' "paginate": {' .
308            '  "first":    "' . self::translate('first') . '",' .
309            '  "last":     "' . self::translate('last') . '",' .
310            '  "next":     "' . self::translate('next') . '",' .
311            '  "previous": "' . self::translate('previous') . '"' .
312            ' },' .
313            ' "emptyTable":     "' . self::translate('No records to display') . '",' .
314            ' "info":           "' . /* I18N: %s are placeholders for numbers */
315            self::translate('Showing %1$s to %2$s of %3$s', '_START_', '_END_', '_TOTAL_') . '",' .
316            ' "infoEmpty":      "' . self::translate('Showing %1$s to %2$s of %3$s', self::$locale->digits('0'), self::$locale->digits('0'), self::$locale->digits('0')) . '",' .
317            ' "infoFiltered":   "' . /* I18N: %s is a placeholder for a number */
318            self::translate('(filtered from %s total entries)', '_MAX_') . '",' .
319            ' "lengthMenu":     "' . /* I18N: %s is a number of records per page */
320            self::translate('Display %s', addslashes($length_options)) . '",' .
321            ' "loadingRecords": "' . self::translate('Loading…') . '",' .
322            ' "processing":     "' . self::translate('Loading…') . '",' .
323            ' "search":         "' . self::translate('Filter') . '",' .
324            ' "zeroRecords":    "' . self::translate('No records to display') . '"' .
325            '}';
326    }
327
328    /**
329     * Convert the digits 0-9 into the local script
330     *
331     * Used for years, etc., where we do not want thousands-separators, decimals, etc.
332     *
333     * @param string|int $n
334     *
335     * @return string
336     */
337    public static function digits($n): string
338    {
339        return self::$locale->digits((string) $n);
340    }
341
342    /**
343     * What is the direction of the current locale
344     *
345     * @return string "ltr" or "rtl"
346     */
347    public static function direction(): string
348    {
349        return self::$locale->direction();
350    }
351
352    /**
353     * What is the first day of the week.
354     *
355     * @return int Sunday=0, Monday=1, etc.
356     */
357    public static function firstDay(): int
358    {
359        return self::$locale->territory()->firstDay();
360    }
361
362    /**
363     * Convert a GEDCOM age string into translated_text
364     *
365     * NB: The import function will have normalised this, so we don't need
366     * to worry about badly formatted strings
367     * NOTE: this function is not yet complete - eventually it will replace FunctionsDate::get_age_at_event()
368     *
369     * @param $string
370     *
371     * @return string
372     */
373    public static function gedcomAge(string $string): string
374    {
375        switch ($string) {
376            case 'STILLBORN':
377                // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (stillborn)
378                return self::translate('(stillborn)');
379            case 'INFANT':
380                // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in infancy)
381                return self::translate('(in infancy)');
382            case 'CHILD':
383                // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in childhood)
384                return self::translate('(in childhood)');
385        }
386        $age = [];
387        if (preg_match('/(\d+)y/', $string, $match)) {
388            $years = (int) $match[1];
389            // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
390            $age[] = self::plural('%s year', '%s years', $years, self::number($years));
391        } else {
392            $years = -1;
393        }
394        if (preg_match('/(\d+)m/', $string, $match)) {
395            $months = (int) $match[1];
396            // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
397            $age[] = self::plural('%s month', '%s months', $months, self::number($months));
398        }
399        if (preg_match('/(\d+)w/', $string, $match)) {
400            $weeks = (int) $match[1];
401            // I18N: Part of an age string. e.g. 7 weeks and 3 days
402            $age[] = self::plural('%s week', '%s weeks', $weeks, self::number($weeks));
403        }
404        if (preg_match('/(\d+)d/', $string, $match)) {
405            $days = (int) $match[1];
406            // I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
407            $age[] = self::plural('%s day', '%s days', $days, self::number($days));
408        }
409        // If an age is just a number of years, only show the number
410        if (count($age) === 1 && $years >= 0) {
411            $age = $years;
412        }
413        if ($age) {
414            if (!substr_compare($string, '<', 0, 1)) {
415                // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged less than 21 years)
416                return self::translate('(aged less than %s)', $age);
417            } elseif (!substr_compare($string, '>', 0, 1)) {
418                // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged more than 21 years)
419                return self::translate('(aged more than %s)', $age);
420            } else {
421                // I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged 43 years)
422                return self::translate('(aged %s)', $age);
423            }
424        } else {
425            // Not a valid string?
426            return self::translate('(aged %s)', $string);
427        }
428    }
429
430    /**
431     * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl"
432     *
433     * @return string
434     */
435    public static function htmlAttributes(): string
436    {
437        return self::$locale->htmlAttributes();
438    }
439
440    /**
441     * Initialise the translation adapter with a locale setting.
442     *
443     * @param string $code Use this locale/language code, or choose one automatically
444     *
445     * @return string $string
446     */
447    public static function init(string $code = ''): string
448    {
449        mb_internal_encoding('UTF-8');
450
451        if ($code !== '') {
452            // Create the specified locale
453            self::$locale = Locale::create($code);
454        } else {
455            // Negotiate a locale, but if we can't then use a failsafe
456            self::$locale = new LocaleEnUs();
457            if (Session::has('locale') && file_exists(WT_ROOT . 'language/' . Session::get('locale') . '.mo')) {
458                // Previously used
459                self::$locale = Locale::create(Session::get('locale'));
460            } else {
461                // Browser negotiation
462                $default_locale = new LocaleEnUs();
463                try {
464                    // @TODO, when no language is requested by the user (e.g. search engines), we should use
465                    // the tree's default language.  However, we currently initialise languages before trees,
466                    //  so there is no tree available for us to use.
467                } catch (\Exception $ex) {
468                    DebugBar::addThrowable($ex);
469                }
470                self::$locale = Locale::httpAcceptLanguage($_SERVER, self::installedLocales(), $default_locale);
471            }
472        }
473
474        $cache_dir  = WT_DATA_DIR . 'cache/';
475        $cache_file = $cache_dir . 'language-' . self::$locale->languageTag() . '-cache.php';
476        if (file_exists($cache_file)) {
477            $filemtime = filemtime($cache_file);
478        } else {
479            $filemtime = 0;
480        }
481
482        // Load the translation file(s)
483        // Note that glob() returns false instead of an empty array when open_basedir_restriction
484        // is in force and no files are found. See PHP bug #47358.
485        if (defined('GLOB_BRACE')) {
486            $translation_files = array_merge(
487                [WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'],
488                glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: [],
489                glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: []
490            );
491        } else {
492            // Some servers do not have GLOB_BRACE - see http://php.net/manual/en/function.glob.php
493            $translation_files = array_merge(
494                [WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'],
495                glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.csv') ?: [],
496                glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.php') ?: [],
497                glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.mo') ?: [],
498                glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.csv') ?: [],
499                glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.php') ?: [],
500                glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.mo') ?: []
501            );
502        }
503        // Rebuild files after one hour
504        $rebuild_cache = time() > $filemtime + 3600;
505        // Rebuild files if any translation file has been updated
506        foreach ($translation_files as $translation_file) {
507            if (filemtime($translation_file) > $filemtime) {
508                $rebuild_cache = true;
509                break;
510            }
511        }
512
513        if ($rebuild_cache) {
514            $translations = [];
515            foreach ($translation_files as $translation_file) {
516                $translation  = new Translation($translation_file);
517                $translations = array_merge($translations, $translation->asArray());
518            }
519            try {
520                File::mkdir($cache_dir);
521                file_put_contents($cache_file, '<?php return ' . var_export($translations, true) . ';');
522            } catch (Exception $ex) {
523                DebugBar::addThrowable($ex);
524
525                // During setup, we may not have been able to create it.
526            }
527        } else {
528            $translations = include $cache_file;
529        }
530
531        // Create a translator
532        self::$translator = new Translator($translations, self::$locale->pluralRule());
533
534        /* I18N: This punctuation is used to separate lists of items */
535        self::$list_separator = self::translate(', ');
536
537        // Create a collator
538        try {
539            // PHP 5.6 cannot catch errors, so test first
540            if (class_exists('Collator')) {
541                self::$collator = new Collator(self::$locale->code());
542                // Ignore upper/lower case differences
543                self::$collator->setStrength(Collator::SECONDARY);
544            }
545        } catch (Exception $ex) {
546            DebugBar::addThrowable($ex);
547
548            // PHP-INTL is not installed?  We'll use a fallback later.
549        }
550
551        return self::$locale->languageTag();
552    }
553
554    /**
555     * All locales for which a translation file exists.
556     *
557     * @return LocaleInterface[]
558     */
559    public static function installedLocales(): array
560    {
561        $locales = [];
562        foreach (glob(WT_ROOT . 'language/*.mo') as $file) {
563            try {
564                $locales[] = Locale::create(basename($file, '.mo'));
565            } catch (\Exception $ex) {
566                DebugBar::addThrowable($ex);
567
568                // Not a recognised locale
569            }
570        }
571        usort($locales, '\Fisharebest\Localization\Locale::compare');
572
573        return $locales;
574    }
575
576    /**
577     * Return the endonym for a given language - as per http://cldr.unicode.org/
578     *
579     * @param string $locale
580     *
581     * @return string
582     */
583    public static function languageName(string $locale): string
584    {
585        return Locale::create($locale)->endonym();
586    }
587
588    /**
589     * Return the script used by a given language
590     *
591     * @param string $locale
592     *
593     * @return string
594     */
595    public static function languageScript(string $locale): string
596    {
597        return Locale::create($locale)->script()->code();
598    }
599
600    /**
601     * Translate a number into the local representation.
602     *
603     * e.g. 12345.67 becomes
604     * en: 12,345.67
605     * fr: 12 345,67
606     * de: 12.345,67
607     *
608     * @param float $n
609     * @param int   $precision
610     *
611     * @return string
612     */
613    public static function number(float $n, int $precision = 0): string
614    {
615        return self::$locale->number(round($n, $precision));
616    }
617
618    /**
619     * Translate a fraction into a percentage.
620     *
621     * e.g. 0.123 becomes
622     * en: 12.3%
623     * fr: 12,3 %
624     * de: 12,3%
625     *
626     * @param float $n
627     * @param int   $precision
628     *
629     * @return string
630     */
631    public static function percentage(float $n, int $precision = 0): string
632    {
633        return self::$locale->percent(round($n, $precision + 2));
634    }
635
636    /**
637     * Translate a plural string
638     * echo self::plural('There is an error', 'There are errors', $num_errors);
639     * echo self::plural('There is one error', 'There are %s errors', $num_errors);
640     * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour);
641     *
642     * @param array $args
643     *
644     * @return string
645     */
646    public static function plural(...$args): string
647    {
648        $args[0] = self::$translator->translatePlural($args[0], $args[1], (int) $args[2]);
649        unset($args[1], $args[2]);
650
651        return sprintf(...$args);
652    }
653
654    /**
655     * UTF8 version of PHP::strrev()
656     *
657     * Reverse RTL text for third-party libraries such as GD2 and googlechart.
658     *
659     * These do not support UTF8 text direction, so we must mimic it for them.
660     *
661     * Numbers are always rendered LTR, even in RTL text.
662     * The visual direction of characters such as parentheses should be reversed.
663     *
664     * @param string $text Text to be reversed
665     *
666     * @return string
667     */
668    public static function reverseText($text): string
669    {
670        // Remove HTML markup - we can't display it and it is LTR.
671        $text = strip_tags($text);
672        // Remove HTML entities.
673        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
674
675        // LTR text doesn't need reversing
676        if (self::scriptDirection(self::textScript($text)) === 'ltr') {
677            return $text;
678        }
679
680        // Mirrored characters
681        $text = strtr($text, self::MIRROR_CHARACTERS);
682
683        $reversed = '';
684        $digits   = '';
685        while ($text != '') {
686            $letter = mb_substr($text, 0, 1);
687            $text   = mb_substr($text, 1);
688            if (strpos(self::DIGITS, $letter) !== false) {
689                $digits .= $letter;
690            } else {
691                $reversed = $letter . $digits . $reversed;
692                $digits   = '';
693            }
694        }
695
696        return $digits . $reversed;
697    }
698
699    /**
700     * Return the direction (ltr or rtl) for a given script
701     *
702     * The PHP/intl library does not provde this information, so we need
703     * our own lookup table.
704     *
705     * @param string $script
706     *
707     * @return string
708     */
709    public static function scriptDirection($script)
710    {
711        switch ($script) {
712            case 'Arab':
713            case 'Hebr':
714            case 'Mong':
715            case 'Thaa':
716                return 'rtl';
717            default:
718                return 'ltr';
719        }
720    }
721
722    /**
723     * Perform a case-insensitive comparison of two strings.
724     *
725     * @param string $string1
726     * @param string $string2
727     *
728     * @return int
729     */
730    public static function strcasecmp($string1, $string2)
731    {
732        if (self::$collator instanceof Collator) {
733            return self::$collator->compare($string1, $string2);
734        } else {
735            return strcmp(self::strtolower($string1), self::strtolower($string2));
736        }
737    }
738
739    /**
740     * Convert a string to lower case.
741     *
742     * @param string $string
743     *
744     * @return string
745     */
746    public static function strtolower($string): string
747    {
748        if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) {
749            $string = strtr($string, self::DOTLESS_I_TOLOWER);
750        }
751
752        return mb_strtolower($string);
753    }
754
755    /**
756     * Convert a string to upper case.
757     *
758     * @param string $string
759     *
760     * @return string
761     */
762    public static function strtoupper($string): string
763    {
764        if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) {
765            $string = strtr($string, self::DOTLESS_I_TOUPPER);
766        }
767
768        return mb_strtoupper($string);
769    }
770
771    /**
772     * Identify the script used for a piece of text
773     *
774     * @param $string
775     *
776     * @return string
777     */
778    public static function textScript($string): string
779    {
780        $string = strip_tags($string); // otherwise HTML tags show up as latin
781        $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin
782        $string = str_replace([
783            '@N.N.',
784            '@P.N.',
785        ], '', $string); // otherwise unknown names show up as latin
786        $pos    = 0;
787        $strlen = strlen($string);
788        while ($pos < $strlen) {
789            // get the Unicode Code Point for the character at position $pos
790            $byte1 = ord($string[$pos]);
791            if ($byte1 < 0x80) {
792                $code_point = $byte1;
793                $chrlen     = 1;
794            } elseif ($byte1 < 0xC0) {
795                // Invalid continuation character
796                return 'Latn';
797            } elseif ($byte1 < 0xE0) {
798                $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F);
799                $chrlen     = 2;
800            } elseif ($byte1 < 0xF0) {
801                $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F);
802                $chrlen     = 3;
803            } elseif ($byte1 < 0xF8) {
804                $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F);
805                $chrlen     = 3;
806            } else {
807                // Invalid UTF
808                return 'Latn';
809            }
810
811            foreach (self::SCRIPT_CHARACTER_RANGES as $range) {
812                if ($code_point >= $range[1] && $code_point <= $range[2]) {
813                    return $range[0];
814                }
815            }
816            // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking.
817            $pos += $chrlen;
818        }
819
820        return 'Latn';
821    }
822
823    /**
824     * Convert a number of seconds into a relative time. For example, 630 => "10 hours, 30 minutes ago"
825     *
826     * @param int $seconds
827     *
828     * @return string
829     */
830    public static function timeAgo($seconds)
831    {
832        $minute = 60;
833        $hour   = 60 * $minute;
834        $day    = 24 * $hour;
835        $month  = 30 * $day;
836        $year   = 365 * $day;
837
838        if ($seconds > $year) {
839            $years = (int)($seconds / $year);
840
841            return self::plural('%s year ago', '%s years ago', $years, self::number($years));
842        } elseif ($seconds > $month) {
843            $months = (int)($seconds / $month);
844
845            return self::plural('%s month ago', '%s months ago', $months, self::number($months));
846        } elseif ($seconds > $day) {
847            $days = (int)($seconds / $day);
848
849            return self::plural('%s day ago', '%s days ago', $days, self::number($days));
850        } elseif ($seconds > $hour) {
851            $hours = (int)($seconds / $hour);
852
853            return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours));
854        } elseif ($seconds > $minute) {
855            $minutes = (int)($seconds / $minute);
856
857            return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes));
858        } else {
859            return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds));
860        }
861    }
862
863    /**
864     * What format is used to display dates in the current locale?
865     *
866     * @return string
867     */
868    public static function timeFormat(): string
869    {
870        /* I18N: This is the format string for the time-of-day. See http://php.net/date for codes */
871        return self::$translator->translate('%H:%i:%s');
872    }
873
874    /**
875     * Translate a string, and then substitute placeholders
876     *
877     * echo I18N::translate('Hello World!');
878     * echo I18N::translate('The %s sat on the mat', 'cat');
879     *
880     * @param array $args
881     *
882     * @return string
883     */
884    public static function translate(...$args): string
885    {
886        $args[0] = self::$translator->translate($args[0]);
887
888        return sprintf(...$args);
889    }
890
891    /**
892     * Context sensitive version of translate.
893     * echo I18N::translateContext('NOMINATIVE', 'January');
894     * echo I18N::translateContext('GENITIVE', 'January');
895     *
896     * @param array $args
897     *
898     * @return string
899     */
900    public static function translateContext(...$args): string
901    {
902        $args[1] = self::$translator->translateContext($args[0], $args[1]);
903        unset($args[0]);
904
905        return sprintf(...$args);
906    }
907}
908