xref: /webtrees/app/I18N.php (revision 1e71bdc0ba6fc5add8fed9a3beb51cfca09e47dd)
1<?php
2namespace Fisharebest\Webtrees;
3
4/**
5 * webtrees: online genealogy
6 * Copyright (C) 2015 webtrees development team
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19use Fisharebest\Localization\Locale;
20use Fisharebest\Localization\Locale\LocaleEnUs;
21use Fisharebest\Localization\Translation;
22use Fisharebest\Localization\Translator;
23use Patchwork\TurkishUtf8;
24
25/**
26 * Class I18N - Functions to support internationalization (i18n) functionality.
27 */
28class I18N {
29	/** @var Locale The current locale (e.g. LocaleEnGb) */
30	private static $locale;
31
32	/** @var Translator */
33	private static $translator;
34
35	// Digits are always rendered LTR, even in RTL text.
36	const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹';
37
38	// Reversable character conversions from the UNICODE 5.1 database.
39	// It excludes ambiguous (turkish dotless i) and mixed-case (Dz) characters.
40	// The characters should be arranged in default unicode-collation order.
41	const ALPHABET_LOWER = 'aàáâãäåāăąǎǟǡǻȁȃȧḁạảấầẩẫậắằẳẵặⓐaæǣǽbḃḅḇⓑbƀɓƃcçćĉċčḉⅽⓒcƈdďḋḍḏḑḓⅾⓓddždzđɖɗƌðeèéêëēĕėęěȅȇȩḕḗḙḛḝẹẻẽếềểễệⓔeǝəɛfḟⓕfƒgĝğġģǧǵḡⓖgǥɠɣƣhĥȟḣḥḧḩḫⓗhƕħiìíîïĩīĭįǐȉȋḭḯỉịⅰⓘiⅱⅲijⅳⅸɨɩjĵⓙjkķǩḱḳḵⓚkƙlĺļľḷḹḻḽⅼⓛlŀljłƚmḿṁṃⅿⓜmnñńņňǹṅṇṉṋⓝnnjɲƞŋoòóôõöōŏőơǒǫǭȍȏȫȭȯȱṍṏṑṓọỏốồổỗộớờởỡợⓞoœøǿɔɵȣpṕṗⓟpƥqⓠqrŕŗřȑȓṙṛṝṟⓡrʀsśŝşšșṡṣṥṧṩⓢsʃtţťțṫṭṯṱⓣtŧƭʈuùúûüũūŭůűųưǔǖǘǚǜȕȗṳṵṷṹṻụủứừửữựⓤuʉɯʊvṽṿⅴⓥvⅵⅶⅷʋʌwŵẁẃẅẇẉⓦwxẋẍⅹⓧxⅺⅻyýÿŷȳẏỳỵỷỹⓨyƴzźżžẑẓẕⓩzƶȥǯʒƹȝþƿƨƽƅάαἀἁἂἃἄἅἆἇὰάᾀᾁᾂᾃᾄᾅᾆᾇᾰᾱᾳβγδέεἐἑἒἓἔἕὲέϝϛζήηἠἡἢἣἤἥἦἧὴήᾐᾑᾒᾓᾔᾕᾖᾗῃθϊἰἱἲἳἴἵἶἷὶίῐῑκϗλμνξοόὀὁὂὃὄὅὸόπϟϙρῥσϲτυϋύὑὓὕὗὺύῠῡφχψωώὠὡὢὣὤὥὦὧὼώᾠᾡᾢᾣᾤᾥᾦᾧῳϡϸϻϣϥϧϩϫϭϯаӑӓәӛӕбвгґғҕдԁђԃѓҙеѐёӗєжӂӝҗзԅӟѕӡԇиѝӣҋӥіїйјкқӄҡҟҝлӆљԉмӎнӊңӈҥњԋоӧөӫпҧҁрҏсԍҫтԏҭћќуӯўӱӳүұѹфхҳһѡѿѽѻцҵчӵҷӌҹҽҿџшщъыӹьҍѣэӭюяѥѧѫѩѭѯѱѳѵѷҩաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆȼɂɇɉɋɍɏͱͳͷͻͼͽӏӷӻӽӿԑԓԕԗԙԛԝԟԡԣԥᵹᵽỻỽỿⅎↄⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡⱨⱪⱬⱳⱶⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⴀⴁⴂⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌⴍⴎⴏⴐⴑⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜⴝⴞⴟⴠⴡⴢⴣⴤⴥꙁꙃꙅꙇꙉꙋꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼꝿꞁꞃꞅꞇꞌ';
42	const ALPHABET_UPPER = 'AÀÁÂÃÄÅĀĂĄǍǞǠǺȀȂȦḀẠẢẤẦẨẪẬẮẰẲẴẶⒶAÆǢǼBḂḄḆⒷBɃƁƂCÇĆĈĊČḈⅭⒸCƇDĎḊḌḎḐḒⅮⒹDDŽDZĐƉƊƋÐEÈÉÊËĒĔĖĘĚȄȆȨḔḖḘḚḜẸẺẼẾỀỂỄỆⒺEƎƏƐFḞⒻFƑGĜĞĠĢǦǴḠⒼGǤƓƔƢHĤȞḢḤḦḨḪⒽHǶĦIÌÍÎÏĨĪĬĮǏȈȊḬḮỈỊⅠⒾIⅡⅢIJⅣⅨƗƖJĴⒿJKĶǨḰḲḴⓀKƘLĹĻĽḶḸḺḼⅬⓁLĿLJŁȽMḾṀṂⅯⓂMNÑŃŅŇǸṄṆṈṊⓃNNJƝȠŊOÒÓÔÕÖŌŎŐƠǑǪǬȌȎȪȬȮȰṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢⓄOŒØǾƆƟȢPṔṖⓅPƤQⓆQRŔŖŘȐȒṘṚṜṞⓇRƦSŚŜŞŠȘṠṢṤṦṨⓈSƩTŢŤȚṪṬṮṰⓉTŦƬƮUÙÚÛÜŨŪŬŮŰŲƯǓǕǗǙǛȔȖṲṴṶṸṺỤỦỨỪỬỮỰⓊUɄƜƱVṼṾⅤⓋVⅥⅦⅧƲɅWŴẀẂẄẆẈⓌWXẊẌⅩⓍXⅪⅫYÝŸŶȲẎỲỴỶỸⓎYƳZŹŻŽẐẒẔⓏZƵȤǮƷƸȜÞǷƧƼƄΆΑἈἉἊἋἌἍἎἏᾺΆᾈᾉᾊᾋᾌᾍᾎᾏᾸᾹᾼΒΓΔΈΕἘἙἚἛἜἝῈΈϜϚΖΉΗἨἩἪἫἬἭἮἯῊΉᾘᾙᾚᾛᾜᾝᾞᾟῌΘΪἸἹἺἻἼἽἾἿῚΊῘῙΚϏΛΜΝΞΟΌὈὉὊὋὌὍῸΌΠϞϘΡῬΣϹΤΥΫΎὙὛὝὟῪΎῨῩΦΧΨΩΏὨὩὪὫὬὭὮὯῺΏᾨᾩᾪᾫᾬᾭᾮᾯῼϠϷϺϢϤϦϨϪϬϮАӐӒӘӚӔБВГҐҒҔДԀЂԂЃҘЕЀЁӖЄЖӁӜҖЗԄӞЅӠԆИЍӢҊӤІЇЙЈКҚӃҠҞҜЛӅЉԈМӍНӉҢӇҤЊԊОӦӨӪПҦҀРҎСԌҪТԎҬЋЌУӮЎӰӲҮҰѸФХҲҺѠѾѼѺЦҴЧӴҶӋҸҼҾЏШЩЪЫӸЬҌѢЭӬЮЯѤѦѪѨѬѮѰѲѴѶҨԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖȻɁɆɈɊɌɎͰͲͶϽϾϿӀӶӺӼӾԐԒԔԖԘԚԜԞԠԢԤꝽⱣỺỼỾℲↃⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮⱠⱧⱩⱫⱲⱵⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢⳫⳭႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅꙀꙂꙄꙆꙈꙊꙌꙎꙐꙒꙔꙖꙘꙚꙜꙞꙢꙤꙦꙨꙪꙬꚀꚂꚄꚆꚈꚊꚌꚎꚐꚒꚔꚖꜢꜤꜦꜨꜪꜬꜮꜲꜴꜶꜸꜺꜼꜾꝀꝂꝄꝆꝈꝊꝌꝎꝐꝒꝔꝖꝘꝚꝜꝞꝠꝢꝤꝦꝨꝪꝬꝮꝹꝻꝾꞀꞂꞄꞆꞋ';
43
44	// Alphabet for the currently selected locale
45	private static $alphabet_lower = 'abcdefghijklmnopqrstuvwxyz';
46	private static $alphabet_upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
47
48	// Lookup table to convert unicode code-points into scripts.
49	// See https://en.wikipedia.org/wiki/Unicode_block
50	// Note: we only need details for scripts of languages into which webtrees is translated.
51	private static $scripts = array(
52		array('Latn', 0x0041, 0x005A), // a-z
53		array('Latn', 0x0061, 0x007A), // A-Z
54		array('Latn', 0x0100, 0x02AF),
55		array('Grek', 0x0370, 0x03FF),
56		array('Cyrl', 0x0400, 0x052F),
57		array('Hebr', 0x0590, 0x05FF),
58		array('Arab', 0x0600, 0x06FF),
59		array('Arab', 0x0750, 0x077F),
60		array('Arab', 0x08A0, 0x08FF),
61		array('Deva', 0x0900, 0x097F),
62		array('Taml', 0x0B80, 0x0BFF),
63		array('Sinh', 0x0D80, 0x0DFF),
64		array('Thai', 0x0E00, 0x0E7F),
65		array('Geor', 0x10A0, 0x10FF),
66		array('Grek', 0x1F00, 0x1FFF),
67		array('Deva', 0xA8E0, 0xA8FF),
68		array('Hans', 0x3000, 0x303F), // Mixed CJK, not just Hans
69		array('Hans', 0x3400, 0xFAFF), // Mixed CJK, not just Hans
70		array('Hans', 0x20000, 0x2FA1F), // Mixed CJK, not just Hans
71	);
72
73	// Characters that are displayed in mirror form in RTL text.
74	private static $mirror_characters = array(
75		'(' => ')',
76		')' => '(',
77		'[' => ']',
78		']' => '[',
79		'{' => '}',
80		'}' => '{',
81		'<' => '>',
82		'>' => '<',
83		'‹' => '›',
84		'›' => '‹',
85		'«' => '»',
86		'»' => '«',
87		'﴾' => '﴿',
88		'﴿' => '﴾',
89		'“' => '”',
90		'”' => '“',
91		'‘' => '’',
92		'’' => '‘',
93	);
94
95	/** @var string Punctuation used to separate list items, typically a comma */
96	public static $list_separator;
97
98	/**
99	 * Initialise the translation adapter with a locale setting.
100	 *
101	 * @param string|null $code Use this locale/language code, or choose one automatically
102	 *
103	 * @return string $string
104	 */
105	public static function init($code = null) {
106		global $WT_SESSION, $WT_TREE;
107
108		if ($code !== null) {
109			// Create the specified locale
110			self::$locale = Locale::create($code);
111		} else {
112			// Negotiate a locale, but if we can't then use a failsafe
113			self::$locale = new LocaleEnUs;
114			if (Filter::get('lang')) {
115				// A request in the URL
116				try {
117					$locale = Locale::create(Filter::get('lang'));
118					if (file_exists(WT_ROOT . 'language/' . $locale->languageTag() . '.mo')) {
119						self::$locale = $locale;
120					}
121				} catch (\Exception $ex) {
122				}
123			} elseif ($WT_SESSION->locale) {
124				// Previously used
125				self::$locale = Locale::create($WT_SESSION->locale);
126			} else {
127				// Browser negotiation
128				$default_locale = new LocaleEnUs;
129				try {
130					if ($WT_TREE) {
131						$default_locale = Locale::create($WT_TREE->getPreference('LANGUAGE'));
132					}
133				} catch (\Exception $ex) {
134				}
135				self::$locale = Locale::httpAcceptLanguage($_SESSION, self::installedLocales(), $default_locale);
136			}
137		}
138
139		File::mkdir(WT_DATA_DIR . 'cache');
140		$cache_file = WT_DATA_DIR . 'cache/language-' . self::$locale->languageTag() . '-cache.php';
141		if (file_exists($cache_file)) {
142			$filemtime = filemtime($cache_file);
143		} else {
144			$filemtime = 0;
145		}
146
147		// Load the translation file(s)
148		// Note that glob() returns false instead of an empty array when open_basedir_restriction
149		// is in force and no files are found.  See PHP bug #47358.
150		$translation_files = array_merge(
151			array(WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'),
152			glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: array(),
153			glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: array()
154		);
155
156		// Rebuild files after 2 hours
157		$rebuild_cache = time() > $filemtime + 7200;
158		// Rebuild files if any translation file has been updated
159		foreach ($translation_files as $translation_file) {
160			if (filemtime($translation_file) > $filemtime) {
161				$rebuild_cache = true;
162				break;
163			}
164		}
165
166		if ($rebuild_cache) {
167			$translations = array();
168			foreach ($translation_files as $translation_file) {
169				$translation = new Translation($translation_file);
170				$translations = array_merge($translations, $translation->asArray());
171			}
172			file_put_contents($cache_file, '<' . '?php return ' . var_export($translations, true) . ';');
173		} else {
174			$translations = include $cache_file;
175		}
176
177		// Create a translator
178		self::$translator = new Translator($translations, self::$locale->pluralRule());
179
180		// Extract language settings from the translation file
181		global $DATE_FORMAT; // I18N: This is the format string for full dates.  See http://php.net/date for codes
182		$DATE_FORMAT = self::$translator->translate('%j %F %Y');
183
184		global $TIME_FORMAT; // I18N: This is the format string for the time-of-day.  See http://php.net/date for codes
185		$TIME_FORMAT = self::$translator->translate('%H:%i:%s');
186
187		// Alphabetic sorting sequence (upper-case letters), used by webtrees to sort strings
188		list(, self::$alphabet_upper) = explode('=', self::$translator->translate('ALPHABET_upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
189		// Alphabetic sorting sequence (lower-case letters), used by webtrees to sort strings
190		list(, self::$alphabet_lower) = explode('=', self::$translator->translate('ALPHABET_lower=abcdefghijklmnopqrstuvwxyz'));
191
192		global $WEEK_START;
193		$WEEK_START = self::$locale->territory()->firstDay();
194
195		self::$list_separator = /* I18N: This punctuation is used to separate lists of items */ self::translate(', ');
196
197		return self::$locale->languageTag();
198	}
199
200	/**
201	 * The prefered locales for this site, or a default list if no preference.
202	 *
203	 * @return Locale[]
204	 */
205	public static function activeLocales() {
206		$code_list = Site::getPreference('LANGUAGES');
207
208		if ($code_list) {
209			$codes = explode(',', $code_list);
210		} else {
211			$codes = array(
212				'ar', 'bg', 'bs', 'ca', 'cs', 'da', 'de', 'el', 'en-GB', 'en-US', 'es',
213				'et', 'fi', 'fr', 'he', 'hr', 'hu', 'is', 'it', 'ka', 'lt', 'mr', 'nb',
214				'nl', 'nn', 'pl', 'pt', 'ru', 'sk', 'sv', 'tr', 'uk', 'vi', 'zh-Hans',
215			);
216		}
217
218		$locales = array();
219		foreach ($codes as $code) {
220			if (file_exists(WT_ROOT . 'language/' . $code . '.mo')) {
221				try {
222					$locales[] = Locale::create($code);
223				} catch (\Exception $ex) {
224					// No such locale exists?
225				}
226			}
227		}
228		usort($locales, '\Fisharebest\Localization\Locale::compare');
229
230		return $locales;
231	}
232
233	/**
234	 * Which MySQL collation should be used for this locale?
235	 *
236	 * @return string
237	 */
238	public static function collation() {
239		$collation = self::$locale->collation();
240		switch ($collation) {
241		case 'croatian_ci':
242		case 'german2_ci':
243		case 'vietnamese_ci':
244			// Only available in MySQL 5.6
245			return 'utf8_unicode_ci';
246		default:
247			return 'utf8_' . $collation;
248		}
249	}
250
251	/**
252	 * All locales for which a translation file exists.
253	 *
254	 * @return Locale[]
255	 */
256	public static function installedLocales() {
257		$locales = array();
258		foreach (glob(WT_ROOT . 'language/*.mo') as $file) {
259			try {
260				$locales[] = Locale::create(basename($file, '.mo'));
261			} catch (\Exception $ex) {
262				// Not a recognised locale
263			}
264		}
265		usort($locales, '\Fisharebest\Localization\Locale::compare');
266
267		return $locales;
268	}
269
270	/**
271	 * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl"
272	 *
273	 * @return string
274	 */
275	public static function htmlAttributes() {
276		return self::$locale->htmlAttributes();
277	}
278
279	/**
280	 * Translate a number into the local representation.
281	 *
282	 * e.g. 12345.67 becomes
283	 * en: 12,345.67
284	 * fr: 12 345,67
285	 * de: 12.345,67
286	 *
287	 * @param float   $n
288	 * @param integer $precision
289	 *
290	 * @return string
291	 */
292	public static function number($n, $precision = 0) {
293		return self::$locale->number(round($n, $precision));
294	}
295
296	/**
297	 * Convert the digits 0-9 into the local script
298	 *
299	 * Used for years, etc., where we do not want thousands-separators, decimals, etc.
300	 *
301	 * @param integer $n
302	 *
303	 * @return string
304	 */
305	public static function digits($n) {
306		return self::$locale->digits($n);
307	}
308
309	/**
310	 * Translate a fraction into a percentage.
311	 *
312	 * e.g. 0.123 becomes
313	 * en: 12.3%
314	 * fr: 12,3 %
315	 * de: 12,3%
316	 *
317	 * @param float   $n
318	 * @param integer $precision
319	 *
320	 * @return string
321	 */
322	public static function percentage($n, $precision = 0) {
323		return self::$locale->percent(round($n, $precision + 2));
324	}
325
326	/**
327	 * What is the direction of the current locale
328	 *
329	 * @return string "ltr" or "rtl"
330	 */
331	public static function direction() {
332		return self::$locale->direction();
333	}
334
335	/**
336	 * Translate a string, and then substitute placeholders
337	 *
338	 * echo I18N::translate('Hello World!');
339	 * echo I18N::translate('The %s sat on the mat', 'cat');
340	 *
341	 * @return string
342	 */
343	public static function translate(/* var_args */) {
344		$args = func_get_args();
345		$args[0] = self::$translator->translate($args[0]);
346
347		return call_user_func_array('sprintf', $args);
348	}
349
350	/**
351	 * Context sensitive version of translate.
352	 *
353	 * echo I18N::translate_c('NOMINATIVE', 'January');
354	 * echo I18N::translate_c('GENITIVE',   'January');
355	 *
356	 * @return string
357	 */
358	public static function translateContext(/* var_args */) {
359		$args = func_get_args();
360		$args[0] = self::$translator->translateContext($args[0], $args[1]);
361		unset($args[1]);
362
363		return call_user_func_array('sprintf', $args);
364	}
365
366	/**
367	 * Similar to translate, but do perform "no operation" on it.
368	 *
369	 * This is necessary to fetch a format string (containing % characters) without
370	 * performing sustitution of arguments.
371	 *
372	 * @param string $string
373	 *
374	 * @return string
375	 */
376	public static function noop($string) {
377		return self::$translator->translate($string);
378	}
379
380	/**
381	 * Translate a plural string
382	 *
383	 * echo self::plural('There is an error', 'There are errors', $num_errors);
384	 * echo self::plural('There is one error', 'There are %s errors', $num_errors);
385	 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour);
386	 *
387	 * @return string
388	 */
389	public static function plural(/* var_args */) {
390		$args = func_get_args();
391		$args[0] = self::$translator->translatePlural($args[0], $args[1], $args[2]);
392		unset($args[1], $args[2]);
393
394		return call_user_func_array('sprintf', $args);
395	}
396
397	/**
398	 * Convert a GEDCOM age string into translated_text
399	 *
400	 * NB: The import function will have normalised this, so we don't need
401	 * to worry about badly formatted strings
402	 * NOTE: this function is not yet complete - eventually it will replace get_age_at_event()
403	 *
404	 * @param $string
405	 *
406	 * @return string
407	 */
408	public static function gedcomAge($string) {
409		switch ($string) {
410		case 'STILLBORN':
411			// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (stillborn)
412			return self::translate('(stillborn)');
413		case 'INFANT':
414			// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (in infancy)
415			return self::translate('(in infancy)');
416		case 'CHILD':
417			// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (in childhood)
418			return self::translate('(in childhood)');
419		}
420		$age = array();
421		if (preg_match('/(\d+)y/', $string, $match)) {
422			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
423			$years = $match[1];
424			$age[] = self::plural('%s year', '%s years', $years, self::number($years));
425		} else {
426			$years = -1;
427		}
428		if (preg_match('/(\d+)m/', $string, $match)) {
429			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
430			$age[] = self::plural('%s month', '%s months', $match[1], self::number($match[1]));
431		}
432		if (preg_match('/(\d+)w/', $string, $match)) {
433			// I18N: Part of an age string. e.g. 7 weeks and 3 days
434			$age[] = self::plural('%s week', '%s weeks', $match[1], self::number($match[1]));
435		}
436		if (preg_match('/(\d+)d/', $string, $match)) {
437			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
438			$age[] = self::plural('%s day', '%s days', $match[1], self::number($match[1]));
439		}
440		// If an age is just a number of years, only show the number
441		if (count($age) === 1 && $years >= 0) {
442			$age = $years;
443		}
444		if ($age) {
445			if (!substr_compare($string, '<', 0, 1)) {
446				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (aged less than 21 years)
447				return self::translate('(aged less than %s)', $age);
448			} elseif (!substr_compare($string, '>', 0, 1)) {
449				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (aged more than 21 years)
450				return self::translate('(aged more than %s)', $age);
451			} else {
452				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (aged 43 years)
453				return self::translate('(aged %s)', $age);
454			}
455		} else {
456			// Not a valid string?
457			return self::translate('(aged %s)', $string);
458		}
459	}
460
461	/**
462	 * Convert a number of seconds into a relative time.  For example, 630 => "10 hours, 30 minutes ago"
463	 *
464	 * @param integer $seconds
465	 *
466	 * @return string
467	 */
468	public static function timeAgo($seconds) {
469		$minute = 60;
470		$hour   = 60 * $minute;
471		$day    = 24 * $hour;
472		$month  = 30 * $day;
473		$year   = 365 * $day;
474
475		if ($seconds > $year) {
476			$years = (int) ($seconds / $year);
477			return self::plural('%s year ago', '%s years ago', $years, self::number($years));
478		} elseif ($seconds > $month) {
479			$months = (int) ($seconds / $month);
480			return self::plural('%s month ago', '%s months ago', $months, self::number($months));
481		} elseif ($seconds > $day) {
482			$days = (int) ($seconds / $day);
483			return self::plural('%s day ago', '%s days ago', $days, self::number($days));
484		} elseif ($seconds > $hour) {
485			$hours = (int) ($seconds / $hour);
486			return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours));
487		} elseif ($seconds > $minute) {
488			$minutes = (int) ($seconds / $minute);
489			return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes));
490		} else {
491			return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds));
492		}
493	}
494
495	/**
496	 * Return the endonym for a given language - as per http://cldr.unicode.org/
497	 *
498	 * @param string $locale
499	 *
500	 * @return string
501	 */
502	public static function languageName($locale) {
503		return Locale::create($locale)->endonym();
504	}
505
506	/**
507	 * Return the script used by a given language
508	 *
509	 * @param string $locale
510	 *
511	 * @return string
512	 */
513	public static function languageScript($locale) {
514		return Locale::create($locale)->script()->code();
515	}
516
517	/**
518	 * Identify the script used for a piece of text
519	 *
520	 * @param $string
521	 *
522	 * @return string
523	 */
524	public static function textScript($string) {
525		$string = strip_tags($string); // otherwise HTML tags show up as latin
526		$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin
527		$string = str_replace(array('@N.N.', '@P.N.'), '', $string); // otherwise unknown names show up as latin
528		$pos = 0;
529		$strlen = strlen($string);
530		while ($pos < $strlen) {
531			// get the Unicode Code Point for the character at position $pos
532			$byte1 = ord($string[$pos]);
533			if ($byte1 < 0x80) {
534				$code_point = $byte1;
535				$chrlen = 1;
536			} elseif ($byte1 < 0xC0) {
537				// Invalid continuation character
538				return 'Latn';
539			} elseif ($byte1 < 0xE0) {
540				$code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F);
541				$chrlen = 2;
542			} elseif ($byte1 < 0xF0) {
543				$code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F);
544				$chrlen = 3;
545			} elseif ($byte1 < 0xF8) {
546				$code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F);
547				$chrlen = 3;
548 			} else {
549				// Invalid UTF
550				return 'Latn';
551			}
552
553			foreach (self::$scripts as $range) {
554				if ($code_point >= $range[1] && $code_point <= $range[2]) {
555					return $range[0];
556				}
557			}
558			// Not a recognised script.  Maybe punctuation, spacing, etc.  Keep looking.
559			$pos += $chrlen;
560		}
561
562		return 'Latn';
563	}
564
565	/**
566	 * Return the direction (ltr or rtl) for a given script
567	 *
568	 * The PHP/intl library does not provde this information, so we need
569	 * our own lookup table.
570	 *
571	 * @param string $script
572	 *
573	 * @return string
574	 */
575	public static function scriptDirection($script) {
576		switch ($script) {
577		case 'Arab':
578		case 'Hebr':
579		case 'Mong':
580		case 'Thaa':
581			return 'rtl';
582		default:
583			return 'ltr';
584		}
585	}
586
587	/**
588	 * UTF8 version of PHP::strtoupper()
589	 *
590	 * Convert a string to upper case, using the rules from the current locale
591	 *
592	 * @param string $string
593	 *
594	 * @return string
595	 */
596	public static function strtoupper($string) {
597		if (self::$locale->language()->code() === 'tr' || self::$locale->language()->code() === 'az') {
598			return TurkishUtf8::strtoupper($string);
599		} else {
600			return mb_strtoupper($string);
601		}
602	}
603
604	/**
605	 * UTF8 version of PHP::strtolower()
606	 *
607	 * Convert a string to lower case, using the rules from the current locale
608	 *
609	 * @param string $string
610	 *
611	 * @return string
612	 */
613	public static function strtolower($string) {
614		if (self::$locale->language()->code() === 'tr' || self::$locale->language()->code() === 'az') {
615			return TurkishUtf8::strtolower($string);
616		} else {
617			return mb_strtolower($string);
618		}
619	}
620
621	/**
622	 * UTF8 version of PHP::strcasecmp()
623	 *
624	 * Perform a case-insensitive comparison of two strings, using rules from the current locale
625	 *
626	 * @param string $string1
627	 * @param string $string2
628	 *
629	 * @return integer
630	 */
631	public static function strcasecmp($string1, $string2) {
632		$strpos1 = 0;
633		$strpos2 = 0;
634		$strlen1 = strlen($string1);
635		$strlen2 = strlen($string2);
636		while ($strpos1 < $strlen1 && $strpos2 < $strlen2) {
637			$byte1 = ord($string1[$strpos1]);
638			$byte2 = ord($string2[$strpos2]);
639			if (($byte1 & 0xE0) === 0xC0) {
640				$chr1 = $string1[$strpos1++] . $string1[$strpos1++];
641			} elseif (($byte1 & 0xF0) === 0xE0) {
642				$chr1 = $string1[$strpos1++] . $string1[$strpos1++] . $string1[$strpos1++];
643			} else {
644				$chr1 = $string1[$strpos1++];
645			}
646			if (($byte2 & 0xE0) === 0xC0) {
647				$chr2 = $string2[$strpos2++] . $string2[$strpos2++];
648			} elseif (($byte2 & 0xF0) === 0xE0) {
649				$chr2 = $string2[$strpos2++] . $string2[$strpos2++] . $string2[$strpos2++];
650			} else {
651				$chr2 = $string2[$strpos2++];
652			}
653			if ($chr1 === $chr2) {
654				continue;
655			}
656			// Try the local alphabet first
657			$offset1 = strpos(self::$alphabet_lower, $chr1);
658			if ($offset1 === false) {
659				$offset1 = strpos(self::$alphabet_upper, $chr1);
660			}
661			$offset2 = strpos(self::$alphabet_lower, $chr2);
662			if ($offset2 === false) {
663				$offset2 = strpos(self::$alphabet_upper, $chr2);
664			}
665			if ($offset1 !== false && $offset2 !== false) {
666				if ($offset1 === $offset2) {
667					continue;
668				} else {
669					return $offset1 - $offset2;
670				}
671			}
672			// Try the global alphabet next
673			$offset1 = strpos(self::ALPHABET_LOWER, $chr1);
674			if ($offset1 === false) {
675				$offset1 = strpos(self::ALPHABET_UPPER, $chr1);
676			}
677			$offset2 = strpos(self::ALPHABET_LOWER, $chr2);
678			if ($offset2 === false) {
679				$offset2 = strpos(self::ALPHABET_UPPER, $chr2);
680			}
681			if ($offset1 !== false && $offset2 !== false) {
682				if ($offset1 === $offset2) {
683					continue;
684				} else {
685					return $offset1 - $offset2;
686				}
687			}
688			// Just compare by unicode order
689			return strcmp($chr1, $chr2);
690		}
691		// Shortest string comes first.
692		return ($strlen1 - $strpos1) - ($strlen2 - $strpos2);
693	}
694
695	/**
696	 * UTF8 version of PHP::strrev()
697	 *
698	 * Reverse RTL text for third-party libraries such as GD2 and googlechart.
699	 *
700	 * These do not support UTF8 text direction, so we must mimic it for them.
701	 *
702	 * Numbers are always rendered LTR, even in RTL text.
703	 * The visual direction of characters such as parentheses should be reversed.
704	 *
705	 * @param string $text Text to be reversed
706	 *
707	 * @return string
708	 */
709	public static function reverseText($text) {
710		// Remove HTML markup - we can't display it and it is LTR.
711		$text = Filter::unescapeHtml($text);
712
713		// LTR text doesn't need reversing
714		if (self::scriptDirection(self::textScript($text)) === 'ltr') {
715			return $text;
716		}
717
718		// Mirrored characters
719		$text = strtr($text, self::$mirror_characters);
720
721		$reversed = '';
722		$digits = '';
723		while ($text != '') {
724			$letter = mb_substr($text, 0, 1);
725			$text = mb_substr($text, 1);
726			if (strpos(self::DIGITS, $letter) !== false) {
727				$digits .= $letter;
728			} else {
729				$reversed = $letter . $digits . $reversed;
730				$digits = '';
731			}
732		}
733
734		return $digits . $reversed;
735	}
736
737	/**
738	 * Generate consistent I18N for datatables.js
739	 *
740	 * @param array|null $lengths An optional array of page lengths
741	 *
742	 * @return string
743	 */
744	public static function datatablesI18N(array $lengths = null) {
745		if ($lengths === null) {
746			$lengths = array(10, 20, 30, 50, 100, -1);
747		}
748
749		$length_menu = '';
750		foreach ($lengths as $length) {
751			$length_menu .=
752				'<option value="' . $length . '">' .
753				($length === -1 ? /* I18N: listbox option, e.g. “10,25,50,100,all” */ self::translate('All') : self::number($length)) .
754				'</option>';
755		}
756		$length_menu = '<select>' . $length_menu . '</select>';
757		$length_menu = /* I18N: Display %s [records per page], %s is a placeholder for listbox containing numeric options */ self::translate('Display %s', $length_menu);
758
759		$digits = self::$locale->digits('0123456789');
760		if ($digits === '0123456789') {
761			$callback = '';
762		} else {
763			$callback = ',
764				"infoCallback": function(oSettings, iStart, iEnd, iMax, iTotal, sPre) {
765					return sPre
766						.replace(/0/g, "' . mb_substr($digits, 0, 1) . '")
767						.replace(/1/g, "' . mb_substr($digits, 1, 1) . '")
768						.replace(/2/g, "' . mb_substr($digits, 2, 1) . '")
769						.replace(/3/g, "' . mb_substr($digits, 3, 1) . '")
770						.replace(/4/g, "' . mb_substr($digits, 4, 1) . '")
771						.replace(/5/g, "' . mb_substr($digits, 5, 1) . '")
772						.replace(/6/g, "' . mb_substr($digits, 6, 1) . '")
773						.replace(/7/g, "' . mb_substr($digits, 7, 1) . '")
774						.replace(/8/g, "' . mb_substr($digits, 8, 1) . '")
775						.replace(/9/g, "' . mb_substr($digits, 9, 1) . '");
776				},
777				"formatNumber": function(iIn) {
778					return String(iIn)
779						.replace(/0/g, "' . mb_substr($digits, 0, 1) . '")
780						.replace(/1/g, "' . mb_substr($digits, 1, 1) . '")
781						.replace(/2/g, "' . mb_substr($digits, 2, 1) . '")
782						.replace(/3/g, "' . mb_substr($digits, 3, 1) . '")
783						.replace(/4/g, "' . mb_substr($digits, 4, 1) . '")
784						.replace(/5/g, "' . mb_substr($digits, 5, 1) . '")
785						.replace(/6/g, "' . mb_substr($digits, 6, 1) . '")
786						.replace(/7/g, "' . mb_substr($digits, 7, 1) . '")
787						.replace(/8/g, "' . mb_substr($digits, 8, 1) . '")
788						.replace(/9/g, "' . mb_substr($digits, 9, 1) . '");
789				}
790			';
791		}
792
793		return
794			'"language": {' .
795			' "paginate": {' .
796			'  "first":    "' . /* I18N: button label, first page    */ self::translate('first') . '",' .
797			'  "last":     "' . /* I18N: button label, last page     */ self::translate('last') . '",' .
798			'  "next":     "' . /* I18N: button label, next page     */ self::translate('next') . '",' .
799			'  "previous": "' . /* I18N: button label, previous page */ self::translate('previous') . '"' .
800			' },' .
801			' "emptyTable":     "' . self::translate('No records to display') . '",' .
802			' "info":           "' . /* I18N: %s are placeholders for numbers */ self::translate('Showing %1$s to %2$s of %3$s', '_START_', '_END_', '_TOTAL_') . '",' .
803			' "infoEmpty":      "' . self::translate('Showing %1$s to %2$s of %3$s', 0, 0, 0) . '",' .
804			' "infoFiltered":   "' . /* I18N: %s is a placeholder for a number */ self::translate('(filtered from %s total entries)', '_MAX_') . '",' .
805			' "infoPostfix":    "",' .
806			' "lengthMenu":     "' . Filter::escapeJs($length_menu) . '",' .
807			' "loadingRecords": "' . self::translate('Loading…') . '",' .
808			' "processing":     "' . self::translate('Loading…') . '",' .
809			' "search":         "' . self::translate('Filter') . '",' .
810			' "url":            "",' .
811			' "zeroRecords":    "' . self::translate('No records to display') . '"' .
812			'}' .
813			$callback;
814	}
815}
816