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