xref: /webtrees/app/I18N.php (revision 04a105eeae4a6619d5e98410fb92e32a8fa16ed5)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2015 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 Fisharebest\ExtCalendar\ArabicCalendar;
19use Fisharebest\ExtCalendar\CalendarInterface;
20use Fisharebest\ExtCalendar\GregorianCalendar;
21use Fisharebest\ExtCalendar\JewishCalendar;
22use Fisharebest\ExtCalendar\PersianCalendar;
23use Fisharebest\Localization\Locale;
24use Fisharebest\Localization\Locale\LocaleEnUs;
25use Fisharebest\Localization\Locale\LocaleInterface;
26use Fisharebest\Localization\Translation;
27use Fisharebest\Localization\Translator;
28use Patchwork\TurkishUtf8;
29
30/**
31 * Internationalization (i18n) and localization (l10n).
32 */
33class I18N {
34	/** @var LocaleInterface The current locale (e.g. LocaleEnGb) */
35	private static $locale;
36
37	/** @var Translator An object that performs translation*/
38	private static $translator;
39
40	// Digits are always rendered LTR, even in RTL text.
41	const DIGITS = '0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹';
42
43	// Reversable character conversions from the UNICODE 5.1 database.
44	// It excludes ambiguous (turkish dotless i) and mixed-case (Dz) characters.
45	// The characters should be arranged in default unicode-collation order.
46	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ƶȥǯʒƹȝþƿƨƽƅάαἀἁἂἃἄἅἆἇὰάᾀᾁᾂᾃᾄᾅᾆᾇᾰᾱᾳβγδέεἐἑἒἓἔἕὲέϝϛζήηἠἡἢἣἤἥἦἧὴήᾐᾑᾒᾓᾔᾕᾖᾗῃθϊἰἱἲἳἴἵἶἷὶίῐῑκϗλμνξοόὀὁὂὃὄὅὸόπϟϙρῥσϲτυϋύὑὓὕὗὺύῠῡφχψωώὠὡὢὣὤὥὦὧὼώᾠᾡᾢᾣᾤᾥᾦᾧῳϡϸϻϣϥϧϩϫϭϯаӑӓәӛӕбвгґғҕдԁђԃѓҙеѐёӗєжӂӝҗзԅӟѕӡԇиѝӣҋӥіїйјкқӄҡҟҝлӆљԉмӎнӊңӈҥњԋоӧөӫпҧҁрҏсԍҫтԏҭћќуӯўӱӳүұѹфхҳһѡѿѽѻцҵчӵҷӌҹҽҿџшщъыӹьҍѣэӭюяѥѧѫѩѭѯѱѳѵѷҩաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆȼɂɇɉɋɍɏͱͳͷͻͼͽӏӷӻӽӿԑԓԕԗԙԛԝԟԡԣԥᵹᵽỻỽỿⅎↄⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡⱨⱪⱬⱳⱶⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⴀⴁⴂⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌⴍⴎⴏⴐⴑⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜⴝⴞⴟⴠⴡⴢⴣⴤⴥꙁꙃꙅꙇꙉꙋꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼꝿꞁꞃꞅꞇꞌ';
47	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ƵȤǮƷƸȜÞǷƧƼƄΆΑἈἉἊἋἌἍἎἏᾺΆᾈᾉᾊᾋᾌᾍᾎᾏᾸᾹᾼΒΓΔΈΕἘἙἚἛἜἝῈΈϜϚΖΉΗἨἩἪἫἬἭἮἯῊΉᾘᾙᾚᾛᾜᾝᾞᾟῌΘΪἸἹἺἻἼἽἾἿῚΊῘῙΚϏΛΜΝΞΟΌὈὉὊὋὌὍῸΌΠϞϘΡῬΣϹΤΥΫΎὙὛὝὟῪΎῨῩΦΧΨΩΏὨὩὪὫὬὭὮὯῺΏᾨᾩᾪᾫᾬᾭᾮᾯῼϠϷϺϢϤϦϨϪϬϮАӐӒӘӚӔБВГҐҒҔДԀЂԂЃҘЕЀЁӖЄЖӁӜҖЗԄӞЅӠԆИЍӢҊӤІЇЙЈКҚӃҠҞҜЛӅЉԈМӍНӉҢӇҤЊԊОӦӨӪПҦҀРҎСԌҪТԎҬЋЌУӮЎӰӲҮҰѸФХҲҺѠѾѼѺЦҴЧӴҶӋҸҼҾЏШЩЪЫӸЬҌѢЭӬЮЯѤѦѪѨѬѮѰѲѴѶҨԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖȻɁɆɈɊɌɎͰͲͶϽϾϿӀӶӺӼӾԐԒԔԖԘԚԜԞԠԢԤꝽⱣỺỼỾℲↃⰀⰁⰂⰃⰄⰅⰆⰇⰈⰉⰊⰋⰌⰍⰎⰏⰐⰑⰒⰓⰔⰕⰖⰗⰘⰙⰚⰛⰜⰝⰞⰟⰠⰡⰢⰣⰤⰥⰦⰧⰨⰩⰪⰫⰬⰭⰮⱠⱧⱩⱫⱲⱵⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢⳫⳭႠႡႢႣႤႥႦႧႨႩႪႫႬႭႮႯႰႱႲႳႴႵႶႷႸႹႺႻႼႽႾႿჀჁჂჃჄჅꙀꙂꙄꙆꙈꙊꙌꙎꙐꙒꙔꙖꙘꙚꙜꙞꙢꙤꙦꙨꙪꙬꚀꚂꚄꚆꚈꚊꚌꚎꚐꚒꚔꚖꜢꜤꜦꜨꜪꜬꜮꜲꜴꜶꜸꜺꜼꜾꝀꝂꝄꝆꝈꝊꝌꝎꝐꝒꝔꝖꝘꝚꝜꝞꝠꝢꝤꝦꝨꝪꝬꝮꝹꝻꝾꞀꞂꞄꞆꞋ';
48
49	/** @var string Alphabet, in lower case, for the current locale. */
50	private static $alphabet_lower = 'abcdefghijklmnopqrstuvwxyz';
51
52	/** @var string Alphabet, in upper case, for the current locale. */
53	private static $alphabet_upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
54
55	/** @var int[][] Character ranges used by each script. */
56	private static $scripts = array(
57		array('Latn', 0x0041, 0x005A), // a-z
58		array('Latn', 0x0061, 0x007A), // A-Z
59		array('Latn', 0x0100, 0x02AF),
60		array('Grek', 0x0370, 0x03FF),
61		array('Cyrl', 0x0400, 0x052F),
62		array('Hebr', 0x0590, 0x05FF),
63		array('Arab', 0x0600, 0x06FF),
64		array('Arab', 0x0750, 0x077F),
65		array('Arab', 0x08A0, 0x08FF),
66		array('Deva', 0x0900, 0x097F),
67		array('Taml', 0x0B80, 0x0BFF),
68		array('Sinh', 0x0D80, 0x0DFF),
69		array('Thai', 0x0E00, 0x0E7F),
70		array('Geor', 0x10A0, 0x10FF),
71		array('Grek', 0x1F00, 0x1FFF),
72		array('Deva', 0xA8E0, 0xA8FF),
73		array('Hans', 0x3000, 0x303F), // Mixed CJK, not just Hans
74		array('Hans', 0x3400, 0xFAFF), // Mixed CJK, not just Hans
75		array('Hans', 0x20000, 0x2FA1F), // Mixed CJK, not just Hans
76	);
77
78	/** @var string[] Characters that are displayed in mirror form in RTL text. */
79	private static $mirror_characters = array(
80		'('   => ')',
81		')'   => '(',
82		'['   => ']',
83		']'   => '[',
84		'{'   => '}',
85		'}'   => '{',
86		'<'   => '>',
87		'>'   => '<',
88		'‹'   => '›',
89		'›'   => '‹',
90		'«'   => '»',
91		'»'   => '«',
92		'﴾'   => '﴿',
93		'﴿'   => '﴾',
94		'“'   => '”',
95		'”'   => '“',
96		'‘'   => '’',
97		'’'   => '‘',
98	);
99
100	/** @var string Punctuation used to separate list items, typically a comma */
101	public static $list_separator;
102
103	/**
104	 * The prefered locales for this site, or a default list if no preference.
105	 *
106	 * @return LocaleInterface[]
107	 */
108	public static function activeLocales() {
109		$code_list = Site::getPreference('LANGUAGES');
110
111		if ($code_list) {
112			$codes = explode(',', $code_list);
113		} else {
114			$codes = array(
115				'ar', 'bg', 'bs', 'ca', 'cs', 'da', 'de', 'el', 'en-GB', 'en-US', 'es',
116				'et', 'fi', 'fr', 'he', 'hr', 'hu', 'is', 'it', 'ka', 'lt', 'mr', 'nb',
117				'nl', 'nn', 'pl', 'pt', 'ru', 'sk', 'sv', 'tr', 'uk', 'vi', 'zh-Hans',
118			);
119		}
120
121		$locales = array();
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 = array(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		$digits = self::$locale->digits('0123456789');
186		if ($digits === '0123456789') {
187			$callback = '';
188		} else {
189			$callback = ',
190				"infoCallback": function(oSettings, iStart, iEnd, iMax, iTotal, sPre) {
191					return sPre
192						.replace(/0/g, "' . mb_substr($digits, 0, 1) . '")
193						.replace(/1/g, "' . mb_substr($digits, 1, 1) . '")
194						.replace(/2/g, "' . mb_substr($digits, 2, 1) . '")
195						.replace(/3/g, "' . mb_substr($digits, 3, 1) . '")
196						.replace(/4/g, "' . mb_substr($digits, 4, 1) . '")
197						.replace(/5/g, "' . mb_substr($digits, 5, 1) . '")
198						.replace(/6/g, "' . mb_substr($digits, 6, 1) . '")
199						.replace(/7/g, "' . mb_substr($digits, 7, 1) . '")
200						.replace(/8/g, "' . mb_substr($digits, 8, 1) . '")
201						.replace(/9/g, "' . mb_substr($digits, 9, 1) . '");
202				},
203				"formatNumber": function(iIn) {
204					return String(iIn)
205						.replace(/0/g, "' . mb_substr($digits, 0, 1) . '")
206						.replace(/1/g, "' . mb_substr($digits, 1, 1) . '")
207						.replace(/2/g, "' . mb_substr($digits, 2, 1) . '")
208						.replace(/3/g, "' . mb_substr($digits, 3, 1) . '")
209						.replace(/4/g, "' . mb_substr($digits, 4, 1) . '")
210						.replace(/5/g, "' . mb_substr($digits, 5, 1) . '")
211						.replace(/6/g, "' . mb_substr($digits, 6, 1) . '")
212						.replace(/7/g, "' . mb_substr($digits, 7, 1) . '")
213						.replace(/8/g, "' . mb_substr($digits, 8, 1) . '")
214						.replace(/9/g, "' . mb_substr($digits, 9, 1) . '");
215				}
216			';
217		}
218
219		return
220			'"language": {' .
221			' "paginate": {' .
222			'  "first":    "' . /* I18N: button label, first page    */ self::translate('first') . '",' .
223			'  "last":     "' . /* I18N: button label, last page     */ self::translate('last') . '",' .
224			'  "next":     "' . /* I18N: button label, next page     */ self::translate('next') . '",' .
225			'  "previous": "' . /* I18N: button label, previous page */ self::translate('previous') . '"' .
226			' },' .
227			' "emptyTable":     "' . self::translate('No records to display') . '",' .
228			' "info":           "' . /* I18N: %s are placeholders for numbers */ self::translate('Showing %1$s to %2$s of %3$s', '_START_', '_END_', '_TOTAL_') . '",' .
229			' "infoEmpty":      "' . self::translate('Showing %1$s to %2$s of %3$s', 0, 0, 0) . '",' .
230			' "infoFiltered":   "' . /* I18N: %s is a placeholder for a number */ self::translate('(filtered from %s total entries)', '_MAX_') . '",' .
231			' "infoPostfix":    "",' .
232			' "lengthMenu":     "' . Filter::escapeJs($length_menu) . '",' .
233			' "loadingRecords": "' . self::translate('Loading…') . '",' .
234			' "processing":     "' . self::translate('Loading…') . '",' .
235			' "search":         "' . self::translate('Filter') . '",' .
236			' "url":            "",' .
237			' "zeroRecords":    "' . self::translate('No records to display') . '"' .
238			'}' .
239			$callback;
240	}
241
242	/**
243	 * Convert the digits 0-9 into the local script
244	 *
245	 * Used for years, etc., where we do not want thousands-separators, decimals, etc.
246	 *
247	 * @param int $n
248	 *
249	 * @return string
250	 */
251	public static function digits($n) {
252		return self::$locale->digits($n);
253	}
254
255	/**
256	 * What is the direction of the current locale
257	 *
258	 * @return string "ltr" or "rtl"
259	 */
260	public static function direction() {
261		return self::$locale->direction();
262	}
263
264	/**
265	 * What is the first day of the week.
266	 *
267	 * @return int Sunday=0, Monday=1, etc.
268	 */
269	public static function firstDay() {
270		return self::$locale->territory()->firstDay();
271	}
272
273	/**
274	 * Convert a GEDCOM age string into translated_text
275	 *
276	 * NB: The import function will have normalised this, so we don't need
277	 * to worry about badly formatted strings
278	 * NOTE: this function is not yet complete - eventually it will replace FunctionsDate::get_age_at_event()
279	 *
280	 * @param $string
281	 *
282	 * @return string
283	 */
284	public static function gedcomAge($string) {
285		switch ($string) {
286			case 'STILLBORN':
287				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (stillborn)
288				return self::translate('(stillborn)');
289			case 'INFANT':
290				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (in infancy)
291				return self::translate('(in infancy)');
292			case 'CHILD':
293				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (in childhood)
294				return self::translate('(in childhood)');
295		}
296		$age = array();
297		if (preg_match('/(\d+)y/', $string, $match)) {
298			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
299			$years = $match[1];
300			$age[] = self::plural('%s year', '%s years', $years, self::number($years));
301		} else {
302			$years = -1;
303		}
304		if (preg_match('/(\d+)m/', $string, $match)) {
305			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
306			$age[] = self::plural('%s month', '%s months', $match[1], self::number($match[1]));
307		}
308		if (preg_match('/(\d+)w/', $string, $match)) {
309			// I18N: Part of an age string. e.g. 7 weeks and 3 days
310			$age[] = self::plural('%s week', '%s weeks', $match[1], self::number($match[1]));
311		}
312		if (preg_match('/(\d+)d/', $string, $match)) {
313			// I18N: Part of an age string. e.g. 5 years, 4 months and 3 days
314			$age[] = self::plural('%s day', '%s days', $match[1], self::number($match[1]));
315		}
316		// If an age is just a number of years, only show the number
317		if (count($age) === 1 && $years >= 0) {
318			$age = $years;
319		}
320		if ($age) {
321			if (!substr_compare($string, '<', 0, 1)) {
322				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (aged less than 21 years)
323				return self::translate('(aged less than %s)', $age);
324			} elseif (!substr_compare($string, '>', 0, 1)) {
325				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (aged more than 21 years)
326				return self::translate('(aged more than %s)', $age);
327			} else {
328				// I18N: Description of an individual’s age at an event.  For example, Died 14 Jan 1900 (aged 43 years)
329				return self::translate('(aged %s)', $age);
330			}
331		} else {
332			// Not a valid string?
333			return self::translate('(aged %s)', $string);
334		}
335	}
336
337	/**
338	 * Generate i18n markup for the <html> tag, e.g. lang="ar" dir="rtl"
339	 *
340	 * @return string
341	 */
342	public static function htmlAttributes() {
343		return self::$locale->htmlAttributes();
344	}
345
346	/**
347	 * Initialise the translation adapter with a locale setting.
348	 *
349	 * @param string|null $code Use this locale/language code, or choose one automatically
350	 *
351	 * @return string $string
352	 */
353	public static function init($code = null) {
354		global $WT_TREE;
355
356		if ($code !== null) {
357			// Create the specified locale
358			self::$locale = Locale::create($code);
359		} else {
360			// Negotiate a locale, but if we can't then use a failsafe
361			self::$locale = new LocaleEnUs;
362			if (Session::has('locale')) {
363				// Previously used
364				self::$locale = Locale::create(Session::get('locale'));
365			} else {
366				// Browser negotiation
367				$default_locale = new LocaleEnUs;
368				try {
369					if ($WT_TREE) {
370						$default_locale = Locale::create($WT_TREE->getPreference('LANGUAGE'));
371					}
372				} catch (\Exception $ex) {
373				}
374				self::$locale = Locale::httpAcceptLanguage($_SERVER, self::installedLocales(), $default_locale);
375			}
376		}
377
378		File::mkdir(WT_DATA_DIR . 'cache');
379		$cache_file = WT_DATA_DIR . 'cache/language-' . self::$locale->languageTag() . '-cache.php';
380		if (file_exists($cache_file)) {
381			$filemtime = filemtime($cache_file);
382		} else {
383			$filemtime = 0;
384		}
385
386		// Load the translation file(s)
387		// Note that glob() returns false instead of an empty array when open_basedir_restriction
388		// is in force and no files are found.  See PHP bug #47358.
389		if (defined('GLOB_BRACE')) {
390			$translation_files = array_merge(
391				array(WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'),
392				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: array(),
393				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.{csv,php,mo}', GLOB_BRACE) ?: array()
394			);
395		} else {
396			// Some servers do not have GLOB_BRACE - see http://php.net/manual/en/function.glob.php
397			$translation_files = array_merge(
398				array(WT_ROOT . 'language/' . self::$locale->languageTag() . '.mo'),
399				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.csv') ?: array(),
400				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.php') ?: array(),
401				glob(WT_MODULES_DIR . '*/language/' . self::$locale->languageTag() . '.mo') ?: array(),
402				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.csv') ?: array(),
403				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.php') ?: array(),
404				glob(WT_DATA_DIR . 'language/' . self::$locale->languageTag() . '.mo') ?: array()
405			);
406		}
407		// Rebuild files after one hour
408		$rebuild_cache = time() > $filemtime + 3600;
409		// Rebuild files if any translation file has been updated
410		foreach ($translation_files as $translation_file) {
411			if (filemtime($translation_file) > $filemtime) {
412				$rebuild_cache = true;
413				break;
414			}
415		}
416
417		if ($rebuild_cache) {
418			$translations = array();
419			foreach ($translation_files as $translation_file) {
420				$translation  = new Translation($translation_file);
421				$translations = array_merge($translations, $translation->asArray());
422			}
423			file_put_contents($cache_file, '<' . '?php return ' . var_export($translations, true) . ';');
424		} else {
425			$translations = include $cache_file;
426		}
427
428		// Create a translator
429		self::$translator = new Translator($translations, self::$locale->pluralRule());
430
431		// Alphabetic sorting sequence (upper-case letters), used by webtrees to sort strings
432		list(, self::$alphabet_upper) = explode('=', self::$translator->translate('ALPHABET_upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
433		// Alphabetic sorting sequence (lower-case letters), used by webtrees to sort strings
434		list(, self::$alphabet_lower) = explode('=', self::$translator->translate('ALPHABET_lower=abcdefghijklmnopqrstuvwxyz'));
435
436		self::$list_separator = /* I18N: This punctuation is used to separate lists of items */ self::translate(', ');
437
438		return self::$locale->languageTag();
439	}
440
441	/**
442	 * All locales for which a translation file exists.
443	 *
444	 * @return LocaleInterface[]
445	 */
446	public static function installedLocales() {
447		$locales = array();
448		foreach (glob(WT_ROOT . 'language/*.mo') as $file) {
449			try {
450				$locales[] = Locale::create(basename($file, '.mo'));
451			} catch (\Exception $ex) {
452				// Not a recognised locale
453			}
454		}
455		usort($locales, '\Fisharebest\Localization\Locale::compare');
456
457		return $locales;
458	}
459
460	/**
461	 * Return the endonym for a given language - as per http://cldr.unicode.org/
462	 *
463	 * @param string $locale
464	 *
465	 * @return string
466	 */
467	public static function languageName($locale) {
468		return Locale::create($locale)->endonym();
469	}
470
471	/**
472	 * Return the script used by a given language
473	 *
474	 * @param string $locale
475	 *
476	 * @return string
477	 */
478	public static function languageScript($locale) {
479		return Locale::create($locale)->script()->code();
480	}
481
482	/**
483	 * Translate a number into the local representation.
484	 *
485	 * e.g. 12345.67 becomes
486	 * en: 12,345.67
487	 * fr: 12 345,67
488	 * de: 12.345,67
489	 *
490	 * @param float $n
491	 * @param int   $precision
492	 *
493	 * @return string
494	 */
495	public static function number($n, $precision = 0) {
496		return self::$locale->number(round($n, $precision));
497	}
498
499	/**
500	 * Translate a fraction into a percentage.
501	 *
502	 * e.g. 0.123 becomes
503	 * en: 12.3%
504	 * fr: 12,3 %
505	 * de: 12,3%
506	 *
507	 * @param float $n
508	 * @param int   $precision
509	 *
510	 * @return string
511	 */
512	public static function percentage($n, $precision = 0) {
513		return self::$locale->percent(round($n, $precision + 2));
514	}
515
516	/**
517	 * Translate a plural string
518	 *
519	 * echo self::plural('There is an error', 'There are errors', $num_errors);
520	 * echo self::plural('There is one error', 'There are %s errors', $num_errors);
521	 * echo self::plural('There is %1$s %2$s cat', 'There are %1$s %2$s cats', $num, $num, $colour);
522	 *
523	 * @return string
524	 */
525	public static function plural(/* var_args */) {
526		$args    = func_get_args();
527		$args[0] = self::$translator->translatePlural($args[0], $args[1], (int) $args[2]);
528		unset($args[1], $args[2]);
529
530		return self::substitutePlaceholders($args);
531	}
532
533	/**
534	 * UTF8 version of PHP::strrev()
535	 *
536	 * Reverse RTL text for third-party libraries such as GD2 and googlechart.
537	 *
538	 * These do not support UTF8 text direction, so we must mimic it for them.
539	 *
540	 * Numbers are always rendered LTR, even in RTL text.
541	 * The visual direction of characters such as parentheses should be reversed.
542	 *
543	 * @param string $text Text to be reversed
544	 *
545	 * @return string
546	 */
547	public static function reverseText($text) {
548		// Remove HTML markup - we can't display it and it is LTR.
549		$text = Filter::unescapeHtml($text);
550
551		// LTR text doesn't need reversing
552		if (self::scriptDirection(self::textScript($text)) === 'ltr') {
553			return $text;
554		}
555
556		// Mirrored characters
557		$text = strtr($text, self::$mirror_characters);
558
559		$reversed = '';
560		$digits   = '';
561		while ($text != '') {
562			$letter = mb_substr($text, 0, 1);
563			$text   = mb_substr($text, 1);
564			if (strpos(self::DIGITS, $letter) !== false) {
565				$digits .= $letter;
566			} else {
567				$reversed = $letter . $digits . $reversed;
568				$digits   = '';
569			}
570		}
571
572		return $digits . $reversed;
573	}
574
575	/**
576	 * Return the direction (ltr or rtl) for a given script
577	 *
578	 * The PHP/intl library does not provde this information, so we need
579	 * our own lookup table.
580	 *
581	 * @param string $script
582	 *
583	 * @return string
584	 */
585	public static function scriptDirection($script) {
586		switch ($script) {
587		case 'Arab':
588		case 'Hebr':
589		case 'Mong':
590		case 'Thaa':
591			return 'rtl';
592		default:
593			return 'ltr';
594		}
595	}
596
597	/**
598	 * UTF8 version of PHP::strcasecmp()
599	 *
600	 * Perform a case-insensitive comparison of two strings, using rules from the current locale
601	 *
602	 * @param string $string1
603	 * @param string $string2
604	 *
605	 * @return int
606	 */
607	public static function strcasecmp($string1, $string2) {
608		$strpos1 = 0;
609		$strpos2 = 0;
610		$strlen1 = strlen($string1);
611		$strlen2 = strlen($string2);
612		while ($strpos1 < $strlen1 && $strpos2 < $strlen2) {
613			$byte1 = ord($string1[$strpos1]);
614			$byte2 = ord($string2[$strpos2]);
615			if (($byte1 & 0xE0) === 0xC0) {
616				$chr1 = $string1[$strpos1++] . $string1[$strpos1++];
617			} elseif (($byte1 & 0xF0) === 0xE0) {
618				$chr1 = $string1[$strpos1++] . $string1[$strpos1++] . $string1[$strpos1++];
619			} else {
620				$chr1 = $string1[$strpos1++];
621			}
622			if (($byte2 & 0xE0) === 0xC0) {
623				$chr2 = $string2[$strpos2++] . $string2[$strpos2++];
624			} elseif (($byte2 & 0xF0) === 0xE0) {
625				$chr2 = $string2[$strpos2++] . $string2[$strpos2++] . $string2[$strpos2++];
626			} else {
627				$chr2 = $string2[$strpos2++];
628			}
629			if ($chr1 === $chr2) {
630				continue;
631			}
632			// Try the local alphabet first
633			$offset1 = strpos(self::$alphabet_lower, $chr1);
634			if ($offset1 === false) {
635				$offset1 = strpos(self::$alphabet_upper, $chr1);
636			}
637			$offset2 = strpos(self::$alphabet_lower, $chr2);
638			if ($offset2 === false) {
639				$offset2 = strpos(self::$alphabet_upper, $chr2);
640			}
641			if ($offset1 !== false && $offset2 !== false) {
642				if ($offset1 === $offset2) {
643					continue;
644				} else {
645					return $offset1 - $offset2;
646				}
647			}
648			// Try the global alphabet next
649			$offset1 = strpos(self::ALPHABET_LOWER, $chr1);
650			if ($offset1 === false) {
651				$offset1 = strpos(self::ALPHABET_UPPER, $chr1);
652			}
653			$offset2 = strpos(self::ALPHABET_LOWER, $chr2);
654			if ($offset2 === false) {
655				$offset2 = strpos(self::ALPHABET_UPPER, $chr2);
656			}
657			if ($offset1 !== false && $offset2 !== false) {
658				if ($offset1 === $offset2) {
659					continue;
660				} else {
661					return $offset1 - $offset2;
662				}
663			}
664			// Just compare by unicode order
665			return strcmp($chr1, $chr2);
666		}
667		// Shortest string comes first.
668		return ($strlen1 - $strpos1) - ($strlen2 - $strpos2);
669	}
670
671	/**
672	 * UTF8 version of PHP::strtolower()
673	 *
674	 * Convert a string to lower case, using the rules from the current locale
675	 *
676	 * @param string $string
677	 *
678	 * @return string
679	 */
680	public static function strtolower($string) {
681		if (self::$locale->language()->code() === 'tr' || self::$locale->language()->code() === 'az') {
682			return TurkishUtf8::strtolower($string);
683		} else {
684			return mb_strtolower($string);
685		}
686	}
687
688	/**
689	 * UTF8 version of PHP::strtoupper()
690	 *
691	 * Convert a string to upper case, using the rules from the current locale
692	 *
693	 * @param string $string
694	 *
695	 * @return string
696	 */
697	public static function strtoupper($string) {
698		if (self::$locale->language()->code() === 'tr' || self::$locale->language()->code() === 'az') {
699			return TurkishUtf8::strtoupper($string);
700		} else {
701			return mb_strtoupper($string);
702		}
703	}
704
705	/**
706	 * Substitute any "%s" placeholders in a translated string.
707	 * This also allows us to have translated strings that contain
708	 * "%" characters, which can't be passed to sprintf.
709	 *
710	 * @param string[] $args translated string plus optional parameters
711	 *
712	 * @return string
713	 */
714	private static function substitutePlaceholders(array $args) {
715		if (count($args) > 1) {
716			return call_user_func_array('sprintf', $args);
717		} else {
718			return $args[0];
719		}
720	}
721
722	/**
723	 * Identify the script used for a piece of text
724	 *
725	 * @param $string
726	 *
727	 * @return string
728	 */
729	public static function textScript($string) {
730		$string = strip_tags($string); // otherwise HTML tags show up as latin
731		$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); // otherwise HTML entities show up as latin
732		$string = str_replace(array('@N.N.', '@P.N.'), '', $string); // otherwise unknown names show up as latin
733		$pos    = 0;
734		$strlen = strlen($string);
735		while ($pos < $strlen) {
736			// get the Unicode Code Point for the character at position $pos
737			$byte1 = ord($string[$pos]);
738			if ($byte1 < 0x80) {
739				$code_point = $byte1;
740				$chrlen     = 1;
741			} elseif ($byte1 < 0xC0) {
742				// Invalid continuation character
743				return 'Latn';
744			} elseif ($byte1 < 0xE0) {
745				$code_point = (($byte1 & 0x1F) << 6) + (ord($string[$pos + 1]) & 0x3F);
746				$chrlen     = 2;
747			} elseif ($byte1 < 0xF0) {
748				$code_point = (($byte1 & 0x0F) << 12) + ((ord($string[$pos + 1]) & 0x3F) << 6) + (ord($string[$pos + 2]) & 0x3F);
749				$chrlen     = 3;
750			} elseif ($byte1 < 0xF8) {
751				$code_point = (($byte1 & 0x07) << 24) + ((ord($string[$pos + 1]) & 0x3F) << 12) + ((ord($string[$pos + 2]) & 0x3F) << 6) + (ord($string[$pos + 3]) & 0x3F);
752				$chrlen     = 3;
753			} else {
754				// Invalid UTF
755				return 'Latn';
756			}
757
758			foreach (self::$scripts as $range) {
759				if ($code_point >= $range[1] && $code_point <= $range[2]) {
760					return $range[0];
761				}
762			}
763			// Not a recognised script.  Maybe punctuation, spacing, etc.  Keep looking.
764			$pos += $chrlen;
765		}
766
767		return 'Latn';
768	}
769
770	/**
771	 * Convert a number of seconds into a relative time.  For example, 630 => "10 hours, 30 minutes ago"
772	 *
773	 * @param int $seconds
774	 *
775	 * @return string
776	 */
777	public static function timeAgo($seconds) {
778		$minute = 60;
779		$hour   = 60 * $minute;
780		$day    = 24 * $hour;
781		$month  = 30 * $day;
782		$year   = 365 * $day;
783
784		if ($seconds > $year) {
785			$years = (int) ($seconds / $year);
786
787			return self::plural('%s year ago', '%s years ago', $years, self::number($years));
788		} elseif ($seconds > $month) {
789			$months = (int) ($seconds / $month);
790
791			return self::plural('%s month ago', '%s months ago', $months, self::number($months));
792		} elseif ($seconds > $day) {
793			$days = (int) ($seconds / $day);
794
795			return self::plural('%s day ago', '%s days ago', $days, self::number($days));
796		} elseif ($seconds > $hour) {
797			$hours = (int) ($seconds / $hour);
798
799			return self::plural('%s hour ago', '%s hours ago', $hours, self::number($hours));
800		} elseif ($seconds > $minute) {
801			$minutes = (int) ($seconds / $minute);
802
803			return self::plural('%s minute ago', '%s minutes ago', $minutes, self::number($minutes));
804		} else {
805			return self::plural('%s second ago', '%s seconds ago', $seconds, self::number($seconds));
806		}
807	}
808
809	/**
810	 * What format is used to display dates in the current locale?
811	 *
812	 * @return string
813	 */
814	public static function timeFormat() {
815		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');
816	}
817
818	/**
819	 * Translate a string, and then substitute placeholders
820	 *
821	 * echo I18N::translate('Hello World!');
822	 * echo I18N::translate('The %s sat on the mat', 'cat');
823	 *
824	 * @return string
825	 */
826	public static function translate(/* var_args */) {
827		$args    = func_get_args();
828		$args[0] = self::$translator->translate($args[0]);
829
830		return self::substitutePlaceholders($args);
831	}
832
833	/**
834	 * Context sensitive version of translate.
835	 *
836	 * echo I18N::translateContext('NOMINATIVE', 'January');
837	 * echo I18N::translateContext('GENITIVE',   'January');
838	 *
839	 * @return string
840	 */
841	public static function translateContext(/* var_args */) {
842		$args    = func_get_args();
843		$args[0] = self::$translator->translateContext($args[0], $args[1]);
844		unset($args[1]);
845
846		return self::substitutePlaceholders($args);
847	}
848
849	/**
850	 * What is the last day of the weekend.
851	 *
852	 * @return int Sunday=0, Monday=1, etc.
853	 */
854	public static function weekendEnd() {
855		return self::$locale->territory()->weekendEnd();
856	}
857
858	/**
859	 * What is the first day of the weekend.
860	 *
861	 * @return int Sunday=0, Monday=1, etc.
862	 */
863	public static function weekendStart() {
864		return self::$locale->territory()->weekendStart();
865	}
866
867	/**
868	 * Which calendar prefered in this locale?
869	 *
870	 * @return CalendarInterface
871	 */
872	public static function defaultCalendar() {
873		switch (self::$locale->languageTag()) {
874			case 'ar':
875				return new ArabicCalendar;
876			case 'fa':
877				return new PersianCalendar;
878			case 'he':
879			case 'yi':
880				return new JewishCalendar;
881			default:
882				return new GregorianCalendar;
883		}
884	}
885}
886