xref: /webtrees/app/I18N.php (revision 6bdf767435631ad1dc27ec1ffd855d43dbdce907)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2017 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;
30
31/**
32 * Internationalization (i18n) and localization (l10n).
33 */
34class I18N {
35	/** @var LocaleInterface The current locale (e.g. LocaleEnGb) */
36	private static $locale;
37
38	/** @var Translator An object that performs translation*/
39	private static $translator;
40
41	/** @var  Collator From the php-intl library */
42	private static $collator;
43
44	// Digits are always rendered LTR, even in RTL text.
45	const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹';
46
47	// These locales need special handling for the dotless letter I.
48	const DOTLESS_I_LOCALES = ['az', 'tr'];
49	const DOTLESS_I_TOLOWER = ['I' => 'ı', 'İ' => 'i'];
50	const DOTLESS_I_TOUPPER = ['ı' => 'I', 'i' => 'İ'];
51
52	// The ranges of characters used by each script.
53	const SCRIPT_CHARACTER_RANGES = [
54		['Latn', 0x0041, 0x005A],
55		['Latn', 0x0061, 0x007A],
56		['Latn', 0x0100, 0x02AF],
57		['Grek', 0x0370, 0x03FF],
58		['Cyrl', 0x0400, 0x052F],
59		['Hebr', 0x0590, 0x05FF],
60		['Arab', 0x0600, 0x06FF],
61		['Arab', 0x0750, 0x077F],
62		['Arab', 0x08A0, 0x08FF],
63		['Deva', 0x0900, 0x097F],
64		['Taml', 0x0B80, 0x0BFF],
65		['Sinh', 0x0D80, 0x0DFF],
66		['Thai', 0x0E00, 0x0E7F],
67		['Geor', 0x10A0, 0x10FF],
68		['Grek', 0x1F00, 0x1FFF],
69		['Deva', 0xA8E0, 0xA8FF],
70		['Hans', 0x3000, 0x303F], // Mixed CJK, not just Hans
71		['Hans', 0x3400, 0xFAFF], // Mixed CJK, not just Hans
72		['Hans', 0x20000, 0x2FA1F], // Mixed CJK, not just Hans
73	];
74
75	// Characters that are displayed in mirror form in RTL text.
76	const MIRROR_CHARACTERS = [
77		'(' => ')',
78		')' => '(',
79		'[' => ']',
80		']' => '[',
81		'{' => '}',
82		'}' => '{',
83		'<' => '>',
84		'>' => '<',
85		'‹' => '›',
86		'›' => '‹',
87		'«' => '»',
88		'»' => '«',
89		'﴾' => '﴿',
90		'﴿' => '﴾',
91		'“' => '”',
92		'”' => '“',
93		'‘' => '’',
94		'’' => '‘',
95	];
96
97	// Default list of locales to show in the menu.
98	const DEFAULT_LOCALES = [
99		'ar', 'bg', 'bs', 'ca', 'cs', 'da', 'de', 'el', 'en-GB', 'en-US', 'es',
100		'et', 'fi', 'fr', 'he', 'hr', 'hu', 'is', 'it', 'ka', 'lt', 'mr', 'nb',
101		'nl', 'nn', 'pl', 'pt', 'ru', 'sk', 'sv', 'tr', 'uk', 'vi', 'zh-Hans',
102	];
103
104	/** @var string Punctuation used to separate list items, typically a comma */
105	public static $list_separator;
106
107	/**
108	 * The prefered locales for this site, or a default list if no preference.
109	 *
110	 * @return LocaleInterface[]
111	 */
112	public static function activeLocales() {
113		$code_list = Site::getPreference('LANGUAGES');
114
115		if (empty($code_list)) {
116			$codes = self::DEFAULT_LOCALES;
117		} else {
118			$codes = explode(',', $code_list);
119		}
120
121		$locales = [];
122		foreach ($codes as $code) {
123			if (file_exists(WT_ROOT . 'language/' . $code . '.mo')) {
124				try {
125					$locales[] = Locale::create($code);
126				} catch (\Exception $ex) {
127					// No such locale exists?
128				}
129			}
130		}
131		usort($locales, '\Fisharebest\Localization\Locale::compare');
132
133		return $locales;
134	}
135
136	/**
137	 * Which MySQL collation should be used for this locale?
138	 *
139	 * @return string
140	 */
141	public static function collation() {
142		$collation = self::$locale->collation();
143		switch ($collation) {
144		case 'croatian_ci':
145		case 'german2_ci':
146		case 'vietnamese_ci':
147			// Only available in MySQL 5.6
148			return 'utf8_unicode_ci';
149		default:
150			return 'utf8_' . $collation;
151		}
152	}
153
154	/**
155	 * What format is used to display dates in the current locale?
156	 *
157	 * @return string
158	 */
159	public static function dateFormat() {
160		return /* I18N: This is the format string for full dates. See http://php.net/date for codes */ self::$translator->translate('%j %F %Y');
161	}
162
163	/**
164	 * Generate consistent I18N for datatables.js
165	 *
166	 * @param array|null $lengths An optional array of page lengths
167	 *
168	 * @return string
169	 */
170	public static function datatablesI18N(array $lengths = null) {
171		if ($lengths === null) {
172			$lengths = [10, 20, 30, 50, 100, -1];
173		}
174
175		$length_menu = '';
176		foreach ($lengths as $length) {
177			$length_menu .=
178				'<option value="' . $length . '">' .
179				($length === -1 ? /* I18N: listbox option, e.g. “10,25,50,100,all” */ self::translate('All') : self::number($length)) .
180				'</option>';
181		}
182		$length_menu = '<select>' . $length_menu . '</select>';
183		$length_menu = /* I18N: Display %s [records per page], %s is a placeholder for listbox containing numeric options */ self::translate('Display %s', $length_menu);
184
185		return
186			'"formatNumber": function(n) { return String(n).replace(/[0-9]/g, function(w) { return ("' . self::$locale->digits('0123456789') . '")[+w]; }); },' .
187			'"language": {' .
188			' "paginate": {' .
189			'  "first":    "' . /* I18N: A button label, first page */ self::translate('first') . '",' .
190			'  "last":     "' . /* I18N: A button label, last page */ self::translate('last') . '",' .
191			'  "next":     "' . /* I18N: A button label, next page */ self::translate('next') . '",' .
192			'  "previous": "' . /* I18N: A button label, previous page */ self::translate('previous') . '"' .
193			' },' .
194			' "emptyTable":     "' . self::translate('No records to display') . '",' .
195			' "info":           "' . /* I18N: %s are placeholders for numbers */ self::translate('Showing %1$s to %2$s of %3$s', '_START_', '_END_', '_TOTAL_') . '",' .
196			' "infoEmpty":      "' . self::translate('Showing %1$s to %2$s of %3$s', self::$locale->digits('0'), self::$locale->digits('0'), self::$locale->digits('0')) . '",' .
197			' "infoFiltered":   "' . /* I18N: %s is a placeholder for a number */ self::translate('(filtered from %s total entries)', '_MAX_') . '",' .
198			' "lengthMenu":     "' . Filter::escapeJs($length_menu) . '",' .
199			' "loadingRecords": "' . self::translate('Loading…') . '",' .
200			' "processing":     "' . self::translate('Loading…') . '",' .
201			' "search":         "' . self::translate('Filter') . '",' .
202			' "zeroRecords":    "' . self::translate('No records to display') . '"' .
203			'}';
204	}
205
206	/**
207	 * Convert the digits 0-9 into the local script
208	 *
209	 * Used for years, etc., where we do not want thousands-separators, decimals, etc.
210	 *
211	 * @param int $n
212	 *
213	 * @return string
214	 */
215	public static function digits($n) {
216		return self::$locale->digits($n);
217	}
218
219	/**
220	 * What is the direction of the current locale
221	 *
222	 * @return string "ltr" or "rtl"
223	 */
224	public static function direction() {
225		return self::$locale->direction();
226	}
227
228	/**
229	 * What is the first day of the week.
230	 *
231	 * @return int Sunday=0, Monday=1, etc.
232	 */
233	public static function firstDay() {
234		return self::$locale->territory()->firstDay();
235	}
236
237	/**
238	 * Convert a GEDCOM age string into translated_text
239	 *
240	 * NB: The import function will have normalised this, so we don't need
241	 * to worry about badly formatted strings
242	 * NOTE: this function is not yet complete - eventually it will replace FunctionsDate::get_age_at_event()
243	 *
244	 * @param $string
245	 *
246	 * @return string
247	 */
248	public static function gedcomAge($string) {
249		switch ($string) {
250		case 'STILLBORN':
251			// I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (stillborn)
252			return self::translate('(stillborn)');
253		case 'INFANT':
254			// I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in infancy)
255			return self::translate('(in infancy)');
256		case 'CHILD':
257			// I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (in childhood)
258			return self::translate('(in childhood)');
259		}
260		$age = [];
261		if (preg_match('/(\d+)y/', $string, $match)) {
262			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
263			$years = $match[1];
264			$age[] = self::plural('%s year', '%s years', $years, self::number($years));
265		} else {
266			$years = -1;
267		}
268		if (preg_match('/(\d+)m/', $string, $match)) {
269			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
270			$age[] = self::plural('%s month', '%s months', $match[1], self::number($match[1]));
271		}
272		if (preg_match('/(\d+)w/', $string, $match)) {
273			// I18N: Part of an age string. e.g. 7 weeks and 3 days
274			$age[] = self::plural('%s week', '%s weeks', $match[1], self::number($match[1]));
275		}
276		if (preg_match('/(\d+)d/', $string, $match)) {
277			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
278			$age[] = self::plural('%s day', '%s days', $match[1], self::number($match[1]));
279		}
280		// If an age is just a number of years, only show the number
281		if (count($age) === 1 && $years >= 0) {
282			$age = $years;
283		}
284		if ($age) {
285			if (!substr_compare($string, '<', 0, 1)) {
286				// I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged less than 21 years)
287				return self::translate('(aged less than %s)', $age);
288			} elseif (!substr_compare($string, '>', 0, 1)) {
289				// I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged more than 21 years)
290				return self::translate('(aged more than %s)', $age);
291			} else {
292				// I18N: Description of an individual’s age at an event. For example, Died 14 Jan 1900 (aged 43 years)
293				return self::translate('(aged %s)', $age);
294			}
295		} else {
296			// Not a valid string?
297			return self::translate('(aged %s)', $string);
298		}
299	}
300
301	/**
302	 * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl"
303	 *
304	 * @return string
305	 */
306	public static function htmlAttributes() {
307		return self::$locale->htmlAttributes();
308	}
309
310	/**
311	 * Initialise the translation adapter with a locale setting.
312	 *
313	 * @param string|null $code Use this locale/language code, or choose one automatically
314	 *
315	 * @return string $string
316	 */
317	public static function init($code = null) {
318		global $WT_TREE;
319
320		mb_internal_encoding('UTF-8');
321
322		if ($code !== null) {
323			// Create the specified locale
324			self::$locale = Locale::create($code);
325		} else {
326			// Negotiate a locale, but if we can't then use a failsafe
327			self::$locale = new LocaleEnUs;
328			if (Session::has('locale')) {
329				// Previously used
330				self::$locale = Locale::create(Session::get('locale'));
331			} else {
332				// Browser negotiation
333				$default_locale = new LocaleEnUs;
334				try {
335					if ($WT_TREE) {
336						$default_locale = Locale::create($WT_TREE->getPreference('LANGUAGE'));
337					}
338				} catch (\Exception $ex) {
339				}
340				self::$locale = Locale::httpAcceptLanguage($_SERVER, self::installedLocales(), $default_locale);
341			}
342		}
343
344		$cache_dir  = WT_DATA_DIR . 'cache/';
345		$cache_file = $cache_dir . 'language-' . self::$locale->languageTag() . '-cache.php';
346		if (file_exists($cache_file)) {
347			$filemtime = filemtime($cache_file);
348		} else {
349			$filemtime = 0;
350		}
351
352		// Load the translation file(s)
353		// Note that glob() returns false instead of an empty array when open_basedir_restriction
354		// is in force and no files are found. See PHP bug #47358.
355		if (defined('GLOB_BRACE')) {
356			$translation_files = array_merge(
357				[WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'],
358				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: [],
359				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: []
360			);
361		} else {
362			// Some servers do not have GLOB_BRACE - see http://php.net/manual/en/function.glob.php
363			$translation_files = array_merge(
364				[WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'],
365				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.csv') ?: [],
366				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.php') ?: [],
367				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.mo') ?: [],
368				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.csv') ?: [],
369				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.php') ?: [],
370				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.mo') ?: []
371			);
372		}
373		// Rebuild files after one hour
374		$rebuild_cache = time() > $filemtime + 3600;
375		// Rebuild files if any translation file has been updated
376		foreach ($translation_files as $translation_file) {
377			if (filemtime($translation_file) > $filemtime) {
378				$rebuild_cache = true;
379				break;
380			}
381		}
382
383		if ($rebuild_cache) {
384			$translations = [];
385			foreach ($translation_files as $translation_file) {
386				$translation  = new Translation($translation_file);
387				$translations = array_merge($translations, $translation->asArray());
388			}
389			try {
390				File::mkdir($cache_dir);
391				file_put_contents($cache_file, '<?php return ' . var_export($translations, true) . ';');
392			} catch (Exception $ex) {
393				// During setup, we may not have been able to create it.
394			}
395		} else {
396			$translations = include $cache_file;
397		}
398
399		// Create a translator
400		self::$translator = new Translator($translations, self::$locale->pluralRule());
401
402		self::$list_separator = /* I18N: This punctuation is used to separate lists of items */ self::translate(', ');
403
404		// Create a collator
405		try {
406			// PHP 5.6 cannot catch errors, so test first
407			if (class_exists('Collator')) {
408				self::$collator = new Collator(self::$locale->code());
409				// Ignore upper/lower case differences
410				self::$collator->setStrength(Collator::SECONDARY);
411			}
412		} catch (Exception $ex) {
413			// PHP-INTL is not installed?  We'll use a fallback later.
414		}
415
416		return self::$locale->languageTag();
417	}
418
419	/**
420	 * All locales for which a translation file exists.
421	 *
422	 * @return LocaleInterface[]
423	 */
424	public static function installedLocales() {
425		$locales = [];
426		foreach (glob(WT_ROOT . 'language/*.mo') as $file) {
427			try {
428				$locales[] = Locale::create(basename($file, '.mo'));
429			} catch (\Exception $ex) {
430				// Not a recognised locale
431			}
432		}
433		usort($locales, '\Fisharebest\Localization\Locale::compare');
434
435		return $locales;
436	}
437
438	/**
439	 * Return the endonym for a given language - as per http://cldr.unicode.org/
440	 *
441	 * @param string $locale
442	 *
443	 * @return string
444	 */
445	public static function languageName($locale) {
446		return Locale::create($locale)->endonym();
447	}
448
449	/**
450	 * Return the script used by a given language
451	 *
452	 * @param string $locale
453	 *
454	 * @return string
455	 */
456	public static function languageScript($locale) {
457		return Locale::create($locale)->script()->code();
458	}
459
460	/**
461	 * Translate a number into the local representation.
462	 *
463	 * e.g. 12345.67 becomes
464	 * en: 12,345.67
465	 * fr: 12 345,67
466	 * de: 12.345,67
467	 *
468	 * @param float $n
469	 * @param int   $precision
470	 *
471	 * @return string
472	 */
473	public static function number($n, $precision = 0) {
474		return self::$locale->number(round($n, $precision));
475	}
476
477	/**
478	 * Translate a fraction into a percentage.
479	 *
480	 * e.g. 0.123 becomes
481	 * en: 12.3%
482	 * fr: 12,3 %
483	 * de: 12,3%
484	 *
485	 * @param float $n
486	 * @param int   $precision
487	 *
488	 * @return string
489	 */
490	public static function percentage($n, $precision = 0) {
491		return self::$locale->percent(round($n, $precision + 2));
492	}
493
494	/**
495	 * Translate a plural string
496	 *
497	 * echo self::plural('There is an error', 'There are errors', $num_errors);
498	 * echo self::plural('There is one error', 'There are %s errors', $num_errors);
499	 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour);
500	 *
501	 * @return string
502	 */
503	public static function plural(/* var_args */) {
504		$args    = func_get_args();
505		$args[0] = self::$translator->translatePlural($args[0], $args[1], (int) $args[2]);
506		unset($args[1], $args[2]);
507
508		return self::substitutePlaceholders($args);
509	}
510
511	/**
512	 * UTF8 version of PHP::strrev()
513	 *
514	 * Reverse RTL text for third-party libraries such as GD2 and googlechart.
515	 *
516	 * These do not support UTF8 text direction, so we must mimic it for them.
517	 *
518	 * Numbers are always rendered LTR, even in RTL text.
519	 * The visual direction of characters such as parentheses should be reversed.
520	 *
521	 * @param string $text Text to be reversed
522	 *
523	 * @return string
524	 */
525	public static function reverseText($text) {
526		// Remove HTML markup - we can't display it and it is LTR.
527		$text = Filter::unescapeHtml($text);
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