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