xref: /webtrees/app/I18N.php (revision 15d603e7c7c15d20f055d3d9c38d6b133453c5be)
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":     "' . Filter::escapeJs(/* I18N: %s is a number of records per page */ self::translate('Display %s', $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')) {
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 = Filter::unescapeHtml($text);
517
518		// LTR text doesn't need reversing
519		if (self::scriptDirection(self::textScript($text)) === 'ltr') {
520			return $text;
521		}
522
523		// Mirrored characters
524		$text = strtr($text, self::MIRROR_CHARACTERS);
525
526		$reversed = '';
527		$digits   = '';
528		while ($text != '') {
529			$letter = mb_substr($text, 0, 1);
530			$text   = mb_substr($text, 1);
531			if (strpos(self::DIGITS, $letter) !== false) {
532				$digits .= $letter;
533			} else {
534				$reversed = $letter . $digits . $reversed;
535				$digits   = '';
536			}
537		}
538
539		return $digits . $reversed;
540	}
541
542	/**
543	 * Return the direction (ltr or rtl) for a given script
544	 *
545	 * The PHP/intl library does not provde this information, so we need
546	 * our own lookup table.
547	 *
548	 * @param string $script
549	 *
550	 * @return string
551	 */
552	public static function scriptDirection($script) {
553		switch ($script) {
554		case 'Arab':
555		case 'Hebr':
556		case 'Mong':
557		case 'Thaa':
558			return 'rtl';
559		default:
560			return 'ltr';
561		}
562	}
563
564	/**
565	 * Perform a case-insensitive comparison of two strings.
566	 *
567	 * @param string $string1
568	 * @param string $string2
569	 *
570	 * @return int
571	 */
572	public static function strcasecmp($string1, $string2) {
573		if (self::$collator instanceof Collator) {
574			return self::$collator->compare($string1, $string2);
575		} else {
576			return strcmp(self::strtolower($string1), self::strtolower($string2));
577		}
578	}
579
580	/**
581	 * Convert a string to lower case.
582	 *
583	 * @param string $string
584	 *
585	 * @return string
586	 */
587	public static function strtolower($string) {
588		if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) {
589			$string = strtr($string, self::DOTLESS_I_TOLOWER);
590		}
591
592		return mb_strtolower($string);
593	}
594
595	/**
596	 * Convert a string to upper case.
597	 *
598	 * @param string $string
599	 *
600	 * @return string
601	 */
602	public static function strtoupper($string) {
603		if (in_array(self::$locale->language()->code(), self::DOTLESS_I_LOCALES)) {
604			$string = strtr($string, self::DOTLESS_I_TOUPPER);
605		}
606
607		return mb_strtoupper($string);
608	}
609
610	/**
611	 * Substitute any "%s" placeholders in a translated string.
612	 * This also allows us to have translated strings that contain
613	 * "%" characters, which can't be passed to sprintf.
614	 *
615	 * @param string[] $args translated string plus optional parameters
616	 *
617	 * @return string
618	 */
619	private static function substitutePlaceholders(array $args) {
620		if (count($args) > 1) {
621			return call_user_func_array('sprintf', $args);
622		} else {
623			return $args[0];
624		}
625	}
626
627	/**
628	 * Identify the script used for a piece of text
629	 *
630	 * @param $string
631	 *
632	 * @return string
633	 */
634	public static function textScript($string) {
635		$string = strip_tags($string); // otherwise HTML tags show up as latin
636		$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin
637		$string = str_replace(['@N.N.', '@P.N.'], '', $string); // otherwise unknown names show up as latin
638		$pos    = 0;
639		$strlen = strlen($string);
640		while ($pos < $strlen) {
641			// get the Unicode Code Point for the character at position $pos
642			$byte1 = ord($string[$pos]);
643			if ($byte1 < 0x80) {
644				$code_point = $byte1;
645				$chrlen     = 1;
646			} elseif ($byte1 < 0xC0) {
647				// Invalid continuation character
648				return 'Latn';
649			} elseif ($byte1 < 0xE0) {
650				$code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F);
651				$chrlen     = 2;
652			} elseif ($byte1 < 0xF0) {
653				$code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F);
654				$chrlen     = 3;
655			} elseif ($byte1 < 0xF8) {
656				$code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F);
657				$chrlen     = 3;
658			} else {
659				// Invalid UTF
660				return 'Latn';
661			}
662
663			foreach (self::SCRIPT_CHARACTER_RANGES as $range) {
664				if ($code_point >= $range[1] && $code_point <= $range[2]) {
665					return $range[0];
666				}
667			}
668			// Not a recognised script. Maybe punctuation, spacing, etc. Keep looking.
669			$pos += $chrlen;
670		}
671
672		return 'Latn';
673	}
674
675	/**
676	 * Convert a number of seconds into a relative time. For example, 630 => "10 hours, 30 minutes ago"
677	 *
678	 * @param int $seconds
679	 *
680	 * @return string
681	 */
682	public static function timeAgo($seconds) {
683		$minute = 60;
684		$hour   = 60 * $minute;
685		$day    = 24 * $hour;
686		$month  = 30 * $day;
687		$year   = 365 * $day;
688
689		if ($seconds > $year) {
690			$years = (int) ($seconds / $year);
691
692			return self::plural('%s year ago', '%s years ago', $years, self::number($years));
693		} elseif ($seconds > $month) {
694			$months = (int) ($seconds / $month);
695
696			return self::plural('%s month ago', '%s months ago', $months, self::number($months));
697		} elseif ($seconds > $day) {
698			$days = (int) ($seconds / $day);
699
700			return self::plural('%s day ago', '%s days ago', $days, self::number($days));
701		} elseif ($seconds > $hour) {
702			$hours = (int) ($seconds / $hour);
703
704			return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours));
705		} elseif ($seconds > $minute) {
706			$minutes = (int) ($seconds / $minute);
707
708			return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes));
709		} else {
710			return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds));
711		}
712	}
713
714	/**
715	 * What format is used to display dates in the current locale?
716	 *
717	 * @return string
718	 */
719	public static function timeFormat() {
720		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');
721	}
722
723	/**
724	 * Translate a string, and then substitute placeholders
725	 *
726	 * echo I18N::translate('Hello World!');
727	 * echo I18N::translate('The %s sat on the mat', 'cat');
728	 *
729	 * @return string
730	 */
731	public static function translate(/* var_args */) {
732		$args    = func_get_args();
733		$args[0] = self::$translator->translate($args[0]);
734
735		return self::substitutePlaceholders($args);
736	}
737
738	/**
739	 * Context sensitive version of translate.
740	 *
741	 * echo I18N::translateContext('NOMINATIVE', 'January');
742	 * echo I18N::translateContext('GENITIVE', 'January');
743	 *
744	 * @return string
745	 */
746	public static function translateContext(/* var_args */) {
747		$args    = func_get_args();
748		$args[0] = self::$translator->translateContext($args[0], $args[1]);
749		unset($args[1]);
750
751		return self::substitutePlaceholders($args);
752	}
753
754	/**
755	 * What is the last day of the weekend.
756	 *
757	 * @return int Sunday=0, Monday=1, etc.
758	 */
759	public static function weekendEnd() {
760		return self::$locale->territory()->weekendEnd();
761	}
762
763	/**
764	 * What is the first day of the weekend.
765	 *
766	 * @return int Sunday=0, Monday=1, etc.
767	 */
768	public static function weekendStart() {
769		return self::$locale->territory()->weekendStart();
770	}
771
772	/**
773	 * Which calendar prefered in this locale?
774	 *
775	 * @return CalendarInterface
776	 */
777	public static function defaultCalendar() {
778		switch (self::$locale->languageTag()) {
779		case 'ar':
780			return new ArabicCalendar;
781		case 'fa':
782			return new PersianCalendar;
783		case 'he':
784		case 'yi':
785			return new JewishCalendar;
786		default:
787			return new GregorianCalendar;
788		}
789	}
790}
791