xref: /webtrees/app/I18N.php (revision 220febf96a8c962107632f2cb1da280ff17fa093)
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     * @return string
643     */
644    public static function plural(...$args): string
645    {
646        $args[0] = self::$translator->translatePlural($args[0], $args[1], (int) $args[2]);
647        unset($args[1], $args[2]);
648
649        return sprintf(...$args);
650    }
651
652    /**
653     * UTF8 version of PHP::strrev()
654     *
655     * Reverse RTL text for third-party libraries such as GD2 and googlechart.
656     *
657     * These do not support UTF8 text direction, so we must mimic it for them.
658     *
659     * Numbers are always rendered LTR, even in RTL text.
660     * The visual direction of characters such as parentheses should be reversed.
661     *
662     * @param string $text Text to be reversed
663     *
664     * @return string
665     */
666    public static function reverseText($text): string
667    {
668        // Remove HTML markup - we can't display it and it is LTR.
669        $text = strip_tags($text);
670        // Remove HTML entities.
671        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
672
673        // LTR text doesn't need reversing
674        if (self::scriptDirection(self::textScript($text)) === 'ltr') {
675            return $text;
676        }
677
678        // Mirrored characters
679        $text = strtr($text, self::MIRROR_CHARACTERS);
680
681        $reversed = '';
682        $digits   = '';
683        while ($text != '') {
684            $letter = mb_substr($text, 0, 1);
685            $text   = mb_substr($text, 1);
686            if (strpos(self::DIGITS, $letter) !== false) {
687                $digits .= $letter;
688            } else {
689                $reversed = $letter . $digits . $reversed;
690                $digits   = '';
691            }
692        }
693
694        return $digits . $reversed;
695    }
696
697    /**
698     * Return the direction (ltr or rtl) for a given script
699     *
700     * The PHP/intl library does not provde this information, so we need
701     * our own lookup table.
702     *
703     * @param string $script
704     *
705     * @return string
706     */
707    public static function scriptDirection($script)
708    {
709        switch ($script) {
710            case 'Arab':
711            case 'Hebr':
712            case 'Mong':
713            case 'Thaa':
714                return 'rtl';
715            default:
716                return 'ltr';
717        }
718    }
719
720    /**
721     * Perform a case-insensitive comparison of two strings.
722     *
723     * @param string $string1
724     * @param string $string2
725     *
726     * @return int
727     */
728    public static function strcasecmp($string1, $string2)
729    {
730        if (self::$collator instanceof Collator) {
731            return self::$collator->compare($string1, $string2);
732        } else {
733            return strcmp(self::strtolower($string1), self::strtolower($string2));
734        }
735    }
736
737    /**
738     * Convert a string to lower case.
739     *
740     * @param string $string
741     *
742     * @return string
743     */
744    public static function strtolower($string): string
745    {
746        if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) {
747            $string = strtr($string, self::DOTLESS_I_TOLOWER);
748        }
749
750        return mb_strtolower($string);
751    }
752
753    /**
754     * Convert a string to upper case.
755     *
756     * @param string $string
757     *
758     * @return string
759     */
760    public static function strtoupper($string): string
761    {
762        if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) {
763            $string = strtr($string, self::DOTLESS_I_TOUPPER);
764        }
765
766        return mb_strtoupper($string);
767    }
768
769    /**
770     * Identify the script used for a piece of text
771     *
772     * @param $string
773     *
774     * @return string
775     */
776    public static function textScript($string): string
777    {
778        $string = strip_tags($string); // otherwise HTML tags show up as latin
779        $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin
780        $string = str_replace([
781            '@N.N.',
782            '@P.N.',
783        ], '', $string); // otherwise unknown names show up as latin
784        $pos    = 0;
785        $strlen = strlen($string);
786        while ($pos < $strlen) {
787            // get the Unicode Code Point for the character at position $pos
788            $byte1 = ord($string[$pos]);
789            if ($byte1 < 0x80) {
790                $code_point = $byte1;
791                $chrlen     = 1;
792            } elseif ($byte1 < 0xC0) {
793                // Invalid continuation character
794                return 'Latn';
795            } elseif ($byte1 < 0xE0) {
796                $code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F);
797                $chrlen     = 2;
798            } elseif ($byte1 < 0xF0) {
799                $code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F);
800                $chrlen     = 3;
801            } elseif ($byte1 < 0xF8) {
802                $code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F);
803                $chrlen     = 3;
804            } else {
805                // Invalid UTF
806                return 'Latn';
807            }
808
809            foreach (self::SCRIPT_CHARACTER_RANGES as $range) {
810                if ($code_point >= $range[1] && $code_point <= $range[2]) {
811                    return $range[0];
812                }
813            }
814            // Not a recognised script. Maybe punctuation, spacing, etc. Keep looking.
815            $pos += $chrlen;
816        }
817
818        return 'Latn';
819    }
820
821    /**
822     * Convert a number of seconds into a relative time. For example, 630 => "10 hours, 30 minutes ago"
823     *
824     * @param int $seconds
825     *
826     * @return string
827     */
828    public static function timeAgo($seconds)
829    {
830        $minute = 60;
831        $hour   = 60 * $minute;
832        $day    = 24 * $hour;
833        $month  = 30 * $day;
834        $year   = 365 * $day;
835
836        if ($seconds > $year) {
837            $years = (int)($seconds / $year);
838
839            return self::plural('%s year ago', '%s years ago', $years, self::number($years));
840        } elseif ($seconds > $month) {
841            $months = (int)($seconds / $month);
842
843            return self::plural('%s month ago', '%s months ago', $months, self::number($months));
844        } elseif ($seconds > $day) {
845            $days = (int)($seconds / $day);
846
847            return self::plural('%s day ago', '%s days ago', $days, self::number($days));
848        } elseif ($seconds > $hour) {
849            $hours = (int)($seconds / $hour);
850
851            return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours));
852        } elseif ($seconds > $minute) {
853            $minutes = (int)($seconds / $minute);
854
855            return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes));
856        } else {
857            return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds));
858        }
859    }
860
861    /**
862     * What format is used to display dates in the current locale?
863     *
864     * @return string
865     */
866    public static function timeFormat(): string
867    {
868        /* I18N: This is the format string for the time-of-day. See http://php.net/date for codes */
869        return self::$translator->translate('%H:%i:%s');
870    }
871
872    /**
873     * Translate a string, and then substitute placeholders
874     *
875     * echo I18N::translate('Hello World!');
876     * echo I18N::translate('The %s sat on the mat', 'cat');
877     *
878     * @return string
879     */
880    public static function translate(...$args): string
881    {
882        $args[0] = self::$translator->translate($args[0]);
883
884        return sprintf(...$args);
885    }
886
887    /**
888     * Context sensitive version of translate.
889     * echo I18N::translateContext('NOMINATIVE', 'January');
890     * echo I18N::translateContext('GENITIVE', 'January');
891     *
892     * @return string
893     */
894    public static function translateContext(...$args): string
895    {
896        $args[1] = self::$translator->translateContext($args[0], $args[1]);
897        unset($args[0]);
898
899        return sprintf(...$args);
900    }
901}
902