Merge "Remove deprecated Language::getLanguageNames()"
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * Internationalisation code.
4 *
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 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Language
22 */
23
24 /**
25 * @defgroup Language Language
26 */
27
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
30 exit( 1 );
31 }
32
33 if ( function_exists( 'mb_strtoupper' ) ) {
34 mb_internal_encoding( 'UTF-8' );
35 }
36
37 use CLDRPluralRuleParser\Evaluator;
38
39 /**
40 * Internationalisation code
41 * @ingroup Language
42 */
43 class Language {
44 /**
45 * @var LanguageConverter
46 */
47 public $mConverter;
48
49 public $mVariants, $mCode, $mLoaded = false;
50 public $mMagicExtensions = [], $mMagicHookDone = false;
51 private $mHtmlCode = null, $mParentLanguage = false;
52
53 public $dateFormatStrings = [];
54 public $mExtendedSpecialPageAliases;
55
56 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
57
58 /**
59 * ReplacementArray object caches
60 */
61 public $transformData = [];
62
63 /**
64 * @var LocalisationCache
65 */
66 static public $dataCache;
67
68 static public $mLangObjCache = [];
69
70 static public $mWeekdayMsgs = [
71 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
72 'friday', 'saturday'
73 ];
74
75 static public $mWeekdayAbbrevMsgs = [
76 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
77 ];
78
79 static public $mMonthMsgs = [
80 'january', 'february', 'march', 'april', 'may_long', 'june',
81 'july', 'august', 'september', 'october', 'november',
82 'december'
83 ];
84 static public $mMonthGenMsgs = [
85 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
86 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
87 'december-gen'
88 ];
89 static public $mMonthAbbrevMsgs = [
90 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
91 'sep', 'oct', 'nov', 'dec'
92 ];
93
94 static public $mIranianCalendarMonthMsgs = [
95 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
96 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
97 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
98 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
99 ];
100
101 static public $mHebrewCalendarMonthMsgs = [
102 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
103 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
104 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
105 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
106 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
107 ];
108
109 static public $mHebrewCalendarMonthGenMsgs = [
110 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
111 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
112 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
113 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
114 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
115 ];
116
117 static public $mHijriCalendarMonthMsgs = [
118 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
119 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
120 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
121 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
122 ];
123
124 /**
125 * @since 1.20
126 * @var array
127 */
128 static public $durationIntervals = [
129 'millennia' => 31556952000,
130 'centuries' => 3155695200,
131 'decades' => 315569520,
132 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
133 'weeks' => 604800,
134 'days' => 86400,
135 'hours' => 3600,
136 'minutes' => 60,
137 'seconds' => 1,
138 ];
139
140 /**
141 * Cache for language fallbacks.
142 * @see Language::getFallbacksIncludingSiteLanguage
143 * @since 1.21
144 * @var array
145 */
146 static private $fallbackLanguageCache = [];
147
148 /**
149 * Cache for language names
150 * @var HashBagOStuff|null
151 */
152 static private $languageNameCache;
153
154 /**
155 * Unicode directional formatting characters, for embedBidi()
156 */
157 static private $lre = "\xE2\x80\xAA"; // U+202A LEFT-TO-RIGHT EMBEDDING
158 static private $rle = "\xE2\x80\xAB"; // U+202B RIGHT-TO-LEFT EMBEDDING
159 static private $pdf = "\xE2\x80\xAC"; // U+202C POP DIRECTIONAL FORMATTING
160
161 /**
162 * Directionality test regex for embedBidi(). Matches the first strong directionality codepoint:
163 * - in group 1 if it is LTR
164 * - in group 2 if it is RTL
165 * Does not match if there is no strong directionality codepoint.
166 *
167 * The form is '/(?:([strong ltr codepoint])|([strong rtl codepoint]))/u' .
168 *
169 * Generated by UnicodeJS (see tools/strongDir) from the UCD; see
170 * https://git.wikimedia.org/summary/unicodejs.git .
171 */
172 // @codingStandardsIgnoreStart
173 // @codeCoverageIgnoreStart
174 static private $strongDirRegex = '/(?:([\x{41}-\x{5a}\x{61}-\x{7a}\x{aa}\x{b5}\x{ba}\x{c0}-\x{d6}\x{d8}-\x{f6}\x{f8}-\x{2b8}\x{2bb}-\x{2c1}\x{2d0}\x{2d1}\x{2e0}-\x{2e4}\x{2ee}\x{370}-\x{373}\x{376}\x{377}\x{37a}-\x{37d}\x{37f}\x{386}\x{388}-\x{38a}\x{38c}\x{38e}-\x{3a1}\x{3a3}-\x{3f5}\x{3f7}-\x{482}\x{48a}-\x{52f}\x{531}-\x{556}\x{559}-\x{55f}\x{561}-\x{587}\x{589}\x{903}-\x{939}\x{93b}\x{93d}-\x{940}\x{949}-\x{94c}\x{94e}-\x{950}\x{958}-\x{961}\x{964}-\x{980}\x{982}\x{983}\x{985}-\x{98c}\x{98f}\x{990}\x{993}-\x{9a8}\x{9aa}-\x{9b0}\x{9b2}\x{9b6}-\x{9b9}\x{9bd}-\x{9c0}\x{9c7}\x{9c8}\x{9cb}\x{9cc}\x{9ce}\x{9d7}\x{9dc}\x{9dd}\x{9df}-\x{9e1}\x{9e6}-\x{9f1}\x{9f4}-\x{9fa}\x{a03}\x{a05}-\x{a0a}\x{a0f}\x{a10}\x{a13}-\x{a28}\x{a2a}-\x{a30}\x{a32}\x{a33}\x{a35}\x{a36}\x{a38}\x{a39}\x{a3e}-\x{a40}\x{a59}-\x{a5c}\x{a5e}\x{a66}-\x{a6f}\x{a72}-\x{a74}\x{a83}\x{a85}-\x{a8d}\x{a8f}-\x{a91}\x{a93}-\x{aa8}\x{aaa}-\x{ab0}\x{ab2}\x{ab3}\x{ab5}-\x{ab9}\x{abd}-\x{ac0}\x{ac9}\x{acb}\x{acc}\x{ad0}\x{ae0}\x{ae1}\x{ae6}-\x{af0}\x{af9}\x{b02}\x{b03}\x{b05}-\x{b0c}\x{b0f}\x{b10}\x{b13}-\x{b28}\x{b2a}-\x{b30}\x{b32}\x{b33}\x{b35}-\x{b39}\x{b3d}\x{b3e}\x{b40}\x{b47}\x{b48}\x{b4b}\x{b4c}\x{b57}\x{b5c}\x{b5d}\x{b5f}-\x{b61}\x{b66}-\x{b77}\x{b83}\x{b85}-\x{b8a}\x{b8e}-\x{b90}\x{b92}-\x{b95}\x{b99}\x{b9a}\x{b9c}\x{b9e}\x{b9f}\x{ba3}\x{ba4}\x{ba8}-\x{baa}\x{bae}-\x{bb9}\x{bbe}\x{bbf}\x{bc1}\x{bc2}\x{bc6}-\x{bc8}\x{bca}-\x{bcc}\x{bd0}\x{bd7}\x{be6}-\x{bf2}\x{c01}-\x{c03}\x{c05}-\x{c0c}\x{c0e}-\x{c10}\x{c12}-\x{c28}\x{c2a}-\x{c39}\x{c3d}\x{c41}-\x{c44}\x{c58}-\x{c5a}\x{c60}\x{c61}\x{c66}-\x{c6f}\x{c7f}\x{c82}\x{c83}\x{c85}-\x{c8c}\x{c8e}-\x{c90}\x{c92}-\x{ca8}\x{caa}-\x{cb3}\x{cb5}-\x{cb9}\x{cbd}-\x{cc4}\x{cc6}-\x{cc8}\x{cca}\x{ccb}\x{cd5}\x{cd6}\x{cde}\x{ce0}\x{ce1}\x{ce6}-\x{cef}\x{cf1}\x{cf2}\x{d02}\x{d03}\x{d05}-\x{d0c}\x{d0e}-\x{d10}\x{d12}-\x{d3a}\x{d3d}-\x{d40}\x{d46}-\x{d48}\x{d4a}-\x{d4c}\x{d4e}\x{d57}\x{d5f}-\x{d61}\x{d66}-\x{d75}\x{d79}-\x{d7f}\x{d82}\x{d83}\x{d85}-\x{d96}\x{d9a}-\x{db1}\x{db3}-\x{dbb}\x{dbd}\x{dc0}-\x{dc6}\x{dcf}-\x{dd1}\x{dd8}-\x{ddf}\x{de6}-\x{def}\x{df2}-\x{df4}\x{e01}-\x{e30}\x{e32}\x{e33}\x{e40}-\x{e46}\x{e4f}-\x{e5b}\x{e81}\x{e82}\x{e84}\x{e87}\x{e88}\x{e8a}\x{e8d}\x{e94}-\x{e97}\x{e99}-\x{e9f}\x{ea1}-\x{ea3}\x{ea5}\x{ea7}\x{eaa}\x{eab}\x{ead}-\x{eb0}\x{eb2}\x{eb3}\x{ebd}\x{ec0}-\x{ec4}\x{ec6}\x{ed0}-\x{ed9}\x{edc}-\x{edf}\x{f00}-\x{f17}\x{f1a}-\x{f34}\x{f36}\x{f38}\x{f3e}-\x{f47}\x{f49}-\x{f6c}\x{f7f}\x{f85}\x{f88}-\x{f8c}\x{fbe}-\x{fc5}\x{fc7}-\x{fcc}\x{fce}-\x{fda}\x{1000}-\x{102c}\x{1031}\x{1038}\x{103b}\x{103c}\x{103f}-\x{1057}\x{105a}-\x{105d}\x{1061}-\x{1070}\x{1075}-\x{1081}\x{1083}\x{1084}\x{1087}-\x{108c}\x{108e}-\x{109c}\x{109e}-\x{10c5}\x{10c7}\x{10cd}\x{10d0}-\x{1248}\x{124a}-\x{124d}\x{1250}-\x{1256}\x{1258}\x{125a}-\x{125d}\x{1260}-\x{1288}\x{128a}-\x{128d}\x{1290}-\x{12b0}\x{12b2}-\x{12b5}\x{12b8}-\x{12be}\x{12c0}\x{12c2}-\x{12c5}\x{12c8}-\x{12d6}\x{12d8}-\x{1310}\x{1312}-\x{1315}\x{1318}-\x{135a}\x{1360}-\x{137c}\x{1380}-\x{138f}\x{13a0}-\x{13f5}\x{13f8}-\x{13fd}\x{1401}-\x{167f}\x{1681}-\x{169a}\x{16a0}-\x{16f8}\x{1700}-\x{170c}\x{170e}-\x{1711}\x{1720}-\x{1731}\x{1735}\x{1736}\x{1740}-\x{1751}\x{1760}-\x{176c}\x{176e}-\x{1770}\x{1780}-\x{17b3}\x{17b6}\x{17be}-\x{17c5}\x{17c7}\x{17c8}\x{17d4}-\x{17da}\x{17dc}\x{17e0}-\x{17e9}\x{1810}-\x{1819}\x{1820}-\x{1877}\x{1880}-\x{18a8}\x{18aa}\x{18b0}-\x{18f5}\x{1900}-\x{191e}\x{1923}-\x{1926}\x{1929}-\x{192b}\x{1930}\x{1931}\x{1933}-\x{1938}\x{1946}-\x{196d}\x{1970}-\x{1974}\x{1980}-\x{19ab}\x{19b0}-\x{19c9}\x{19d0}-\x{19da}\x{1a00}-\x{1a16}\x{1a19}\x{1a1a}\x{1a1e}-\x{1a55}\x{1a57}\x{1a61}\x{1a63}\x{1a64}\x{1a6d}-\x{1a72}\x{1a80}-\x{1a89}\x{1a90}-\x{1a99}\x{1aa0}-\x{1aad}\x{1b04}-\x{1b33}\x{1b35}\x{1b3b}\x{1b3d}-\x{1b41}\x{1b43}-\x{1b4b}\x{1b50}-\x{1b6a}\x{1b74}-\x{1b7c}\x{1b82}-\x{1ba1}\x{1ba6}\x{1ba7}\x{1baa}\x{1bae}-\x{1be5}\x{1be7}\x{1bea}-\x{1bec}\x{1bee}\x{1bf2}\x{1bf3}\x{1bfc}-\x{1c2b}\x{1c34}\x{1c35}\x{1c3b}-\x{1c49}\x{1c4d}-\x{1c7f}\x{1cc0}-\x{1cc7}\x{1cd3}\x{1ce1}\x{1ce9}-\x{1cec}\x{1cee}-\x{1cf3}\x{1cf5}\x{1cf6}\x{1d00}-\x{1dbf}\x{1e00}-\x{1f15}\x{1f18}-\x{1f1d}\x{1f20}-\x{1f45}\x{1f48}-\x{1f4d}\x{1f50}-\x{1f57}\x{1f59}\x{1f5b}\x{1f5d}\x{1f5f}-\x{1f7d}\x{1f80}-\x{1fb4}\x{1fb6}-\x{1fbc}\x{1fbe}\x{1fc2}-\x{1fc4}\x{1fc6}-\x{1fcc}\x{1fd0}-\x{1fd3}\x{1fd6}-\x{1fdb}\x{1fe0}-\x{1fec}\x{1ff2}-\x{1ff4}\x{1ff6}-\x{1ffc}\x{200e}\x{2071}\x{207f}\x{2090}-\x{209c}\x{2102}\x{2107}\x{210a}-\x{2113}\x{2115}\x{2119}-\x{211d}\x{2124}\x{2126}\x{2128}\x{212a}-\x{212d}\x{212f}-\x{2139}\x{213c}-\x{213f}\x{2145}-\x{2149}\x{214e}\x{214f}\x{2160}-\x{2188}\x{2336}-\x{237a}\x{2395}\x{249c}-\x{24e9}\x{26ac}\x{2800}-\x{28ff}\x{2c00}-\x{2c2e}\x{2c30}-\x{2c5e}\x{2c60}-\x{2ce4}\x{2ceb}-\x{2cee}\x{2cf2}\x{2cf3}\x{2d00}-\x{2d25}\x{2d27}\x{2d2d}\x{2d30}-\x{2d67}\x{2d6f}\x{2d70}\x{2d80}-\x{2d96}\x{2da0}-\x{2da6}\x{2da8}-\x{2dae}\x{2db0}-\x{2db6}\x{2db8}-\x{2dbe}\x{2dc0}-\x{2dc6}\x{2dc8}-\x{2dce}\x{2dd0}-\x{2dd6}\x{2dd8}-\x{2dde}\x{3005}-\x{3007}\x{3021}-\x{3029}\x{302e}\x{302f}\x{3031}-\x{3035}\x{3038}-\x{303c}\x{3041}-\x{3096}\x{309d}-\x{309f}\x{30a1}-\x{30fa}\x{30fc}-\x{30ff}\x{3105}-\x{312d}\x{3131}-\x{318e}\x{3190}-\x{31ba}\x{31f0}-\x{321c}\x{3220}-\x{324f}\x{3260}-\x{327b}\x{327f}-\x{32b0}\x{32c0}-\x{32cb}\x{32d0}-\x{32fe}\x{3300}-\x{3376}\x{337b}-\x{33dd}\x{33e0}-\x{33fe}\x{3400}-\x{4db5}\x{4e00}-\x{9fd5}\x{a000}-\x{a48c}\x{a4d0}-\x{a60c}\x{a610}-\x{a62b}\x{a640}-\x{a66e}\x{a680}-\x{a69d}\x{a6a0}-\x{a6ef}\x{a6f2}-\x{a6f7}\x{a722}-\x{a787}\x{a789}-\x{a7ad}\x{a7b0}-\x{a7b7}\x{a7f7}-\x{a801}\x{a803}-\x{a805}\x{a807}-\x{a80a}\x{a80c}-\x{a824}\x{a827}\x{a830}-\x{a837}\x{a840}-\x{a873}\x{a880}-\x{a8c3}\x{a8ce}-\x{a8d9}\x{a8f2}-\x{a8fd}\x{a900}-\x{a925}\x{a92e}-\x{a946}\x{a952}\x{a953}\x{a95f}-\x{a97c}\x{a983}-\x{a9b2}\x{a9b4}\x{a9b5}\x{a9ba}\x{a9bb}\x{a9bd}-\x{a9cd}\x{a9cf}-\x{a9d9}\x{a9de}-\x{a9e4}\x{a9e6}-\x{a9fe}\x{aa00}-\x{aa28}\x{aa2f}\x{aa30}\x{aa33}\x{aa34}\x{aa40}-\x{aa42}\x{aa44}-\x{aa4b}\x{aa4d}\x{aa50}-\x{aa59}\x{aa5c}-\x{aa7b}\x{aa7d}-\x{aaaf}\x{aab1}\x{aab5}\x{aab6}\x{aab9}-\x{aabd}\x{aac0}\x{aac2}\x{aadb}-\x{aaeb}\x{aaee}-\x{aaf5}\x{ab01}-\x{ab06}\x{ab09}-\x{ab0e}\x{ab11}-\x{ab16}\x{ab20}-\x{ab26}\x{ab28}-\x{ab2e}\x{ab30}-\x{ab65}\x{ab70}-\x{abe4}\x{abe6}\x{abe7}\x{abe9}-\x{abec}\x{abf0}-\x{abf9}\x{ac00}-\x{d7a3}\x{d7b0}-\x{d7c6}\x{d7cb}-\x{d7fb}\x{e000}-\x{fa6d}\x{fa70}-\x{fad9}\x{fb00}-\x{fb06}\x{fb13}-\x{fb17}\x{ff21}-\x{ff3a}\x{ff41}-\x{ff5a}\x{ff66}-\x{ffbe}\x{ffc2}-\x{ffc7}\x{ffca}-\x{ffcf}\x{ffd2}-\x{ffd7}\x{ffda}-\x{ffdc}\x{10000}-\x{1000b}\x{1000d}-\x{10026}\x{10028}-\x{1003a}\x{1003c}\x{1003d}\x{1003f}-\x{1004d}\x{10050}-\x{1005d}\x{10080}-\x{100fa}\x{10100}\x{10102}\x{10107}-\x{10133}\x{10137}-\x{1013f}\x{101d0}-\x{101fc}\x{10280}-\x{1029c}\x{102a0}-\x{102d0}\x{10300}-\x{10323}\x{10330}-\x{1034a}\x{10350}-\x{10375}\x{10380}-\x{1039d}\x{1039f}-\x{103c3}\x{103c8}-\x{103d5}\x{10400}-\x{1049d}\x{104a0}-\x{104a9}\x{10500}-\x{10527}\x{10530}-\x{10563}\x{1056f}\x{10600}-\x{10736}\x{10740}-\x{10755}\x{10760}-\x{10767}\x{11000}\x{11002}-\x{11037}\x{11047}-\x{1104d}\x{11066}-\x{1106f}\x{11082}-\x{110b2}\x{110b7}\x{110b8}\x{110bb}-\x{110c1}\x{110d0}-\x{110e8}\x{110f0}-\x{110f9}\x{11103}-\x{11126}\x{1112c}\x{11136}-\x{11143}\x{11150}-\x{11172}\x{11174}-\x{11176}\x{11182}-\x{111b5}\x{111bf}-\x{111c9}\x{111cd}\x{111d0}-\x{111df}\x{111e1}-\x{111f4}\x{11200}-\x{11211}\x{11213}-\x{1122e}\x{11232}\x{11233}\x{11235}\x{11238}-\x{1123d}\x{11280}-\x{11286}\x{11288}\x{1128a}-\x{1128d}\x{1128f}-\x{1129d}\x{1129f}-\x{112a9}\x{112b0}-\x{112de}\x{112e0}-\x{112e2}\x{112f0}-\x{112f9}\x{11302}\x{11303}\x{11305}-\x{1130c}\x{1130f}\x{11310}\x{11313}-\x{11328}\x{1132a}-\x{11330}\x{11332}\x{11333}\x{11335}-\x{11339}\x{1133d}-\x{1133f}\x{11341}-\x{11344}\x{11347}\x{11348}\x{1134b}-\x{1134d}\x{11350}\x{11357}\x{1135d}-\x{11363}\x{11480}-\x{114b2}\x{114b9}\x{114bb}-\x{114be}\x{114c1}\x{114c4}-\x{114c7}\x{114d0}-\x{114d9}\x{11580}-\x{115b1}\x{115b8}-\x{115bb}\x{115be}\x{115c1}-\x{115db}\x{11600}-\x{11632}\x{1163b}\x{1163c}\x{1163e}\x{11641}-\x{11644}\x{11650}-\x{11659}\x{11680}-\x{116aa}\x{116ac}\x{116ae}\x{116af}\x{116b6}\x{116c0}-\x{116c9}\x{11700}-\x{11719}\x{11720}\x{11721}\x{11726}\x{11730}-\x{1173f}\x{118a0}-\x{118f2}\x{118ff}\x{11ac0}-\x{11af8}\x{12000}-\x{12399}\x{12400}-\x{1246e}\x{12470}-\x{12474}\x{12480}-\x{12543}\x{13000}-\x{1342e}\x{14400}-\x{14646}\x{16800}-\x{16a38}\x{16a40}-\x{16a5e}\x{16a60}-\x{16a69}\x{16a6e}\x{16a6f}\x{16ad0}-\x{16aed}\x{16af5}\x{16b00}-\x{16b2f}\x{16b37}-\x{16b45}\x{16b50}-\x{16b59}\x{16b5b}-\x{16b61}\x{16b63}-\x{16b77}\x{16b7d}-\x{16b8f}\x{16f00}-\x{16f44}\x{16f50}-\x{16f7e}\x{16f93}-\x{16f9f}\x{1b000}\x{1b001}\x{1bc00}-\x{1bc6a}\x{1bc70}-\x{1bc7c}\x{1bc80}-\x{1bc88}\x{1bc90}-\x{1bc99}\x{1bc9c}\x{1bc9f}\x{1d000}-\x{1d0f5}\x{1d100}-\x{1d126}\x{1d129}-\x{1d166}\x{1d16a}-\x{1d172}\x{1d183}\x{1d184}\x{1d18c}-\x{1d1a9}\x{1d1ae}-\x{1d1e8}\x{1d360}-\x{1d371}\x{1d400}-\x{1d454}\x{1d456}-\x{1d49c}\x{1d49e}\x{1d49f}\x{1d4a2}\x{1d4a5}\x{1d4a6}\x{1d4a9}-\x{1d4ac}\x{1d4ae}-\x{1d4b9}\x{1d4bb}\x{1d4bd}-\x{1d4c3}\x{1d4c5}-\x{1d505}\x{1d507}-\x{1d50a}\x{1d50d}-\x{1d514}\x{1d516}-\x{1d51c}\x{1d51e}-\x{1d539}\x{1d53b}-\x{1d53e}\x{1d540}-\x{1d544}\x{1d546}\x{1d54a}-\x{1d550}\x{1d552}-\x{1d6a5}\x{1d6a8}-\x{1d6da}\x{1d6dc}-\x{1d714}\x{1d716}-\x{1d74e}\x{1d750}-\x{1d788}\x{1d78a}-\x{1d7c2}\x{1d7c4}-\x{1d7cb}\x{1d800}-\x{1d9ff}\x{1da37}-\x{1da3a}\x{1da6d}-\x{1da74}\x{1da76}-\x{1da83}\x{1da85}-\x{1da8b}\x{1f110}-\x{1f12e}\x{1f130}-\x{1f169}\x{1f170}-\x{1f19a}\x{1f1e6}-\x{1f202}\x{1f210}-\x{1f23a}\x{1f240}-\x{1f248}\x{1f250}\x{1f251}\x{20000}-\x{2a6d6}\x{2a700}-\x{2b734}\x{2b740}-\x{2b81d}\x{2b820}-\x{2cea1}\x{2f800}-\x{2fa1d}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}])|([\x{590}\x{5be}\x{5c0}\x{5c3}\x{5c6}\x{5c8}-\x{5ff}\x{7c0}-\x{7ea}\x{7f4}\x{7f5}\x{7fa}-\x{815}\x{81a}\x{824}\x{828}\x{82e}-\x{858}\x{85c}-\x{89f}\x{200f}\x{fb1d}\x{fb1f}-\x{fb28}\x{fb2a}-\x{fb4f}\x{10800}-\x{1091e}\x{10920}-\x{10a00}\x{10a04}\x{10a07}-\x{10a0b}\x{10a10}-\x{10a37}\x{10a3b}-\x{10a3e}\x{10a40}-\x{10ae4}\x{10ae7}-\x{10b38}\x{10b40}-\x{10e5f}\x{10e7f}-\x{10fff}\x{1e800}-\x{1e8cf}\x{1e8d7}-\x{1edff}\x{1ef00}-\x{1efff}\x{608}\x{60b}\x{60d}\x{61b}-\x{64a}\x{66d}-\x{66f}\x{671}-\x{6d5}\x{6e5}\x{6e6}\x{6ee}\x{6ef}\x{6fa}-\x{710}\x{712}-\x{72f}\x{74b}-\x{7a5}\x{7b1}-\x{7bf}\x{8a0}-\x{8e2}\x{fb50}-\x{fd3d}\x{fd40}-\x{fdcf}\x{fdf0}-\x{fdfc}\x{fdfe}\x{fdff}\x{fe70}-\x{fefe}\x{1ee00}-\x{1eeef}\x{1eef2}-\x{1eeff}]))/u';
175 // @codeCoverageIgnoreEnd
176 // @codingStandardsIgnoreEnd
177
178 /**
179 * Get a cached or new language object for a given language code
180 * @param string $code
181 * @return Language
182 */
183 static function factory( $code ) {
184 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
185
186 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
187 $code = $wgDummyLanguageCodes[$code];
188 }
189
190 // get the language object to process
191 $langObj = isset( self::$mLangObjCache[$code] )
192 ? self::$mLangObjCache[$code]
193 : self::newFromCode( $code );
194
195 // merge the language object in to get it up front in the cache
196 self::$mLangObjCache = array_merge( [ $code => $langObj ], self::$mLangObjCache );
197 // get rid of the oldest ones in case we have an overflow
198 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
199
200 return $langObj;
201 }
202
203 /**
204 * Create a language object for a given language code
205 * @param string $code
206 * @throws MWException
207 * @return Language
208 */
209 protected static function newFromCode( $code ) {
210 if ( !Language::isValidCode( $code ) ) {
211 throw new MWException( "Invalid language code \"$code\"" );
212 }
213
214 if ( !Language::isValidBuiltInCode( $code ) ) {
215 // It's not possible to customise this code with class files, so
216 // just return a Language object. This is to support uselang= hacks.
217 $lang = new Language;
218 $lang->setCode( $code );
219 return $lang;
220 }
221
222 // Check if there is a language class for the code
223 $class = self::classFromCode( $code );
224 if ( class_exists( $class ) ) {
225 $lang = new $class;
226 return $lang;
227 }
228
229 // Keep trying the fallback list until we find an existing class
230 $fallbacks = Language::getFallbacksFor( $code );
231 foreach ( $fallbacks as $fallbackCode ) {
232 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
233 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
234 }
235
236 $class = self::classFromCode( $fallbackCode );
237 if ( class_exists( $class ) ) {
238 $lang = new $class;
239 $lang->setCode( $code );
240 return $lang;
241 }
242 }
243
244 throw new MWException( "Invalid fallback sequence for language '$code'" );
245 }
246
247 /**
248 * Checks whether any localisation is available for that language tag
249 * in MediaWiki (MessagesXx.php exists).
250 *
251 * @param string $code Language tag (in lower case)
252 * @return bool Whether language is supported
253 * @since 1.21
254 */
255 public static function isSupportedLanguage( $code ) {
256 if ( !self::isValidBuiltInCode( $code ) ) {
257 return false;
258 }
259
260 if ( $code === 'qqq' ) {
261 return false;
262 }
263
264 return is_readable( self::getMessagesFileName( $code ) ) ||
265 is_readable( self::getJsonMessagesFileName( $code ) );
266 }
267
268 /**
269 * Returns true if a language code string is a well-formed language tag
270 * according to RFC 5646.
271 * This function only checks well-formedness; it doesn't check that
272 * language, script or variant codes actually exist in the repositories.
273 *
274 * Based on regexes by Mark Davis of the Unicode Consortium:
275 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
276 *
277 * @param string $code
278 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
279 *
280 * @return bool
281 * @since 1.21
282 */
283 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
284 $alpha = '[a-z]';
285 $digit = '[0-9]';
286 $alphanum = '[a-z0-9]';
287 $x = 'x'; # private use singleton
288 $singleton = '[a-wy-z]'; # other singleton
289 $s = $lenient ? '[-_]' : '-';
290
291 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
292 $script = "$alpha{4}"; # ISO 15924
293 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
294 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
295 $extension = "$singleton(?:$s$alphanum{2,8})+";
296 $privateUse = "$x(?:$s$alphanum{1,8})+";
297
298 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
299 # Since these are limited, this is safe even later changes to the registry --
300 # the only oddity is that it might change the type of the tag, and thus
301 # the results from the capturing groups.
302 # http://www.iana.org/assignments/language-subtag-registry
303
304 $grandfathered = "en{$s}GB{$s}oed"
305 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
306 . "|no{$s}(?:bok|nyn)"
307 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
308 . "|zh{$s}min{$s}nan";
309
310 $variantList = "$variant(?:$s$variant)*";
311 $extensionList = "$extension(?:$s$extension)*";
312
313 $langtag = "(?:($language)"
314 . "(?:$s$script)?"
315 . "(?:$s$region)?"
316 . "(?:$s$variantList)?"
317 . "(?:$s$extensionList)?"
318 . "(?:$s$privateUse)?)";
319
320 # The final breakdown, with capturing groups for each of these components
321 # The variants, extensions, grandfathered, and private-use may have interior '-'
322
323 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
324
325 return (bool)preg_match( "/$root/", strtolower( $code ) );
326 }
327
328 /**
329 * Returns true if a language code string is of a valid form, whether or
330 * not it exists. This includes codes which are used solely for
331 * customisation via the MediaWiki namespace.
332 *
333 * @param string $code
334 *
335 * @return bool
336 */
337 public static function isValidCode( $code ) {
338 static $cache = [];
339 if ( !isset( $cache[$code] ) ) {
340 // People think language codes are html safe, so enforce it.
341 // Ideally we should only allow a-zA-Z0-9-
342 // but, .+ and other chars are often used for {{int:}} hacks
343 // see bugs 37564, 37587, 36938
344 $cache[$code] =
345 // Protect against path traversal
346 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
347 && !preg_match( MediaWikiTitleCodec::getTitleInvalidRegex(), $code );
348 }
349 return $cache[$code];
350 }
351
352 /**
353 * Returns true if a language code is of a valid form for the purposes of
354 * internal customisation of MediaWiki, via Messages*.php or *.json.
355 *
356 * @param string $code
357 *
358 * @throws MWException
359 * @since 1.18
360 * @return bool
361 */
362 public static function isValidBuiltInCode( $code ) {
363
364 if ( !is_string( $code ) ) {
365 if ( is_object( $code ) ) {
366 $addmsg = " of class " . get_class( $code );
367 } else {
368 $addmsg = '';
369 }
370 $type = gettype( $code );
371 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
372 }
373
374 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
375 }
376
377 /**
378 * Returns true if a language code is an IETF tag known to MediaWiki.
379 *
380 * @param string $tag
381 *
382 * @since 1.21
383 * @return bool
384 */
385 public static function isKnownLanguageTag( $tag ) {
386 // Quick escape for invalid input to avoid exceptions down the line
387 // when code tries to process tags which are not valid at all.
388 if ( !self::isValidBuiltInCode( $tag ) ) {
389 return false;
390 }
391
392 if ( isset( MediaWiki\Languages\Data\Names::$names[$tag] )
393 || self::fetchLanguageName( $tag, $tag ) !== ''
394 ) {
395 return true;
396 }
397
398 return false;
399 }
400
401 /**
402 * Get the LocalisationCache instance
403 *
404 * @return LocalisationCache
405 */
406 public static function getLocalisationCache() {
407 if ( is_null( self::$dataCache ) ) {
408 global $wgLocalisationCacheConf;
409 $class = $wgLocalisationCacheConf['class'];
410 self::$dataCache = new $class( $wgLocalisationCacheConf );
411 }
412 return self::$dataCache;
413 }
414
415 function __construct() {
416 $this->mConverter = new FakeConverter( $this );
417 // Set the code to the name of the descendant
418 if ( get_class( $this ) == 'Language' ) {
419 $this->mCode = 'en';
420 } else {
421 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
422 }
423 self::getLocalisationCache();
424 }
425
426 /**
427 * Reduce memory usage
428 */
429 function __destruct() {
430 foreach ( $this as $name => $value ) {
431 unset( $this->$name );
432 }
433 }
434
435 /**
436 * Hook which will be called if this is the content language.
437 * Descendants can use this to register hook functions or modify globals
438 */
439 function initContLang() {
440 }
441
442 /**
443 * @return array
444 * @since 1.19
445 */
446 function getFallbackLanguages() {
447 return self::getFallbacksFor( $this->mCode );
448 }
449
450 /**
451 * Exports $wgBookstoreListEn
452 * @return array
453 */
454 function getBookstoreList() {
455 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
456 }
457
458 /**
459 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
460 * available in localised form, it will be included in English.
461 *
462 * @return array
463 */
464 public function getNamespaces() {
465 if ( is_null( $this->namespaceNames ) ) {
466 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
467
468 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
469 $validNamespaces = MWNamespace::getCanonicalNamespaces();
470
471 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
472
473 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
474 if ( $wgMetaNamespaceTalk ) {
475 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
476 } else {
477 $talk = $this->namespaceNames[NS_PROJECT_TALK];
478 $this->namespaceNames[NS_PROJECT_TALK] =
479 $this->fixVariableInNamespace( $talk );
480 }
481
482 # Sometimes a language will be localised but not actually exist on this wiki.
483 foreach ( $this->namespaceNames as $key => $text ) {
484 if ( !isset( $validNamespaces[$key] ) ) {
485 unset( $this->namespaceNames[$key] );
486 }
487 }
488
489 # The above mixing may leave namespaces out of canonical order.
490 # Re-order by namespace ID number...
491 ksort( $this->namespaceNames );
492
493 Hooks::run( 'LanguageGetNamespaces', [ &$this->namespaceNames ] );
494 }
495
496 return $this->namespaceNames;
497 }
498
499 /**
500 * Arbitrarily set all of the namespace names at once. Mainly used for testing
501 * @param array $namespaces Array of namespaces (id => name)
502 */
503 public function setNamespaces( array $namespaces ) {
504 $this->namespaceNames = $namespaces;
505 $this->mNamespaceIds = null;
506 }
507
508 /**
509 * Resets all of the namespace caches. Mainly used for testing
510 */
511 public function resetNamespaces() {
512 $this->namespaceNames = null;
513 $this->mNamespaceIds = null;
514 $this->namespaceAliases = null;
515 }
516
517 /**
518 * A convenience function that returns getNamespaces() with spaces instead of underscores
519 * in values. Useful for producing output to be displayed e.g. in `<select>` forms.
520 *
521 * @return array
522 */
523 function getFormattedNamespaces() {
524 $ns = $this->getNamespaces();
525 foreach ( $ns as $k => $v ) {
526 $ns[$k] = strtr( $v, '_', ' ' );
527 }
528 return $ns;
529 }
530
531 /**
532 * Get a namespace value by key
533 *
534 * <code>
535 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
536 * echo $mw_ns; // prints 'MediaWiki'
537 * </code>
538 *
539 * @param int $index The array key of the namespace to return
540 * @return string|bool String if the namespace value exists, otherwise false
541 */
542 function getNsText( $index ) {
543 $ns = $this->getNamespaces();
544 return isset( $ns[$index] ) ? $ns[$index] : false;
545 }
546
547 /**
548 * A convenience function that returns the same thing as
549 * getNsText() except with '_' changed to ' ', useful for
550 * producing output.
551 *
552 * <code>
553 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
554 * echo $mw_ns; // prints 'MediaWiki talk'
555 * </code>
556 *
557 * @param int $index The array key of the namespace to return
558 * @return string Namespace name without underscores (empty string if namespace does not exist)
559 */
560 function getFormattedNsText( $index ) {
561 $ns = $this->getNsText( $index );
562 return strtr( $ns, '_', ' ' );
563 }
564
565 /**
566 * Returns gender-dependent namespace alias if available.
567 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
568 * @param int $index Namespace index
569 * @param string $gender Gender key (male, female... )
570 * @return string
571 * @since 1.18
572 */
573 function getGenderNsText( $index, $gender ) {
574 global $wgExtraGenderNamespaces;
575
576 $ns = $wgExtraGenderNamespaces +
577 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
578
579 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
580 }
581
582 /**
583 * Whether this language uses gender-dependent namespace aliases.
584 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
585 * @return bool
586 * @since 1.18
587 */
588 function needsGenderDistinction() {
589 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
590 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
591 // $wgExtraGenderNamespaces overrides everything
592 return true;
593 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
594 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
595 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
596 return false;
597 } else {
598 // Check what is in i18n files
599 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
600 return count( $aliases ) > 0;
601 }
602 }
603
604 /**
605 * Get a namespace key by value, case insensitive.
606 * Only matches namespace names for the current language, not the
607 * canonical ones defined in Namespace.php.
608 *
609 * @param string $text
610 * @return int|bool An integer if $text is a valid value otherwise false
611 */
612 function getLocalNsIndex( $text ) {
613 $lctext = $this->lc( $text );
614 $ids = $this->getNamespaceIds();
615 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
616 }
617
618 /**
619 * @return array
620 */
621 function getNamespaceAliases() {
622 if ( is_null( $this->namespaceAliases ) ) {
623 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
624 if ( !$aliases ) {
625 $aliases = [];
626 } else {
627 foreach ( $aliases as $name => $index ) {
628 if ( $index === NS_PROJECT_TALK ) {
629 unset( $aliases[$name] );
630 $name = $this->fixVariableInNamespace( $name );
631 $aliases[$name] = $index;
632 }
633 }
634 }
635
636 global $wgExtraGenderNamespaces;
637 $genders = $wgExtraGenderNamespaces +
638 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
639 foreach ( $genders as $index => $forms ) {
640 foreach ( $forms as $alias ) {
641 $aliases[$alias] = $index;
642 }
643 }
644
645 # Also add converted namespace names as aliases, to avoid confusion.
646 $convertedNames = [];
647 foreach ( $this->getVariants() as $variant ) {
648 if ( $variant === $this->mCode ) {
649 continue;
650 }
651 foreach ( $this->getNamespaces() as $ns => $_ ) {
652 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
653 }
654 }
655
656 $this->namespaceAliases = $aliases + $convertedNames;
657 }
658
659 return $this->namespaceAliases;
660 }
661
662 /**
663 * @return array
664 */
665 function getNamespaceIds() {
666 if ( is_null( $this->mNamespaceIds ) ) {
667 global $wgNamespaceAliases;
668 # Put namespace names and aliases into a hashtable.
669 # If this is too slow, then we should arrange it so that it is done
670 # before caching. The catch is that at pre-cache time, the above
671 # class-specific fixup hasn't been done.
672 $this->mNamespaceIds = [];
673 foreach ( $this->getNamespaces() as $index => $name ) {
674 $this->mNamespaceIds[$this->lc( $name )] = $index;
675 }
676 foreach ( $this->getNamespaceAliases() as $name => $index ) {
677 $this->mNamespaceIds[$this->lc( $name )] = $index;
678 }
679 if ( $wgNamespaceAliases ) {
680 foreach ( $wgNamespaceAliases as $name => $index ) {
681 $this->mNamespaceIds[$this->lc( $name )] = $index;
682 }
683 }
684 }
685 return $this->mNamespaceIds;
686 }
687
688 /**
689 * Get a namespace key by value, case insensitive. Canonical namespace
690 * names override custom ones defined for the current language.
691 *
692 * @param string $text
693 * @return int|bool An integer if $text is a valid value otherwise false
694 */
695 function getNsIndex( $text ) {
696 $lctext = $this->lc( $text );
697 $ns = MWNamespace::getCanonicalIndex( $lctext );
698 if ( $ns !== null ) {
699 return $ns;
700 }
701 $ids = $this->getNamespaceIds();
702 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
703 }
704
705 /**
706 * short names for language variants used for language conversion links.
707 *
708 * @param string $code
709 * @param bool $usemsg Use the "variantname-xyz" message if it exists
710 * @return string
711 */
712 function getVariantname( $code, $usemsg = true ) {
713 $msg = "variantname-$code";
714 if ( $usemsg && wfMessage( $msg )->exists() ) {
715 return $this->getMessageFromDB( $msg );
716 }
717 $name = self::fetchLanguageName( $code );
718 if ( $name ) {
719 return $name; # if it's defined as a language name, show that
720 } else {
721 # otherwise, output the language code
722 return $code;
723 }
724 }
725
726 /**
727 * @deprecated since 1.24, doesn't handle conflicting aliases. Use
728 * SpecialPageFactory::getLocalNameFor instead.
729 * @param string $name
730 * @return string
731 */
732 function specialPage( $name ) {
733 $aliases = $this->getSpecialPageAliases();
734 if ( isset( $aliases[$name][0] ) ) {
735 $name = $aliases[$name][0];
736 }
737 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
738 }
739
740 /**
741 * @return array
742 */
743 function getDatePreferences() {
744 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
745 }
746
747 /**
748 * @return array
749 */
750 function getDateFormats() {
751 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
752 }
753
754 /**
755 * @return array|string
756 */
757 function getDefaultDateFormat() {
758 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
759 if ( $df === 'dmy or mdy' ) {
760 global $wgAmericanDates;
761 return $wgAmericanDates ? 'mdy' : 'dmy';
762 } else {
763 return $df;
764 }
765 }
766
767 /**
768 * @return array
769 */
770 function getDatePreferenceMigrationMap() {
771 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
772 }
773
774 /**
775 * @param string $image
776 * @return array|null
777 */
778 function getImageFile( $image ) {
779 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
780 }
781
782 /**
783 * @return array
784 * @since 1.24
785 */
786 function getImageFiles() {
787 return self::$dataCache->getItem( $this->mCode, 'imageFiles' );
788 }
789
790 /**
791 * @return array
792 */
793 function getExtraUserToggles() {
794 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
795 }
796
797 /**
798 * @param string $tog
799 * @return string
800 */
801 function getUserToggle( $tog ) {
802 return $this->getMessageFromDB( "tog-$tog" );
803 }
804
805 /**
806 * Get translated language names. This is done on best effort and
807 * by default this is exactly the same as Language::getLanguageNames.
808 * The CLDR extension provides translated names.
809 * @param string $code Language code.
810 * @return array Language code => language name
811 * @since 1.18.0
812 * @deprecated since 1.20, use fetchLanguageNames()
813 */
814 public static function getTranslatedLanguageNames( $code ) {
815 return self::fetchLanguageNames( $code, 'all' );
816 }
817
818 /**
819 * Get an array of language names, indexed by code.
820 * @param null|string $inLanguage Code of language in which to return the names
821 * Use null for autonyms (native names)
822 * @param string $include One of:
823 * 'all' all available languages
824 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
825 * 'mwfile' only if the language is in 'mw' *and* has a message file
826 * @return array Language code => language name
827 * @since 1.20
828 */
829 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
830 $cacheKey = $inLanguage === null ? 'null' : $inLanguage;
831 $cacheKey .= ":$include";
832 if ( self::$languageNameCache === null ) {
833 self::$languageNameCache = new HashBagOStuff( [ 'maxKeys' => 20 ] );
834 }
835
836 $ret = self::$languageNameCache->get( $cacheKey );
837 if ( !$ret ) {
838 $ret = self::fetchLanguageNamesUncached( $inLanguage, $include );
839 self::$languageNameCache->set( $cacheKey, $ret );
840 }
841 return $ret;
842 }
843
844 /**
845 * Uncached helper for fetchLanguageNames
846 * @param null|string $inLanguage Code of language in which to return the names
847 * Use null for autonyms (native names)
848 * @param string $include One of:
849 * 'all' all available languages
850 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
851 * 'mwfile' only if the language is in 'mw' *and* has a message file
852 * @return array Language code => language name
853 */
854 private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) {
855 global $wgExtraLanguageNames;
856
857 // If passed an invalid language code to use, fallback to en
858 if ( $inLanguage !== null && !Language::isValidCode( $inLanguage ) ) {
859 $inLanguage = 'en';
860 }
861
862 $names = [];
863
864 if ( $inLanguage ) {
865 # TODO: also include when $inLanguage is null, when this code is more efficient
866 Hooks::run( 'LanguageGetTranslatedLanguageNames', [ &$names, $inLanguage ] );
867 }
868
869 $mwNames = $wgExtraLanguageNames + MediaWiki\Languages\Data\Names::$names;
870 foreach ( $mwNames as $mwCode => $mwName ) {
871 # - Prefer own MediaWiki native name when not using the hook
872 # - For other names just add if not added through the hook
873 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
874 $names[$mwCode] = $mwName;
875 }
876 }
877
878 if ( $include === 'all' ) {
879 ksort( $names );
880 return $names;
881 }
882
883 $returnMw = [];
884 $coreCodes = array_keys( $mwNames );
885 foreach ( $coreCodes as $coreCode ) {
886 $returnMw[$coreCode] = $names[$coreCode];
887 }
888
889 if ( $include === 'mwfile' ) {
890 $namesMwFile = [];
891 # We do this using a foreach over the codes instead of a directory
892 # loop so that messages files in extensions will work correctly.
893 foreach ( $returnMw as $code => $value ) {
894 if ( is_readable( self::getMessagesFileName( $code ) )
895 || is_readable( self::getJsonMessagesFileName( $code ) )
896 ) {
897 $namesMwFile[$code] = $names[$code];
898 }
899 }
900
901 ksort( $namesMwFile );
902 return $namesMwFile;
903 }
904
905 ksort( $returnMw );
906 # 'mw' option; default if it's not one of the other two options (all/mwfile)
907 return $returnMw;
908 }
909
910 /**
911 * @param string $code The code of the language for which to get the name
912 * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
913 * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
914 * @return string Language name or empty
915 * @since 1.20
916 */
917 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
918 $code = strtolower( $code );
919 $array = self::fetchLanguageNames( $inLanguage, $include );
920 return !array_key_exists( $code, $array ) ? '' : $array[$code];
921 }
922
923 /**
924 * Get a message from the MediaWiki namespace.
925 *
926 * @param string $msg Message name
927 * @return string
928 */
929 function getMessageFromDB( $msg ) {
930 return $this->msg( $msg )->text();
931 }
932
933 /**
934 * Get message object in this language. Only for use inside this class.
935 *
936 * @param string $msg Message name
937 * @return Message
938 */
939 protected function msg( $msg ) {
940 return wfMessage( $msg )->inLanguage( $this );
941 }
942
943 /**
944 * Get the native language name of $code.
945 * Only if defined in MediaWiki, no other data like CLDR.
946 * @param string $code
947 * @return string
948 * @deprecated since 1.20, use fetchLanguageName()
949 */
950 function getLanguageName( $code ) {
951 return self::fetchLanguageName( $code );
952 }
953
954 /**
955 * @param string $key
956 * @return string
957 */
958 function getMonthName( $key ) {
959 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
960 }
961
962 /**
963 * @return array
964 */
965 function getMonthNamesArray() {
966 $monthNames = [ '' ];
967 for ( $i = 1; $i < 13; $i++ ) {
968 $monthNames[] = $this->getMonthName( $i );
969 }
970 return $monthNames;
971 }
972
973 /**
974 * @param string $key
975 * @return string
976 */
977 function getMonthNameGen( $key ) {
978 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
979 }
980
981 /**
982 * @param string $key
983 * @return string
984 */
985 function getMonthAbbreviation( $key ) {
986 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
987 }
988
989 /**
990 * @return array
991 */
992 function getMonthAbbreviationsArray() {
993 $monthNames = [ '' ];
994 for ( $i = 1; $i < 13; $i++ ) {
995 $monthNames[] = $this->getMonthAbbreviation( $i );
996 }
997 return $monthNames;
998 }
999
1000 /**
1001 * @param string $key
1002 * @return string
1003 */
1004 function getWeekdayName( $key ) {
1005 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
1006 }
1007
1008 /**
1009 * @param string $key
1010 * @return string
1011 */
1012 function getWeekdayAbbreviation( $key ) {
1013 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
1014 }
1015
1016 /**
1017 * @param string $key
1018 * @return string
1019 */
1020 function getIranianCalendarMonthName( $key ) {
1021 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1022 }
1023
1024 /**
1025 * @param string $key
1026 * @return string
1027 */
1028 function getHebrewCalendarMonthName( $key ) {
1029 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1030 }
1031
1032 /**
1033 * @param string $key
1034 * @return string
1035 */
1036 function getHebrewCalendarMonthNameGen( $key ) {
1037 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1038 }
1039
1040 /**
1041 * @param string $key
1042 * @return string
1043 */
1044 function getHijriCalendarMonthName( $key ) {
1045 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1046 }
1047
1048 /**
1049 * Pass through result from $dateTimeObj->format()
1050 * @param DateTime|bool|null &$dateTimeObj
1051 * @param string $ts
1052 * @param DateTimeZone|bool|null $zone
1053 * @param string $code
1054 * @return string
1055 */
1056 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1057 if ( !$dateTimeObj ) {
1058 $dateTimeObj = DateTime::createFromFormat(
1059 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1060 );
1061 }
1062 return $dateTimeObj->format( $code );
1063 }
1064
1065 /**
1066 * This is a workalike of PHP's date() function, but with better
1067 * internationalisation, a reduced set of format characters, and a better
1068 * escaping format.
1069 *
1070 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1071 * the PHP manual for definitions. There are a number of extensions, which
1072 * start with "x":
1073 *
1074 * xn Do not translate digits of the next numeric format character
1075 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1076 * xr Use roman numerals for the next numeric format character
1077 * xh Use hebrew numerals for the next numeric format character
1078 * xx Literal x
1079 * xg Genitive month name
1080 *
1081 * xij j (day number) in Iranian calendar
1082 * xiF F (month name) in Iranian calendar
1083 * xin n (month number) in Iranian calendar
1084 * xiy y (two digit year) in Iranian calendar
1085 * xiY Y (full year) in Iranian calendar
1086 *
1087 * xjj j (day number) in Hebrew calendar
1088 * xjF F (month name) in Hebrew calendar
1089 * xjt t (days in month) in Hebrew calendar
1090 * xjx xg (genitive month name) in Hebrew calendar
1091 * xjn n (month number) in Hebrew calendar
1092 * xjY Y (full year) in Hebrew calendar
1093 *
1094 * xmj j (day number) in Hijri calendar
1095 * xmF F (month name) in Hijri calendar
1096 * xmn n (month number) in Hijri calendar
1097 * xmY Y (full year) in Hijri calendar
1098 *
1099 * xkY Y (full year) in Thai solar calendar. Months and days are
1100 * identical to the Gregorian calendar
1101 * xoY Y (full year) in Minguo calendar or Juche year.
1102 * Months and days are identical to the
1103 * Gregorian calendar
1104 * xtY Y (full year) in Japanese nengo. Months and days are
1105 * identical to the Gregorian calendar
1106 *
1107 * Characters enclosed in double quotes will be considered literal (with
1108 * the quotes themselves removed). Unmatched quotes will be considered
1109 * literal quotes. Example:
1110 *
1111 * "The month is" F => The month is January
1112 * i's" => 20'11"
1113 *
1114 * Backslash escaping is also supported.
1115 *
1116 * Input timestamp is assumed to be pre-normalized to the desired local
1117 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1118 * $ts is UTC if $zone is not given.
1119 *
1120 * @param string $format
1121 * @param string $ts 14-character timestamp
1122 * YYYYMMDDHHMMSS
1123 * 01234567890123
1124 * @param DateTimeZone $zone Timezone of $ts
1125 * @param[out] int $ttl The amount of time (in seconds) the output may be cached for.
1126 * Only makes sense if $ts is the current time.
1127 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1128 *
1129 * @throws MWException
1130 * @return string
1131 */
1132 function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = null ) {
1133 $s = '';
1134 $raw = false;
1135 $roman = false;
1136 $hebrewNum = false;
1137 $dateTimeObj = false;
1138 $rawToggle = false;
1139 $iranian = false;
1140 $hebrew = false;
1141 $hijri = false;
1142 $thai = false;
1143 $minguo = false;
1144 $tenno = false;
1145
1146 $usedSecond = false;
1147 $usedMinute = false;
1148 $usedHour = false;
1149 $usedAMPM = false;
1150 $usedDay = false;
1151 $usedWeek = false;
1152 $usedMonth = false;
1153 $usedYear = false;
1154 $usedISOYear = false;
1155 $usedIsLeapYear = false;
1156
1157 $usedHebrewMonth = false;
1158 $usedIranianMonth = false;
1159 $usedHijriMonth = false;
1160 $usedHebrewYear = false;
1161 $usedIranianYear = false;
1162 $usedHijriYear = false;
1163 $usedTennoYear = false;
1164
1165 if ( strlen( $ts ) !== 14 ) {
1166 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1167 }
1168
1169 if ( !ctype_digit( $ts ) ) {
1170 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1171 }
1172
1173 $formatLength = strlen( $format );
1174 for ( $p = 0; $p < $formatLength; $p++ ) {
1175 $num = false;
1176 $code = $format[$p];
1177 if ( $code == 'x' && $p < $formatLength - 1 ) {
1178 $code .= $format[++$p];
1179 }
1180
1181 if ( ( $code === 'xi'
1182 || $code === 'xj'
1183 || $code === 'xk'
1184 || $code === 'xm'
1185 || $code === 'xo'
1186 || $code === 'xt' )
1187 && $p < $formatLength - 1 ) {
1188 $code .= $format[++$p];
1189 }
1190
1191 switch ( $code ) {
1192 case 'xx':
1193 $s .= 'x';
1194 break;
1195 case 'xn':
1196 $raw = true;
1197 break;
1198 case 'xN':
1199 $rawToggle = !$rawToggle;
1200 break;
1201 case 'xr':
1202 $roman = true;
1203 break;
1204 case 'xh':
1205 $hebrewNum = true;
1206 break;
1207 case 'xg':
1208 $usedMonth = true;
1209 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1210 break;
1211 case 'xjx':
1212 $usedHebrewMonth = true;
1213 if ( !$hebrew ) {
1214 $hebrew = self::tsToHebrew( $ts );
1215 }
1216 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1217 break;
1218 case 'd':
1219 $usedDay = true;
1220 $num = substr( $ts, 6, 2 );
1221 break;
1222 case 'D':
1223 $usedDay = true;
1224 $s .= $this->getWeekdayAbbreviation(
1225 Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1226 );
1227 break;
1228 case 'j':
1229 $usedDay = true;
1230 $num = intval( substr( $ts, 6, 2 ) );
1231 break;
1232 case 'xij':
1233 $usedDay = true;
1234 if ( !$iranian ) {
1235 $iranian = self::tsToIranian( $ts );
1236 }
1237 $num = $iranian[2];
1238 break;
1239 case 'xmj':
1240 $usedDay = true;
1241 if ( !$hijri ) {
1242 $hijri = self::tsToHijri( $ts );
1243 }
1244 $num = $hijri[2];
1245 break;
1246 case 'xjj':
1247 $usedDay = true;
1248 if ( !$hebrew ) {
1249 $hebrew = self::tsToHebrew( $ts );
1250 }
1251 $num = $hebrew[2];
1252 break;
1253 case 'l':
1254 $usedDay = true;
1255 $s .= $this->getWeekdayName(
1256 Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1257 );
1258 break;
1259 case 'F':
1260 $usedMonth = true;
1261 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1262 break;
1263 case 'xiF':
1264 $usedIranianMonth = true;
1265 if ( !$iranian ) {
1266 $iranian = self::tsToIranian( $ts );
1267 }
1268 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1269 break;
1270 case 'xmF':
1271 $usedHijriMonth = true;
1272 if ( !$hijri ) {
1273 $hijri = self::tsToHijri( $ts );
1274 }
1275 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1276 break;
1277 case 'xjF':
1278 $usedHebrewMonth = true;
1279 if ( !$hebrew ) {
1280 $hebrew = self::tsToHebrew( $ts );
1281 }
1282 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1283 break;
1284 case 'm':
1285 $usedMonth = true;
1286 $num = substr( $ts, 4, 2 );
1287 break;
1288 case 'M':
1289 $usedMonth = true;
1290 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1291 break;
1292 case 'n':
1293 $usedMonth = true;
1294 $num = intval( substr( $ts, 4, 2 ) );
1295 break;
1296 case 'xin':
1297 $usedIranianMonth = true;
1298 if ( !$iranian ) {
1299 $iranian = self::tsToIranian( $ts );
1300 }
1301 $num = $iranian[1];
1302 break;
1303 case 'xmn':
1304 $usedHijriMonth = true;
1305 if ( !$hijri ) {
1306 $hijri = self::tsToHijri( $ts );
1307 }
1308 $num = $hijri[1];
1309 break;
1310 case 'xjn':
1311 $usedHebrewMonth = true;
1312 if ( !$hebrew ) {
1313 $hebrew = self::tsToHebrew( $ts );
1314 }
1315 $num = $hebrew[1];
1316 break;
1317 case 'xjt':
1318 $usedHebrewMonth = true;
1319 if ( !$hebrew ) {
1320 $hebrew = self::tsToHebrew( $ts );
1321 }
1322 $num = $hebrew[3];
1323 break;
1324 case 'Y':
1325 $usedYear = true;
1326 $num = substr( $ts, 0, 4 );
1327 break;
1328 case 'xiY':
1329 $usedIranianYear = true;
1330 if ( !$iranian ) {
1331 $iranian = self::tsToIranian( $ts );
1332 }
1333 $num = $iranian[0];
1334 break;
1335 case 'xmY':
1336 $usedHijriYear = true;
1337 if ( !$hijri ) {
1338 $hijri = self::tsToHijri( $ts );
1339 }
1340 $num = $hijri[0];
1341 break;
1342 case 'xjY':
1343 $usedHebrewYear = true;
1344 if ( !$hebrew ) {
1345 $hebrew = self::tsToHebrew( $ts );
1346 }
1347 $num = $hebrew[0];
1348 break;
1349 case 'xkY':
1350 $usedYear = true;
1351 if ( !$thai ) {
1352 $thai = self::tsToYear( $ts, 'thai' );
1353 }
1354 $num = $thai[0];
1355 break;
1356 case 'xoY':
1357 $usedYear = true;
1358 if ( !$minguo ) {
1359 $minguo = self::tsToYear( $ts, 'minguo' );
1360 }
1361 $num = $minguo[0];
1362 break;
1363 case 'xtY':
1364 $usedTennoYear = true;
1365 if ( !$tenno ) {
1366 $tenno = self::tsToYear( $ts, 'tenno' );
1367 }
1368 $num = $tenno[0];
1369 break;
1370 case 'y':
1371 $usedYear = true;
1372 $num = substr( $ts, 2, 2 );
1373 break;
1374 case 'xiy':
1375 $usedIranianYear = true;
1376 if ( !$iranian ) {
1377 $iranian = self::tsToIranian( $ts );
1378 }
1379 $num = substr( $iranian[0], -2 );
1380 break;
1381 case 'a':
1382 $usedAMPM = true;
1383 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1384 break;
1385 case 'A':
1386 $usedAMPM = true;
1387 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1388 break;
1389 case 'g':
1390 $usedHour = true;
1391 $h = substr( $ts, 8, 2 );
1392 $num = $h % 12 ? $h % 12 : 12;
1393 break;
1394 case 'G':
1395 $usedHour = true;
1396 $num = intval( substr( $ts, 8, 2 ) );
1397 break;
1398 case 'h':
1399 $usedHour = true;
1400 $h = substr( $ts, 8, 2 );
1401 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1402 break;
1403 case 'H':
1404 $usedHour = true;
1405 $num = substr( $ts, 8, 2 );
1406 break;
1407 case 'i':
1408 $usedMinute = true;
1409 $num = substr( $ts, 10, 2 );
1410 break;
1411 case 's':
1412 $usedSecond = true;
1413 $num = substr( $ts, 12, 2 );
1414 break;
1415 case 'c':
1416 case 'r':
1417 $usedSecond = true;
1418 // fall through
1419 case 'e':
1420 case 'O':
1421 case 'P':
1422 case 'T':
1423 $s .= Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1424 break;
1425 case 'w':
1426 case 'N':
1427 case 'z':
1428 $usedDay = true;
1429 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1430 break;
1431 case 'W':
1432 $usedWeek = true;
1433 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1434 break;
1435 case 't':
1436 $usedMonth = true;
1437 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1438 break;
1439 case 'L':
1440 $usedIsLeapYear = true;
1441 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1442 break;
1443 case 'o':
1444 $usedISOYear = true;
1445 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1446 break;
1447 case 'U':
1448 $usedSecond = true;
1449 // fall through
1450 case 'I':
1451 case 'Z':
1452 $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1453 break;
1454 case '\\':
1455 # Backslash escaping
1456 if ( $p < $formatLength - 1 ) {
1457 $s .= $format[++$p];
1458 } else {
1459 $s .= '\\';
1460 }
1461 break;
1462 case '"':
1463 # Quoted literal
1464 if ( $p < $formatLength - 1 ) {
1465 $endQuote = strpos( $format, '"', $p + 1 );
1466 if ( $endQuote === false ) {
1467 # No terminating quote, assume literal "
1468 $s .= '"';
1469 } else {
1470 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1471 $p = $endQuote;
1472 }
1473 } else {
1474 # Quote at end of string, assume literal "
1475 $s .= '"';
1476 }
1477 break;
1478 default:
1479 $s .= $format[$p];
1480 }
1481 if ( $num !== false ) {
1482 if ( $rawToggle || $raw ) {
1483 $s .= $num;
1484 $raw = false;
1485 } elseif ( $roman ) {
1486 $s .= Language::romanNumeral( $num );
1487 $roman = false;
1488 } elseif ( $hebrewNum ) {
1489 $s .= self::hebrewNumeral( $num );
1490 $hebrewNum = false;
1491 } else {
1492 $s .= $this->formatNum( $num, true );
1493 }
1494 }
1495 }
1496
1497 if ( $usedSecond ) {
1498 $ttl = 1;
1499 } elseif ( $usedMinute ) {
1500 $ttl = 60 - substr( $ts, 12, 2 );
1501 } elseif ( $usedHour ) {
1502 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1503 } elseif ( $usedAMPM ) {
1504 $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1505 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1506 } elseif (
1507 $usedDay ||
1508 $usedHebrewMonth ||
1509 $usedIranianMonth ||
1510 $usedHijriMonth ||
1511 $usedHebrewYear ||
1512 $usedIranianYear ||
1513 $usedHijriYear ||
1514 $usedTennoYear
1515 ) {
1516 // @todo Someone who understands the non-Gregorian calendars
1517 // should write proper logic for them so that they don't need purged every day.
1518 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1519 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1520 } else {
1521 $possibleTtls = [];
1522 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1523 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1524 if ( $usedWeek ) {
1525 $possibleTtls[] =
1526 ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1527 $timeRemainingInDay;
1528 } elseif ( $usedISOYear ) {
1529 // December 28th falls on the last ISO week of the year, every year.
1530 // The last ISO week of a year can be 52 or 53.
1531 $lastWeekOfISOYear = DateTime::createFromFormat(
1532 'Ymd',
1533 substr( $ts, 0, 4 ) . '1228',
1534 $zone ?: new DateTimeZone( 'UTC' )
1535 )->format( 'W' );
1536 $currentISOWeek = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1537 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1538 $timeRemainingInWeek =
1539 ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1540 + $timeRemainingInDay;
1541 $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1542 }
1543
1544 if ( $usedMonth ) {
1545 $possibleTtls[] =
1546 ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1547 substr( $ts, 6, 2 ) ) * 86400
1548 + $timeRemainingInDay;
1549 } elseif ( $usedYear ) {
1550 $possibleTtls[] =
1551 ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1552 Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1553 + $timeRemainingInDay;
1554 } elseif ( $usedIsLeapYear ) {
1555 $year = substr( $ts, 0, 4 );
1556 $timeRemainingInYear =
1557 ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1558 Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1559 + $timeRemainingInDay;
1560 $mod = $year % 4;
1561 if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1562 // this isn't a leap year. see when the next one starts
1563 $nextCandidate = $year - $mod + 4;
1564 if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1565 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1566 $timeRemainingInYear;
1567 } else {
1568 $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1569 $timeRemainingInYear;
1570 }
1571 } else {
1572 // this is a leap year, so the next year isn't
1573 $possibleTtls[] = $timeRemainingInYear;
1574 }
1575 }
1576
1577 if ( $possibleTtls ) {
1578 $ttl = min( $possibleTtls );
1579 }
1580 }
1581
1582 return $s;
1583 }
1584
1585 private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1586 private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1587
1588 /**
1589 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1590 * Gregorian dates to Iranian dates. Originally written in C, it
1591 * is released under the terms of GNU Lesser General Public
1592 * License. Conversion to PHP was performed by Niklas Laxström.
1593 *
1594 * Link: http://www.farsiweb.info/jalali/jalali.c
1595 *
1596 * @param string $ts
1597 *
1598 * @return string
1599 */
1600 private static function tsToIranian( $ts ) {
1601 $gy = substr( $ts, 0, 4 ) -1600;
1602 $gm = substr( $ts, 4, 2 ) -1;
1603 $gd = substr( $ts, 6, 2 ) -1;
1604
1605 # Days passed from the beginning (including leap years)
1606 $gDayNo = 365 * $gy
1607 + floor( ( $gy + 3 ) / 4 )
1608 - floor( ( $gy + 99 ) / 100 )
1609 + floor( ( $gy + 399 ) / 400 );
1610
1611 // Add days of the past months of this year
1612 for ( $i = 0; $i < $gm; $i++ ) {
1613 $gDayNo += self::$GREG_DAYS[$i];
1614 }
1615
1616 // Leap years
1617 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1618 $gDayNo++;
1619 }
1620
1621 // Days passed in current month
1622 $gDayNo += (int)$gd;
1623
1624 $jDayNo = $gDayNo - 79;
1625
1626 $jNp = floor( $jDayNo / 12053 );
1627 $jDayNo %= 12053;
1628
1629 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1630 $jDayNo %= 1461;
1631
1632 if ( $jDayNo >= 366 ) {
1633 $jy += floor( ( $jDayNo - 1 ) / 365 );
1634 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1635 }
1636
1637 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1638 $jDayNo -= self::$IRANIAN_DAYS[$i];
1639 }
1640
1641 $jm = $i + 1;
1642 $jd = $jDayNo + 1;
1643
1644 return [ $jy, $jm, $jd ];
1645 }
1646
1647 /**
1648 * Converting Gregorian dates to Hijri dates.
1649 *
1650 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1651 *
1652 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1653 *
1654 * @param string $ts
1655 *
1656 * @return string
1657 */
1658 private static function tsToHijri( $ts ) {
1659 $year = substr( $ts, 0, 4 );
1660 $month = substr( $ts, 4, 2 );
1661 $day = substr( $ts, 6, 2 );
1662
1663 $zyr = $year;
1664 $zd = $day;
1665 $zm = $month;
1666 $zy = $zyr;
1667
1668 if (
1669 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1670 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1671 ) {
1672 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1673 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1674 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1675 $zd - 32075;
1676 } else {
1677 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1678 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1679 }
1680
1681 $zl = $zjd -1948440 + 10632;
1682 $zn = (int)( ( $zl - 1 ) / 10631 );
1683 $zl = $zl - 10631 * $zn + 354;
1684 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1685 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1686 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1687 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1688 $zm = (int)( ( 24 * $zl ) / 709 );
1689 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1690 $zy = 30 * $zn + $zj - 30;
1691
1692 return [ $zy, $zm, $zd ];
1693 }
1694
1695 /**
1696 * Converting Gregorian dates to Hebrew dates.
1697 *
1698 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1699 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1700 * to translate the relevant functions into PHP and release them under
1701 * GNU GPL.
1702 *
1703 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1704 * and Adar II is 14. In a non-leap year, Adar is 6.
1705 *
1706 * @param string $ts
1707 *
1708 * @return string
1709 */
1710 private static function tsToHebrew( $ts ) {
1711 # Parse date
1712 $year = substr( $ts, 0, 4 );
1713 $month = substr( $ts, 4, 2 );
1714 $day = substr( $ts, 6, 2 );
1715
1716 # Calculate Hebrew year
1717 $hebrewYear = $year + 3760;
1718
1719 # Month number when September = 1, August = 12
1720 $month += 4;
1721 if ( $month > 12 ) {
1722 # Next year
1723 $month -= 12;
1724 $year++;
1725 $hebrewYear++;
1726 }
1727
1728 # Calculate day of year from 1 September
1729 $dayOfYear = $day;
1730 for ( $i = 1; $i < $month; $i++ ) {
1731 if ( $i == 6 ) {
1732 # February
1733 $dayOfYear += 28;
1734 # Check if the year is leap
1735 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1736 $dayOfYear++;
1737 }
1738 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1739 $dayOfYear += 30;
1740 } else {
1741 $dayOfYear += 31;
1742 }
1743 }
1744
1745 # Calculate the start of the Hebrew year
1746 $start = self::hebrewYearStart( $hebrewYear );
1747
1748 # Calculate next year's start
1749 if ( $dayOfYear <= $start ) {
1750 # Day is before the start of the year - it is the previous year
1751 # Next year's start
1752 $nextStart = $start;
1753 # Previous year
1754 $year--;
1755 $hebrewYear--;
1756 # Add days since previous year's 1 September
1757 $dayOfYear += 365;
1758 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1759 # Leap year
1760 $dayOfYear++;
1761 }
1762 # Start of the new (previous) year
1763 $start = self::hebrewYearStart( $hebrewYear );
1764 } else {
1765 # Next year's start
1766 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1767 }
1768
1769 # Calculate Hebrew day of year
1770 $hebrewDayOfYear = $dayOfYear - $start;
1771
1772 # Difference between year's days
1773 $diff = $nextStart - $start;
1774 # Add 12 (or 13 for leap years) days to ignore the difference between
1775 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1776 # difference is only about the year type
1777 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1778 $diff += 13;
1779 } else {
1780 $diff += 12;
1781 }
1782
1783 # Check the year pattern, and is leap year
1784 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1785 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1786 # and non-leap years
1787 $yearPattern = $diff % 30;
1788 # Check if leap year
1789 $isLeap = $diff >= 30;
1790
1791 # Calculate day in the month from number of day in the Hebrew year
1792 # Don't check Adar - if the day is not in Adar, we will stop before;
1793 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1794 $hebrewDay = $hebrewDayOfYear;
1795 $hebrewMonth = 1;
1796 $days = 0;
1797 while ( $hebrewMonth <= 12 ) {
1798 # Calculate days in this month
1799 if ( $isLeap && $hebrewMonth == 6 ) {
1800 # Adar in a leap year
1801 if ( $isLeap ) {
1802 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1803 $days = 30;
1804 if ( $hebrewDay <= $days ) {
1805 # Day in Adar I
1806 $hebrewMonth = 13;
1807 } else {
1808 # Subtract the days of Adar I
1809 $hebrewDay -= $days;
1810 # Try Adar II
1811 $days = 29;
1812 if ( $hebrewDay <= $days ) {
1813 # Day in Adar II
1814 $hebrewMonth = 14;
1815 }
1816 }
1817 }
1818 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1819 # Cheshvan in a complete year (otherwise as the rule below)
1820 $days = 30;
1821 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1822 # Kislev in an incomplete year (otherwise as the rule below)
1823 $days = 29;
1824 } else {
1825 # Odd months have 30 days, even have 29
1826 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1827 }
1828 if ( $hebrewDay <= $days ) {
1829 # In the current month
1830 break;
1831 } else {
1832 # Subtract the days of the current month
1833 $hebrewDay -= $days;
1834 # Try in the next month
1835 $hebrewMonth++;
1836 }
1837 }
1838
1839 return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1840 }
1841
1842 /**
1843 * This calculates the Hebrew year start, as days since 1 September.
1844 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1845 * Used for Hebrew date.
1846 *
1847 * @param int $year
1848 *
1849 * @return string
1850 */
1851 private static function hebrewYearStart( $year ) {
1852 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1853 $b = intval( ( $year - 1 ) % 4 );
1854 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1855 if ( $m < 0 ) {
1856 $m--;
1857 }
1858 $Mar = intval( $m );
1859 if ( $m < 0 ) {
1860 $m++;
1861 }
1862 $m -= $Mar;
1863
1864 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1865 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1866 $Mar++;
1867 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1868 $Mar += 2;
1869 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1870 $Mar++;
1871 }
1872
1873 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1874 return $Mar;
1875 }
1876
1877 /**
1878 * Algorithm to convert Gregorian dates to Thai solar dates,
1879 * Minguo dates or Minguo dates.
1880 *
1881 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1882 * http://en.wikipedia.org/wiki/Minguo_calendar
1883 * http://en.wikipedia.org/wiki/Japanese_era_name
1884 *
1885 * @param string $ts 14-character timestamp
1886 * @param string $cName Calender name
1887 * @return array Converted year, month, day
1888 */
1889 private static function tsToYear( $ts, $cName ) {
1890 $gy = substr( $ts, 0, 4 );
1891 $gm = substr( $ts, 4, 2 );
1892 $gd = substr( $ts, 6, 2 );
1893
1894 if ( !strcmp( $cName, 'thai' ) ) {
1895 # Thai solar dates
1896 # Add 543 years to the Gregorian calendar
1897 # Months and days are identical
1898 $gy_offset = $gy + 543;
1899 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1900 # Minguo dates
1901 # Deduct 1911 years from the Gregorian calendar
1902 # Months and days are identical
1903 $gy_offset = $gy - 1911;
1904 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1905 # Nengō dates up to Meiji period
1906 # Deduct years from the Gregorian calendar
1907 # depending on the nengo periods
1908 # Months and days are identical
1909 if ( ( $gy < 1912 )
1910 || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1911 || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1912 ) {
1913 # Meiji period
1914 $gy_gannen = $gy - 1868 + 1;
1915 $gy_offset = $gy_gannen;
1916 if ( $gy_gannen == 1 ) {
1917 $gy_offset = '元';
1918 }
1919 $gy_offset = '明治' . $gy_offset;
1920 } elseif (
1921 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1922 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1923 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1924 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1925 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1926 ) {
1927 # Taishō period
1928 $gy_gannen = $gy - 1912 + 1;
1929 $gy_offset = $gy_gannen;
1930 if ( $gy_gannen == 1 ) {
1931 $gy_offset = '元';
1932 }
1933 $gy_offset = '大正' . $gy_offset;
1934 } elseif (
1935 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1936 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1937 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1938 ) {
1939 # Shōwa period
1940 $gy_gannen = $gy - 1926 + 1;
1941 $gy_offset = $gy_gannen;
1942 if ( $gy_gannen == 1 ) {
1943 $gy_offset = '元';
1944 }
1945 $gy_offset = '昭和' . $gy_offset;
1946 } else {
1947 # Heisei period
1948 $gy_gannen = $gy - 1989 + 1;
1949 $gy_offset = $gy_gannen;
1950 if ( $gy_gannen == 1 ) {
1951 $gy_offset = '元';
1952 }
1953 $gy_offset = '平成' . $gy_offset;
1954 }
1955 } else {
1956 $gy_offset = $gy;
1957 }
1958
1959 return [ $gy_offset, $gm, $gd ];
1960 }
1961
1962 /**
1963 * Gets directionality of the first strongly directional codepoint, for embedBidi()
1964 *
1965 * This is the rule the BIDI algorithm uses to determine the directionality of
1966 * paragraphs ( http://unicode.org/reports/tr9/#The_Paragraph_Level ) and
1967 * FSI isolates ( http://unicode.org/reports/tr9/#Explicit_Directional_Isolates ).
1968 *
1969 * TODO: Does not handle BIDI control characters inside the text.
1970 * TODO: Does not handle unallocated characters.
1971 *
1972 * @param string $text Text to test
1973 * @return null|string Directionality ('ltr' or 'rtl') or null
1974 */
1975 private static function strongDirFromContent( $text = '' ) {
1976 if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
1977 return null;
1978 }
1979 if ( $matches[1] === '' ) {
1980 return 'rtl';
1981 }
1982 return 'ltr';
1983 }
1984
1985 /**
1986 * Roman number formatting up to 10000
1987 *
1988 * @param int $num
1989 *
1990 * @return string
1991 */
1992 static function romanNumeral( $num ) {
1993 static $table = [
1994 [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
1995 [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
1996 [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
1997 [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1998 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
1999 ];
2000
2001 $num = intval( $num );
2002 if ( $num > 10000 || $num <= 0 ) {
2003 return $num;
2004 }
2005
2006 $s = '';
2007 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2008 if ( $num >= $pow10 ) {
2009 $s .= $table[$i][(int)floor( $num / $pow10 )];
2010 }
2011 $num = $num % $pow10;
2012 }
2013 return $s;
2014 }
2015
2016 /**
2017 * Hebrew Gematria number formatting up to 9999
2018 *
2019 * @param int $num
2020 *
2021 * @return string
2022 */
2023 static function hebrewNumeral( $num ) {
2024 static $table = [
2025 [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
2026 [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
2027 [ '',
2028 [ 'ק' ],
2029 [ 'ר' ],
2030 [ 'ש' ],
2031 [ 'ת' ],
2032 [ 'ת', 'ק' ],
2033 [ 'ת', 'ר' ],
2034 [ 'ת', 'ש' ],
2035 [ 'ת', 'ת' ],
2036 [ 'ת', 'ת', 'ק' ],
2037 [ 'ת', 'ת', 'ר' ],
2038 ],
2039 [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
2040 ];
2041
2042 $num = intval( $num );
2043 if ( $num > 9999 || $num <= 0 ) {
2044 return $num;
2045 }
2046
2047 // Round thousands have special notations
2048 if ( $num === 1000 ) {
2049 return "א' אלף";
2050 } elseif ( $num % 1000 === 0 ) {
2051 return $table[0][$num / 1000] . "' אלפים";
2052 }
2053
2054 $letters = [];
2055
2056 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2057 if ( $num >= $pow10 ) {
2058 if ( $num === 15 || $num === 16 ) {
2059 $letters[] = $table[0][9];
2060 $letters[] = $table[0][$num - 9];
2061 $num = 0;
2062 } else {
2063 $letters = array_merge(
2064 $letters,
2065 (array)$table[$i][intval( $num / $pow10 )]
2066 );
2067
2068 if ( $pow10 === 1000 ) {
2069 $letters[] = "'";
2070 }
2071 }
2072 }
2073
2074 $num = $num % $pow10;
2075 }
2076
2077 $preTransformLength = count( $letters );
2078 if ( $preTransformLength === 1 ) {
2079 // Add geresh (single quote) to one-letter numbers
2080 $letters[] = "'";
2081 } else {
2082 $lastIndex = $preTransformLength - 1;
2083 $letters[$lastIndex] = str_replace(
2084 [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2085 [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2086 $letters[$lastIndex]
2087 );
2088
2089 // Add gershayim (double quote) to multiple-letter numbers,
2090 // but exclude numbers with only one letter after the thousands
2091 // (1001-1009, 1020, 1030, 2001-2009, etc.)
2092 if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2093 $letters[] = "'";
2094 } else {
2095 array_splice( $letters, -1, 0, '"' );
2096 }
2097 }
2098
2099 return implode( $letters );
2100 }
2101
2102 /**
2103 * Used by date() and time() to adjust the time output.
2104 *
2105 * @param string $ts The time in date('YmdHis') format
2106 * @param mixed $tz Adjust the time by this amount (default false, mean we
2107 * get user timecorrection setting)
2108 * @return int
2109 */
2110 function userAdjust( $ts, $tz = false ) {
2111 global $wgUser, $wgLocalTZoffset;
2112
2113 if ( $tz === false ) {
2114 $tz = $wgUser->getOption( 'timecorrection' );
2115 }
2116
2117 $data = explode( '|', $tz, 3 );
2118
2119 if ( $data[0] == 'ZoneInfo' ) {
2120 MediaWiki\suppressWarnings();
2121 $userTZ = timezone_open( $data[2] );
2122 MediaWiki\restoreWarnings();
2123 if ( $userTZ !== false ) {
2124 $date = date_create( $ts, timezone_open( 'UTC' ) );
2125 date_timezone_set( $date, $userTZ );
2126 $date = date_format( $date, 'YmdHis' );
2127 return $date;
2128 }
2129 # Unrecognized timezone, default to 'Offset' with the stored offset.
2130 $data[0] = 'Offset';
2131 }
2132
2133 if ( $data[0] == 'System' || $tz == '' ) {
2134 # Global offset in minutes.
2135 $minDiff = $wgLocalTZoffset;
2136 } elseif ( $data[0] == 'Offset' ) {
2137 $minDiff = intval( $data[1] );
2138 } else {
2139 $data = explode( ':', $tz );
2140 if ( count( $data ) == 2 ) {
2141 $data[0] = intval( $data[0] );
2142 $data[1] = intval( $data[1] );
2143 $minDiff = abs( $data[0] ) * 60 + $data[1];
2144 if ( $data[0] < 0 ) {
2145 $minDiff = -$minDiff;
2146 }
2147 } else {
2148 $minDiff = intval( $data[0] ) * 60;
2149 }
2150 }
2151
2152 # No difference ? Return time unchanged
2153 if ( 0 == $minDiff ) {
2154 return $ts;
2155 }
2156
2157 MediaWiki\suppressWarnings(); // E_STRICT system time bitching
2158 # Generate an adjusted date; take advantage of the fact that mktime
2159 # will normalize out-of-range values so we don't have to split $minDiff
2160 # into hours and minutes.
2161 $t = mktime( (
2162 (int)substr( $ts, 8, 2 ) ), # Hours
2163 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2164 (int)substr( $ts, 12, 2 ), # Seconds
2165 (int)substr( $ts, 4, 2 ), # Month
2166 (int)substr( $ts, 6, 2 ), # Day
2167 (int)substr( $ts, 0, 4 ) ); # Year
2168
2169 $date = date( 'YmdHis', $t );
2170 MediaWiki\restoreWarnings();
2171
2172 return $date;
2173 }
2174
2175 /**
2176 * This is meant to be used by time(), date(), and timeanddate() to get
2177 * the date preference they're supposed to use, it should be used in
2178 * all children.
2179 *
2180 *<code>
2181 * function timeanddate([...], $format = true) {
2182 * $datePreference = $this->dateFormat($format);
2183 * [...]
2184 * }
2185 *</code>
2186 *
2187 * @param int|string|bool $usePrefs If true, the user's preference is used
2188 * if false, the site/language default is used
2189 * if int/string, assumed to be a format.
2190 * @return string
2191 */
2192 function dateFormat( $usePrefs = true ) {
2193 global $wgUser;
2194
2195 if ( is_bool( $usePrefs ) ) {
2196 if ( $usePrefs ) {
2197 $datePreference = $wgUser->getDatePreference();
2198 } else {
2199 $datePreference = (string)User::getDefaultOption( 'date' );
2200 }
2201 } else {
2202 $datePreference = (string)$usePrefs;
2203 }
2204
2205 // return int
2206 if ( $datePreference == '' ) {
2207 return 'default';
2208 }
2209
2210 return $datePreference;
2211 }
2212
2213 /**
2214 * Get a format string for a given type and preference
2215 * @param string $type May be 'date', 'time', 'both', or 'pretty'.
2216 * @param string $pref The format name as it appears in Messages*.php under
2217 * $datePreferences.
2218 *
2219 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2220 *
2221 * @return string
2222 */
2223 function getDateFormatString( $type, $pref ) {
2224 $wasDefault = false;
2225 if ( $pref == 'default' ) {
2226 $wasDefault = true;
2227 $pref = $this->getDefaultDateFormat();
2228 }
2229
2230 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2231 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2232
2233 if ( $type === 'pretty' && $df === null ) {
2234 $df = $this->getDateFormatString( 'date', $pref );
2235 }
2236
2237 if ( !$wasDefault && $df === null ) {
2238 $pref = $this->getDefaultDateFormat();
2239 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2240 }
2241
2242 $this->dateFormatStrings[$type][$pref] = $df;
2243 }
2244 return $this->dateFormatStrings[$type][$pref];
2245 }
2246
2247 /**
2248 * @param string $ts The time format which needs to be turned into a
2249 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2250 * @param bool $adj Whether to adjust the time output according to the
2251 * user configured offset ($timecorrection)
2252 * @param mixed $format True to use user's date format preference
2253 * @param string|bool $timecorrection The time offset as returned by
2254 * validateTimeZone() in Special:Preferences
2255 * @return string
2256 */
2257 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2258 $ts = wfTimestamp( TS_MW, $ts );
2259 if ( $adj ) {
2260 $ts = $this->userAdjust( $ts, $timecorrection );
2261 }
2262 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2263 return $this->sprintfDate( $df, $ts );
2264 }
2265
2266 /**
2267 * @param string $ts The time format which needs to be turned into a
2268 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2269 * @param bool $adj Whether to adjust the time output according to the
2270 * user configured offset ($timecorrection)
2271 * @param mixed $format True to use user's date format preference
2272 * @param string|bool $timecorrection The time offset as returned by
2273 * validateTimeZone() in Special:Preferences
2274 * @return string
2275 */
2276 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2277 $ts = wfTimestamp( TS_MW, $ts );
2278 if ( $adj ) {
2279 $ts = $this->userAdjust( $ts, $timecorrection );
2280 }
2281 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2282 return $this->sprintfDate( $df, $ts );
2283 }
2284
2285 /**
2286 * @param string $ts The time format which needs to be turned into a
2287 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2288 * @param bool $adj Whether to adjust the time output according to the
2289 * user configured offset ($timecorrection)
2290 * @param mixed $format What format to return, if it's false output the
2291 * default one (default true)
2292 * @param string|bool $timecorrection The time offset as returned by
2293 * validateTimeZone() in Special:Preferences
2294 * @return string
2295 */
2296 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2297 $ts = wfTimestamp( TS_MW, $ts );
2298 if ( $adj ) {
2299 $ts = $this->userAdjust( $ts, $timecorrection );
2300 }
2301 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2302 return $this->sprintfDate( $df, $ts );
2303 }
2304
2305 /**
2306 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2307 *
2308 * @since 1.20
2309 *
2310 * @param int $seconds The amount of seconds.
2311 * @param array $chosenIntervals The intervals to enable.
2312 *
2313 * @return string
2314 */
2315 public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2316 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2317
2318 $segments = [];
2319
2320 foreach ( $intervals as $intervalName => $intervalValue ) {
2321 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2322 // duration-years, duration-decades, duration-centuries, duration-millennia
2323 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2324 $segments[] = $message->inLanguage( $this )->escaped();
2325 }
2326
2327 return $this->listToText( $segments );
2328 }
2329
2330 /**
2331 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2332 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2333 *
2334 * @since 1.20
2335 *
2336 * @param int $seconds The amount of seconds.
2337 * @param array $chosenIntervals The intervals to enable.
2338 *
2339 * @return array
2340 */
2341 public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2342 if ( empty( $chosenIntervals ) ) {
2343 $chosenIntervals = [
2344 'millennia',
2345 'centuries',
2346 'decades',
2347 'years',
2348 'days',
2349 'hours',
2350 'minutes',
2351 'seconds'
2352 ];
2353 }
2354
2355 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2356 $sortedNames = array_keys( $intervals );
2357 $smallestInterval = array_pop( $sortedNames );
2358
2359 $segments = [];
2360
2361 foreach ( $intervals as $name => $length ) {
2362 $value = floor( $seconds / $length );
2363
2364 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2365 $seconds -= $value * $length;
2366 $segments[$name] = $value;
2367 }
2368 }
2369
2370 return $segments;
2371 }
2372
2373 /**
2374 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2375 *
2376 * @param string $type Can be 'date', 'time' or 'both'
2377 * @param string $ts The time format which needs to be turned into a
2378 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2379 * @param User $user User object used to get preferences for timezone and format
2380 * @param array $options Array, can contain the following keys:
2381 * - 'timecorrection': time correction, can have the following values:
2382 * - true: use user's preference
2383 * - false: don't use time correction
2384 * - int: value of time correction in minutes
2385 * - 'format': format to use, can have the following values:
2386 * - true: use user's preference
2387 * - false: use default preference
2388 * - string: format to use
2389 * @since 1.19
2390 * @return string
2391 */
2392 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2393 $ts = wfTimestamp( TS_MW, $ts );
2394 $options += [ 'timecorrection' => true, 'format' => true ];
2395 if ( $options['timecorrection'] !== false ) {
2396 if ( $options['timecorrection'] === true ) {
2397 $offset = $user->getOption( 'timecorrection' );
2398 } else {
2399 $offset = $options['timecorrection'];
2400 }
2401 $ts = $this->userAdjust( $ts, $offset );
2402 }
2403 if ( $options['format'] === true ) {
2404 $format = $user->getDatePreference();
2405 } else {
2406 $format = $options['format'];
2407 }
2408 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2409 return $this->sprintfDate( $df, $ts );
2410 }
2411
2412 /**
2413 * Get the formatted date for the given timestamp and formatted for
2414 * the given user.
2415 *
2416 * @param mixed $ts Mixed: the time format which needs to be turned into a
2417 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2418 * @param User $user User object used to get preferences for timezone and format
2419 * @param array $options Array, can contain the following keys:
2420 * - 'timecorrection': time correction, can have the following values:
2421 * - true: use user's preference
2422 * - false: don't use time correction
2423 * - int: value of time correction in minutes
2424 * - 'format': format to use, can have the following values:
2425 * - true: use user's preference
2426 * - false: use default preference
2427 * - string: format to use
2428 * @since 1.19
2429 * @return string
2430 */
2431 public function userDate( $ts, User $user, array $options = [] ) {
2432 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2433 }
2434
2435 /**
2436 * Get the formatted time for the given timestamp and formatted for
2437 * the given user.
2438 *
2439 * @param mixed $ts The time format which needs to be turned into a
2440 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2441 * @param User $user User object used to get preferences for timezone and format
2442 * @param array $options Array, can contain the following keys:
2443 * - 'timecorrection': time correction, can have the following values:
2444 * - true: use user's preference
2445 * - false: don't use time correction
2446 * - int: value of time correction in minutes
2447 * - 'format': format to use, can have the following values:
2448 * - true: use user's preference
2449 * - false: use default preference
2450 * - string: format to use
2451 * @since 1.19
2452 * @return string
2453 */
2454 public function userTime( $ts, User $user, array $options = [] ) {
2455 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2456 }
2457
2458 /**
2459 * Get the formatted date and time for the given timestamp and formatted for
2460 * the given user.
2461 *
2462 * @param mixed $ts The time format which needs to be turned into a
2463 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2464 * @param User $user User object used to get preferences for timezone and format
2465 * @param array $options Array, can contain the following keys:
2466 * - 'timecorrection': time correction, can have the following values:
2467 * - true: use user's preference
2468 * - false: don't use time correction
2469 * - int: value of time correction in minutes
2470 * - 'format': format to use, can have the following values:
2471 * - true: use user's preference
2472 * - false: use default preference
2473 * - string: format to use
2474 * @since 1.19
2475 * @return string
2476 */
2477 public function userTimeAndDate( $ts, User $user, array $options = [] ) {
2478 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2479 }
2480
2481 /**
2482 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
2483 *
2484 * Determine the difference between the timestamp and the current time, and
2485 * generate a readable timestamp by returning "<N> <units> ago", where the
2486 * largest possible unit is used.
2487 *
2488 * @since 1.26 (Prior to 1.26 method existed but was not meant to be used directly)
2489 *
2490 * @param MWTimestamp $time
2491 * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
2492 * @param User|null $user User the timestamp is being generated for
2493 * (or null to use main context's user)
2494 * @return string Formatted timestamp
2495 */
2496 public function getHumanTimestamp(
2497 MWTimestamp $time, MWTimestamp $relativeTo = null, User $user = null
2498 ) {
2499 if ( $relativeTo === null ) {
2500 $relativeTo = new MWTimestamp();
2501 }
2502 if ( $user === null ) {
2503 $user = RequestContext::getMain()->getUser();
2504 }
2505
2506 // Adjust for the user's timezone.
2507 $offsetThis = $time->offsetForUser( $user );
2508 $offsetRel = $relativeTo->offsetForUser( $user );
2509
2510 $ts = '';
2511 if ( Hooks::run( 'GetHumanTimestamp', [ &$ts, $time, $relativeTo, $user, $this ] ) ) {
2512 $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2513 }
2514
2515 // Reset the timezone on the objects.
2516 $time->timestamp->sub( $offsetThis );
2517 $relativeTo->timestamp->sub( $offsetRel );
2518
2519 return $ts;
2520 }
2521
2522 /**
2523 * Convert an MWTimestamp into a pretty human-readable timestamp using
2524 * the given user preferences and relative base time.
2525 *
2526 * @see Language::getHumanTimestamp
2527 * @param MWTimestamp $ts Timestamp to prettify
2528 * @param MWTimestamp $relativeTo Base timestamp
2529 * @param User $user User preferences to use
2530 * @return string Human timestamp
2531 * @since 1.26
2532 */
2533 private function getHumanTimestampInternal(
2534 MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2535 ) {
2536 $diff = $ts->diff( $relativeTo );
2537 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2538 (int)$relativeTo->timestamp->format( 'w' ) );
2539 $days = $diff->days ?: (int)$diffDay;
2540 if ( $diff->invert || $days > 5
2541 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2542 ) {
2543 // Timestamps are in different years: use full timestamp
2544 // Also do full timestamp for future dates
2545 /**
2546 * @todo FIXME: Add better handling of future timestamps.
2547 */
2548 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2549 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2550 } elseif ( $days > 5 ) {
2551 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2552 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2553 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2554 } elseif ( $days > 1 ) {
2555 // Timestamp within the past week: show the day of the week and time
2556 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2557 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2558 // Messages:
2559 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2560 $ts = wfMessage( "$weekday-at" )
2561 ->inLanguage( $this )
2562 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2563 ->text();
2564 } elseif ( $days == 1 ) {
2565 // Timestamp was yesterday: say 'yesterday' and the time.
2566 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2567 $ts = wfMessage( 'yesterday-at' )
2568 ->inLanguage( $this )
2569 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2570 ->text();
2571 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2572 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2573 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2574 $ts = wfMessage( 'today-at' )
2575 ->inLanguage( $this )
2576 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2577 ->text();
2578
2579 // From here on in, the timestamp was soon enough ago so that we can simply say
2580 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2581 } elseif ( $diff->h == 1 ) {
2582 // Less than 90 minutes, but more than an hour ago.
2583 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2584 } elseif ( $diff->i >= 1 ) {
2585 // A few minutes ago.
2586 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2587 } elseif ( $diff->s >= 30 ) {
2588 // Less than a minute, but more than 30 sec ago.
2589 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2590 } else {
2591 // Less than 30 seconds ago.
2592 $ts = wfMessage( 'just-now' )->text();
2593 }
2594
2595 return $ts;
2596 }
2597
2598 /**
2599 * @param string $key
2600 * @return array|null
2601 */
2602 function getMessage( $key ) {
2603 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2604 }
2605
2606 /**
2607 * @return array
2608 */
2609 function getAllMessages() {
2610 return self::$dataCache->getItem( $this->mCode, 'messages' );
2611 }
2612
2613 /**
2614 * @param string $in
2615 * @param string $out
2616 * @param string $string
2617 * @return string
2618 */
2619 function iconv( $in, $out, $string ) {
2620 # This is a wrapper for iconv in all languages except esperanto,
2621 # which does some nasty x-conversions beforehand
2622
2623 # Even with //IGNORE iconv can whine about illegal characters in
2624 # *input* string. We just ignore those too.
2625 # REF: http://bugs.php.net/bug.php?id=37166
2626 # REF: https://phabricator.wikimedia.org/T18885
2627 MediaWiki\suppressWarnings();
2628 $text = iconv( $in, $out . '//IGNORE', $string );
2629 MediaWiki\restoreWarnings();
2630 return $text;
2631 }
2632
2633 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2634
2635 /**
2636 * @param array $matches
2637 * @return mixed|string
2638 */
2639 function ucwordbreaksCallbackAscii( $matches ) {
2640 return $this->ucfirst( $matches[1] );
2641 }
2642
2643 /**
2644 * @param array $matches
2645 * @return string
2646 */
2647 function ucwordbreaksCallbackMB( $matches ) {
2648 return mb_strtoupper( $matches[0] );
2649 }
2650
2651 /**
2652 * @param array $matches
2653 * @return string
2654 */
2655 function ucCallback( $matches ) {
2656 list( $wikiUpperChars ) = self::getCaseMaps();
2657 return strtr( $matches[1], $wikiUpperChars );
2658 }
2659
2660 /**
2661 * @param array $matches
2662 * @return string
2663 */
2664 function lcCallback( $matches ) {
2665 list( , $wikiLowerChars ) = self::getCaseMaps();
2666 return strtr( $matches[1], $wikiLowerChars );
2667 }
2668
2669 /**
2670 * @param array $matches
2671 * @return string
2672 */
2673 function ucwordsCallbackMB( $matches ) {
2674 return mb_strtoupper( $matches[0] );
2675 }
2676
2677 /**
2678 * @param array $matches
2679 * @return string
2680 */
2681 function ucwordsCallbackWiki( $matches ) {
2682 list( $wikiUpperChars ) = self::getCaseMaps();
2683 return strtr( $matches[0], $wikiUpperChars );
2684 }
2685
2686 /**
2687 * Make a string's first character uppercase
2688 *
2689 * @param string $str
2690 *
2691 * @return string
2692 */
2693 function ucfirst( $str ) {
2694 $o = ord( $str );
2695 if ( $o < 96 ) { // if already uppercase...
2696 return $str;
2697 } elseif ( $o < 128 ) {
2698 return ucfirst( $str ); // use PHP's ucfirst()
2699 } else {
2700 // fall back to more complex logic in case of multibyte strings
2701 return $this->uc( $str, true );
2702 }
2703 }
2704
2705 /**
2706 * Convert a string to uppercase
2707 *
2708 * @param string $str
2709 * @param bool $first
2710 *
2711 * @return string
2712 */
2713 function uc( $str, $first = false ) {
2714 if ( function_exists( 'mb_strtoupper' ) ) {
2715 if ( $first ) {
2716 if ( $this->isMultibyte( $str ) ) {
2717 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2718 } else {
2719 return ucfirst( $str );
2720 }
2721 } else {
2722 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2723 }
2724 } else {
2725 if ( $this->isMultibyte( $str ) ) {
2726 $x = $first ? '^' : '';
2727 return preg_replace_callback(
2728 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2729 [ $this, 'ucCallback' ],
2730 $str
2731 );
2732 } else {
2733 return $first ? ucfirst( $str ) : strtoupper( $str );
2734 }
2735 }
2736 }
2737
2738 /**
2739 * @param string $str
2740 * @return mixed|string
2741 */
2742 function lcfirst( $str ) {
2743 $o = ord( $str );
2744 if ( !$o ) {
2745 return strval( $str );
2746 } elseif ( $o >= 128 ) {
2747 return $this->lc( $str, true );
2748 } elseif ( $o > 96 ) {
2749 return $str;
2750 } else {
2751 $str[0] = strtolower( $str[0] );
2752 return $str;
2753 }
2754 }
2755
2756 /**
2757 * @param string $str
2758 * @param bool $first
2759 * @return mixed|string
2760 */
2761 function lc( $str, $first = false ) {
2762 if ( function_exists( 'mb_strtolower' ) ) {
2763 if ( $first ) {
2764 if ( $this->isMultibyte( $str ) ) {
2765 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2766 } else {
2767 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2768 }
2769 } else {
2770 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2771 }
2772 } else {
2773 if ( $this->isMultibyte( $str ) ) {
2774 $x = $first ? '^' : '';
2775 return preg_replace_callback(
2776 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2777 [ $this, 'lcCallback' ],
2778 $str
2779 );
2780 } else {
2781 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2782 }
2783 }
2784 }
2785
2786 /**
2787 * @param string $str
2788 * @return bool
2789 */
2790 function isMultibyte( $str ) {
2791 return strlen( $str ) !== mb_strlen( $str );
2792 }
2793
2794 /**
2795 * @param string $str
2796 * @return mixed|string
2797 */
2798 function ucwords( $str ) {
2799 if ( $this->isMultibyte( $str ) ) {
2800 $str = $this->lc( $str );
2801
2802 // regexp to find first letter in each word (i.e. after each space)
2803 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2804
2805 // function to use to capitalize a single char
2806 if ( function_exists( 'mb_strtoupper' ) ) {
2807 return preg_replace_callback(
2808 $replaceRegexp,
2809 [ $this, 'ucwordsCallbackMB' ],
2810 $str
2811 );
2812 } else {
2813 return preg_replace_callback(
2814 $replaceRegexp,
2815 [ $this, 'ucwordsCallbackWiki' ],
2816 $str
2817 );
2818 }
2819 } else {
2820 return ucwords( strtolower( $str ) );
2821 }
2822 }
2823
2824 /**
2825 * capitalize words at word breaks
2826 *
2827 * @param string $str
2828 * @return mixed
2829 */
2830 function ucwordbreaks( $str ) {
2831 if ( $this->isMultibyte( $str ) ) {
2832 $str = $this->lc( $str );
2833
2834 // since \b doesn't work for UTF-8, we explicitely define word break chars
2835 $breaks = "[ \-\(\)\}\{\.,\?!]";
2836
2837 // find first letter after word break
2838 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2839 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2840
2841 if ( function_exists( 'mb_strtoupper' ) ) {
2842 return preg_replace_callback(
2843 $replaceRegexp,
2844 [ $this, 'ucwordbreaksCallbackMB' ],
2845 $str
2846 );
2847 } else {
2848 return preg_replace_callback(
2849 $replaceRegexp,
2850 [ $this, 'ucwordsCallbackWiki' ],
2851 $str
2852 );
2853 }
2854 } else {
2855 return preg_replace_callback(
2856 '/\b([\w\x80-\xff]+)\b/',
2857 [ $this, 'ucwordbreaksCallbackAscii' ],
2858 $str
2859 );
2860 }
2861 }
2862
2863 /**
2864 * Return a case-folded representation of $s
2865 *
2866 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2867 * and $s2 are the same except for the case of their characters. It is not
2868 * necessary for the value returned to make sense when displayed.
2869 *
2870 * Do *not* perform any other normalisation in this function. If a caller
2871 * uses this function when it should be using a more general normalisation
2872 * function, then fix the caller.
2873 *
2874 * @param string $s
2875 *
2876 * @return string
2877 */
2878 function caseFold( $s ) {
2879 return $this->uc( $s );
2880 }
2881
2882 /**
2883 * @param string $s
2884 * @return string
2885 */
2886 function checkTitleEncoding( $s ) {
2887 if ( is_array( $s ) ) {
2888 throw new MWException( 'Given array to checkTitleEncoding.' );
2889 }
2890 if ( StringUtils::isUtf8( $s ) ) {
2891 return $s;
2892 }
2893
2894 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2895 }
2896
2897 /**
2898 * @return array
2899 */
2900 function fallback8bitEncoding() {
2901 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2902 }
2903
2904 /**
2905 * Most writing systems use whitespace to break up words.
2906 * Some languages such as Chinese don't conventionally do this,
2907 * which requires special handling when breaking up words for
2908 * searching etc.
2909 *
2910 * @return bool
2911 */
2912 function hasWordBreaks() {
2913 return true;
2914 }
2915
2916 /**
2917 * Some languages such as Chinese require word segmentation,
2918 * Specify such segmentation when overridden in derived class.
2919 *
2920 * @param string $string
2921 * @return string
2922 */
2923 function segmentByWord( $string ) {
2924 return $string;
2925 }
2926
2927 /**
2928 * Some languages have special punctuation need to be normalized.
2929 * Make such changes here.
2930 *
2931 * @param string $string
2932 * @return string
2933 */
2934 function normalizeForSearch( $string ) {
2935 return self::convertDoubleWidth( $string );
2936 }
2937
2938 /**
2939 * convert double-width roman characters to single-width.
2940 * range: ff00-ff5f ~= 0020-007f
2941 *
2942 * @param string $string
2943 *
2944 * @return string
2945 */
2946 protected static function convertDoubleWidth( $string ) {
2947 static $full = null;
2948 static $half = null;
2949
2950 if ( $full === null ) {
2951 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2952 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2953 $full = str_split( $fullWidth, 3 );
2954 $half = str_split( $halfWidth );
2955 }
2956
2957 $string = str_replace( $full, $half, $string );
2958 return $string;
2959 }
2960
2961 /**
2962 * @param string $string
2963 * @param string $pattern
2964 * @return string
2965 */
2966 protected static function insertSpace( $string, $pattern ) {
2967 $string = preg_replace( $pattern, " $1 ", $string );
2968 $string = preg_replace( '/ +/', ' ', $string );
2969 return $string;
2970 }
2971
2972 /**
2973 * @param array $termsArray
2974 * @return array
2975 */
2976 function convertForSearchResult( $termsArray ) {
2977 # some languages, e.g. Chinese, need to do a conversion
2978 # in order for search results to be displayed correctly
2979 return $termsArray;
2980 }
2981
2982 /**
2983 * Get the first character of a string.
2984 *
2985 * @param string $s
2986 * @return string
2987 */
2988 function firstChar( $s ) {
2989 $matches = [];
2990 preg_match(
2991 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2992 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2993 $s,
2994 $matches
2995 );
2996
2997 if ( isset( $matches[1] ) ) {
2998 if ( strlen( $matches[1] ) != 3 ) {
2999 return $matches[1];
3000 }
3001
3002 // Break down Hangul syllables to grab the first jamo
3003 $code = UtfNormal\Utils::utf8ToCodepoint( $matches[1] );
3004 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
3005 return $matches[1];
3006 } elseif ( $code < 0xb098 ) {
3007 return "\xe3\x84\xb1";
3008 } elseif ( $code < 0xb2e4 ) {
3009 return "\xe3\x84\xb4";
3010 } elseif ( $code < 0xb77c ) {
3011 return "\xe3\x84\xb7";
3012 } elseif ( $code < 0xb9c8 ) {
3013 return "\xe3\x84\xb9";
3014 } elseif ( $code < 0xbc14 ) {
3015 return "\xe3\x85\x81";
3016 } elseif ( $code < 0xc0ac ) {
3017 return "\xe3\x85\x82";
3018 } elseif ( $code < 0xc544 ) {
3019 return "\xe3\x85\x85";
3020 } elseif ( $code < 0xc790 ) {
3021 return "\xe3\x85\x87";
3022 } elseif ( $code < 0xcc28 ) {
3023 return "\xe3\x85\x88";
3024 } elseif ( $code < 0xce74 ) {
3025 return "\xe3\x85\x8a";
3026 } elseif ( $code < 0xd0c0 ) {
3027 return "\xe3\x85\x8b";
3028 } elseif ( $code < 0xd30c ) {
3029 return "\xe3\x85\x8c";
3030 } elseif ( $code < 0xd558 ) {
3031 return "\xe3\x85\x8d";
3032 } else {
3033 return "\xe3\x85\x8e";
3034 }
3035 } else {
3036 return '';
3037 }
3038 }
3039
3040 function initEncoding() {
3041 # Some languages may have an alternate char encoding option
3042 # (Esperanto X-coding, Japanese furigana conversion, etc)
3043 # If this language is used as the primary content language,
3044 # an override to the defaults can be set here on startup.
3045 }
3046
3047 /**
3048 * @param string $s
3049 * @return string
3050 */
3051 function recodeForEdit( $s ) {
3052 # For some languages we'll want to explicitly specify
3053 # which characters make it into the edit box raw
3054 # or are converted in some way or another.
3055 global $wgEditEncoding;
3056 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
3057 return $s;
3058 } else {
3059 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
3060 }
3061 }
3062
3063 /**
3064 * @param string $s
3065 * @return string
3066 */
3067 function recodeInput( $s ) {
3068 # Take the previous into account.
3069 global $wgEditEncoding;
3070 if ( $wgEditEncoding != '' ) {
3071 $enc = $wgEditEncoding;
3072 } else {
3073 $enc = 'UTF-8';
3074 }
3075 if ( $enc == 'UTF-8' ) {
3076 return $s;
3077 } else {
3078 return $this->iconv( $enc, 'UTF-8', $s );
3079 }
3080 }
3081
3082 /**
3083 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
3084 * also cleans up certain backwards-compatible sequences, converting them
3085 * to the modern Unicode equivalent.
3086 *
3087 * This is language-specific for performance reasons only.
3088 *
3089 * @param string $s
3090 *
3091 * @return string
3092 */
3093 function normalize( $s ) {
3094 global $wgAllUnicodeFixes;
3095 $s = UtfNormal\Validator::cleanUp( $s );
3096 if ( $wgAllUnicodeFixes ) {
3097 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
3098 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
3099 }
3100
3101 return $s;
3102 }
3103
3104 /**
3105 * Transform a string using serialized data stored in the given file (which
3106 * must be in the serialized subdirectory of $IP). The file contains pairs
3107 * mapping source characters to destination characters.
3108 *
3109 * The data is cached in process memory. This will go faster if you have the
3110 * FastStringSearch extension.
3111 *
3112 * @param string $file
3113 * @param string $string
3114 *
3115 * @throws MWException
3116 * @return string
3117 */
3118 function transformUsingPairFile( $file, $string ) {
3119 if ( !isset( $this->transformData[$file] ) ) {
3120 $data = wfGetPrecompiledData( $file );
3121 if ( $data === false ) {
3122 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
3123 }
3124 $this->transformData[$file] = new ReplacementArray( $data );
3125 }
3126 return $this->transformData[$file]->replace( $string );
3127 }
3128
3129 /**
3130 * For right-to-left language support
3131 *
3132 * @return bool
3133 */
3134 function isRTL() {
3135 return self::$dataCache->getItem( $this->mCode, 'rtl' );
3136 }
3137
3138 /**
3139 * Return the correct HTML 'dir' attribute value for this language.
3140 * @return string
3141 */
3142 function getDir() {
3143 return $this->isRTL() ? 'rtl' : 'ltr';
3144 }
3145
3146 /**
3147 * Return 'left' or 'right' as appropriate alignment for line-start
3148 * for this language's text direction.
3149 *
3150 * Should be equivalent to CSS3 'start' text-align value....
3151 *
3152 * @return string
3153 */
3154 function alignStart() {
3155 return $this->isRTL() ? 'right' : 'left';
3156 }
3157
3158 /**
3159 * Return 'right' or 'left' as appropriate alignment for line-end
3160 * for this language's text direction.
3161 *
3162 * Should be equivalent to CSS3 'end' text-align value....
3163 *
3164 * @return string
3165 */
3166 function alignEnd() {
3167 return $this->isRTL() ? 'left' : 'right';
3168 }
3169
3170 /**
3171 * A hidden direction mark (LRM or RLM), depending on the language direction.
3172 * Unlike getDirMark(), this function returns the character as an HTML entity.
3173 * This function should be used when the output is guaranteed to be HTML,
3174 * because it makes the output HTML source code more readable. When
3175 * the output is plain text or can be escaped, getDirMark() should be used.
3176 *
3177 * @param bool $opposite Get the direction mark opposite to your language
3178 * @return string
3179 * @since 1.20
3180 */
3181 function getDirMarkEntity( $opposite = false ) {
3182 if ( $opposite ) {
3183 return $this->isRTL() ? '&lrm;' : '&rlm;';
3184 }
3185 return $this->isRTL() ? '&rlm;' : '&lrm;';
3186 }
3187
3188 /**
3189 * A hidden direction mark (LRM or RLM), depending on the language direction.
3190 * This function produces them as invisible Unicode characters and
3191 * the output may be hard to read and debug, so it should only be used
3192 * when the output is plain text or can be escaped. When the output is
3193 * HTML, use getDirMarkEntity() instead.
3194 *
3195 * @param bool $opposite Get the direction mark opposite to your language
3196 * @return string
3197 */
3198 function getDirMark( $opposite = false ) {
3199 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3200 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3201 if ( $opposite ) {
3202 return $this->isRTL() ? $lrm : $rlm;
3203 }
3204 return $this->isRTL() ? $rlm : $lrm;
3205 }
3206
3207 /**
3208 * @return array
3209 */
3210 function capitalizeAllNouns() {
3211 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3212 }
3213
3214 /**
3215 * An arrow, depending on the language direction.
3216 *
3217 * @param string $direction The direction of the arrow: forwards (default),
3218 * backwards, left, right, up, down.
3219 * @return string
3220 */
3221 function getArrow( $direction = 'forwards' ) {
3222 switch ( $direction ) {
3223 case 'forwards':
3224 return $this->isRTL() ? '←' : '→';
3225 case 'backwards':
3226 return $this->isRTL() ? '→' : '←';
3227 case 'left':
3228 return '←';
3229 case 'right':
3230 return '→';
3231 case 'up':
3232 return '↑';
3233 case 'down':
3234 return '↓';
3235 }
3236 }
3237
3238 /**
3239 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3240 *
3241 * @return bool
3242 */
3243 function linkPrefixExtension() {
3244 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
3245 }
3246
3247 /**
3248 * Get all magic words from cache.
3249 * @return array
3250 */
3251 function getMagicWords() {
3252 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
3253 }
3254
3255 /**
3256 * Run the LanguageGetMagic hook once.
3257 */
3258 protected function doMagicHook() {
3259 if ( $this->mMagicHookDone ) {
3260 return;
3261 }
3262 $this->mMagicHookDone = true;
3263 Hooks::run( 'LanguageGetMagic', [ &$this->mMagicExtensions, $this->getCode() ] );
3264 }
3265
3266 /**
3267 * Fill a MagicWord object with data from here
3268 *
3269 * @param MagicWord $mw
3270 */
3271 function getMagic( $mw ) {
3272 // Saves a function call
3273 if ( !$this->mMagicHookDone ) {
3274 $this->doMagicHook();
3275 }
3276
3277 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3278 $rawEntry = $this->mMagicExtensions[$mw->mId];
3279 } else {
3280 $rawEntry = self::$dataCache->getSubitem(
3281 $this->mCode, 'magicWords', $mw->mId );
3282 }
3283
3284 if ( !is_array( $rawEntry ) ) {
3285 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3286 } else {
3287 $mw->mCaseSensitive = $rawEntry[0];
3288 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3289 }
3290 }
3291
3292 /**
3293 * Add magic words to the extension array
3294 *
3295 * @param array $newWords
3296 */
3297 function addMagicWordsByLang( $newWords ) {
3298 $fallbackChain = $this->getFallbackLanguages();
3299 $fallbackChain = array_reverse( $fallbackChain );
3300 foreach ( $fallbackChain as $code ) {
3301 if ( isset( $newWords[$code] ) ) {
3302 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3303 }
3304 }
3305 }
3306
3307 /**
3308 * Get special page names, as an associative array
3309 * canonical name => array of valid names, including aliases
3310 * @return array
3311 */
3312 function getSpecialPageAliases() {
3313 // Cache aliases because it may be slow to load them
3314 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3315 // Initialise array
3316 $this->mExtendedSpecialPageAliases =
3317 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3318 Hooks::run( 'LanguageGetSpecialPageAliases',
3319 [ &$this->mExtendedSpecialPageAliases, $this->getCode() ] );
3320 }
3321
3322 return $this->mExtendedSpecialPageAliases;
3323 }
3324
3325 /**
3326 * Italic is unsuitable for some languages
3327 *
3328 * @param string $text The text to be emphasized.
3329 * @return string
3330 */
3331 function emphasize( $text ) {
3332 return "<em>$text</em>";
3333 }
3334
3335 /**
3336 * Normally we output all numbers in plain en_US style, that is
3337 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3338 * point twohundredthirtyfive. However this is not suitable for all
3339 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3340 * Icelandic just want to use commas instead of dots, and dots instead
3341 * of commas like "293.291,235".
3342 *
3343 * An example of this function being called:
3344 * <code>
3345 * wfMessage( 'message' )->numParams( $num )->text()
3346 * </code>
3347 *
3348 * See $separatorTransformTable on MessageIs.php for
3349 * the , => . and . => , implementation.
3350 *
3351 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3352 * @param int|float $number The string to be formatted, should be an integer
3353 * or a floating point number.
3354 * @param bool $nocommafy Set to true for special numbers like dates
3355 * @return string
3356 */
3357 public function formatNum( $number, $nocommafy = false ) {
3358 global $wgTranslateNumerals;
3359 if ( !$nocommafy ) {
3360 $number = $this->commafy( $number );
3361 $s = $this->separatorTransformTable();
3362 if ( $s ) {
3363 $number = strtr( $number, $s );
3364 }
3365 }
3366
3367 if ( $wgTranslateNumerals ) {
3368 $s = $this->digitTransformTable();
3369 if ( $s ) {
3370 $number = strtr( $number, $s );
3371 }
3372 }
3373
3374 return $number;
3375 }
3376
3377 /**
3378 * Front-end for non-commafied formatNum
3379 *
3380 * @param int|float $number The string to be formatted, should be an integer
3381 * or a floating point number.
3382 * @since 1.21
3383 * @return string
3384 */
3385 public function formatNumNoSeparators( $number ) {
3386 return $this->formatNum( $number, true );
3387 }
3388
3389 /**
3390 * @param string $number
3391 * @return string
3392 */
3393 public function parseFormattedNumber( $number ) {
3394 $s = $this->digitTransformTable();
3395 if ( $s ) {
3396 // eliminate empty array values such as ''. (bug 64347)
3397 $s = array_filter( $s );
3398 $number = strtr( $number, array_flip( $s ) );
3399 }
3400
3401 $s = $this->separatorTransformTable();
3402 if ( $s ) {
3403 // eliminate empty array values such as ''. (bug 64347)
3404 $s = array_filter( $s );
3405 $number = strtr( $number, array_flip( $s ) );
3406 }
3407
3408 $number = strtr( $number, [ ',' => '' ] );
3409 return $number;
3410 }
3411
3412 /**
3413 * Adds commas to a given number
3414 * @since 1.19
3415 * @param mixed $number
3416 * @return string
3417 */
3418 function commafy( $number ) {
3419 $digitGroupingPattern = $this->digitGroupingPattern();
3420 if ( $number === null ) {
3421 return '';
3422 }
3423
3424 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3425 // default grouping is at thousands, use the same for ###,###,### pattern too.
3426 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3427 } else {
3428 // Ref: http://cldr.unicode.org/translation/number-patterns
3429 $sign = "";
3430 if ( intval( $number ) < 0 ) {
3431 // For negative numbers apply the algorithm like positive number and add sign.
3432 $sign = "-";
3433 $number = substr( $number, 1 );
3434 }
3435 $integerPart = [];
3436 $decimalPart = [];
3437 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3438 preg_match( "/\d+/", $number, $integerPart );
3439 preg_match( "/\.\d*/", $number, $decimalPart );
3440 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3441 if ( $groupedNumber === $number ) {
3442 // the string does not have any number part. Eg: .12345
3443 return $sign . $groupedNumber;
3444 }
3445 $start = $end = ( $integerPart ) ? strlen( $integerPart[0] ) : 0;
3446 while ( $start > 0 ) {
3447 $match = $matches[0][$numMatches - 1];
3448 $matchLen = strlen( $match );
3449 $start = $end - $matchLen;
3450 if ( $start < 0 ) {
3451 $start = 0;
3452 }
3453 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3454 $end = $start;
3455 if ( $numMatches > 1 ) {
3456 // use the last pattern for the rest of the number
3457 $numMatches--;
3458 }
3459 if ( $start > 0 ) {
3460 $groupedNumber = "," . $groupedNumber;
3461 }
3462 }
3463 return $sign . $groupedNumber;
3464 }
3465 }
3466
3467 /**
3468 * @return string
3469 */
3470 function digitGroupingPattern() {
3471 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3472 }
3473
3474 /**
3475 * @return array
3476 */
3477 function digitTransformTable() {
3478 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3479 }
3480
3481 /**
3482 * @return array
3483 */
3484 function separatorTransformTable() {
3485 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3486 }
3487
3488 /**
3489 * Take a list of strings and build a locale-friendly comma-separated
3490 * list, using the local comma-separator message.
3491 * The last two strings are chained with an "and".
3492 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3493 *
3494 * @param string[] $l
3495 * @return string
3496 */
3497 function listToText( array $l ) {
3498 $m = count( $l ) - 1;
3499 if ( $m < 0 ) {
3500 return '';
3501 }
3502 if ( $m > 0 ) {
3503 $and = $this->msg( 'and' )->escaped();
3504 $space = $this->msg( 'word-separator' )->escaped();
3505 if ( $m > 1 ) {
3506 $comma = $this->msg( 'comma-separator' )->escaped();
3507 }
3508 }
3509 $s = $l[$m];
3510 for ( $i = $m - 1; $i >= 0; $i-- ) {
3511 if ( $i == $m - 1 ) {
3512 $s = $l[$i] . $and . $space . $s;
3513 } else {
3514 $s = $l[$i] . $comma . $s;
3515 }
3516 }
3517 return $s;
3518 }
3519
3520 /**
3521 * Take a list of strings and build a locale-friendly comma-separated
3522 * list, using the local comma-separator message.
3523 * @param string[] $list Array of strings to put in a comma list
3524 * @return string
3525 */
3526 function commaList( array $list ) {
3527 return implode(
3528 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3529 $list
3530 );
3531 }
3532
3533 /**
3534 * Take a list of strings and build a locale-friendly semicolon-separated
3535 * list, using the local semicolon-separator message.
3536 * @param string[] $list Array of strings to put in a semicolon list
3537 * @return string
3538 */
3539 function semicolonList( array $list ) {
3540 return implode(
3541 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3542 $list
3543 );
3544 }
3545
3546 /**
3547 * Same as commaList, but separate it with the pipe instead.
3548 * @param string[] $list Array of strings to put in a pipe list
3549 * @return string
3550 */
3551 function pipeList( array $list ) {
3552 return implode(
3553 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3554 $list
3555 );
3556 }
3557
3558 /**
3559 * Truncate a string to a specified length in bytes, appending an optional
3560 * string (e.g. for ellipses)
3561 *
3562 * The database offers limited byte lengths for some columns in the database;
3563 * multi-byte character sets mean we need to ensure that only whole characters
3564 * are included, otherwise broken characters can be passed to the user
3565 *
3566 * If $length is negative, the string will be truncated from the beginning
3567 *
3568 * @param string $string String to truncate
3569 * @param int $length Maximum length (including ellipses)
3570 * @param string $ellipsis String to append to the truncated text
3571 * @param bool $adjustLength Subtract length of ellipsis from $length.
3572 * $adjustLength was introduced in 1.18, before that behaved as if false.
3573 * @return string
3574 */
3575 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3576 # Use the localized ellipsis character
3577 if ( $ellipsis == '...' ) {
3578 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3579 }
3580 # Check if there is no need to truncate
3581 if ( $length == 0 ) {
3582 return $ellipsis; // convention
3583 } elseif ( strlen( $string ) <= abs( $length ) ) {
3584 return $string; // no need to truncate
3585 }
3586 $stringOriginal = $string;
3587 # If ellipsis length is >= $length then we can't apply $adjustLength
3588 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3589 $string = $ellipsis; // this can be slightly unexpected
3590 # Otherwise, truncate and add ellipsis...
3591 } else {
3592 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3593 if ( $length > 0 ) {
3594 $length -= $eLength;
3595 $string = substr( $string, 0, $length ); // xyz...
3596 $string = $this->removeBadCharLast( $string );
3597 $string = rtrim( $string );
3598 $string = $string . $ellipsis;
3599 } else {
3600 $length += $eLength;
3601 $string = substr( $string, $length ); // ...xyz
3602 $string = $this->removeBadCharFirst( $string );
3603 $string = ltrim( $string );
3604 $string = $ellipsis . $string;
3605 }
3606 }
3607 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3608 # This check is *not* redundant if $adjustLength, due to the single case where
3609 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3610 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3611 return $string;
3612 } else {
3613 return $stringOriginal;
3614 }
3615 }
3616
3617 /**
3618 * Remove bytes that represent an incomplete Unicode character
3619 * at the end of string (e.g. bytes of the char are missing)
3620 *
3621 * @param string $string
3622 * @return string
3623 */
3624 protected function removeBadCharLast( $string ) {
3625 if ( $string != '' ) {
3626 $char = ord( $string[strlen( $string ) - 1] );
3627 $m = [];
3628 if ( $char >= 0xc0 ) {
3629 # We got the first byte only of a multibyte char; remove it.
3630 $string = substr( $string, 0, -1 );
3631 } elseif ( $char >= 0x80 &&
3632 // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3633 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3634 '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3635 ) {
3636 # We chopped in the middle of a character; remove it
3637 $string = $m[1];
3638 }
3639 }
3640 return $string;
3641 }
3642
3643 /**
3644 * Remove bytes that represent an incomplete Unicode character
3645 * at the start of string (e.g. bytes of the char are missing)
3646 *
3647 * @param string $string
3648 * @return string
3649 */
3650 protected function removeBadCharFirst( $string ) {
3651 if ( $string != '' ) {
3652 $char = ord( $string[0] );
3653 if ( $char >= 0x80 && $char < 0xc0 ) {
3654 # We chopped in the middle of a character; remove the whole thing
3655 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3656 }
3657 }
3658 return $string;
3659 }
3660
3661 /**
3662 * Truncate a string of valid HTML to a specified length in bytes,
3663 * appending an optional string (e.g. for ellipses), and return valid HTML
3664 *
3665 * This is only intended for styled/linked text, such as HTML with
3666 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3667 * Also, this will not detect things like "display:none" CSS.
3668 *
3669 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3670 *
3671 * @param string $text HTML string to truncate
3672 * @param int $length (zero/positive) Maximum length (including ellipses)
3673 * @param string $ellipsis String to append to the truncated text
3674 * @return string
3675 */
3676 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3677 # Use the localized ellipsis character
3678 if ( $ellipsis == '...' ) {
3679 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3680 }
3681 # Check if there is clearly no need to truncate
3682 if ( $length <= 0 ) {
3683 return $ellipsis; // no text shown, nothing to format (convention)
3684 } elseif ( strlen( $text ) <= $length ) {
3685 return $text; // string short enough even *with* HTML (short-circuit)
3686 }
3687
3688 $dispLen = 0; // innerHTML legth so far
3689 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3690 $tagType = 0; // 0-open, 1-close
3691 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3692 $entityState = 0; // 0-not entity, 1-entity
3693 $tag = $ret = ''; // accumulated tag name, accumulated result string
3694 $openTags = []; // open tag stack
3695 $maybeState = null; // possible truncation state
3696
3697 $textLen = strlen( $text );
3698 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3699 for ( $pos = 0; true; ++$pos ) {
3700 # Consider truncation once the display length has reached the maximim.
3701 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3702 # Check that we're not in the middle of a bracket/entity...
3703 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3704 if ( !$testingEllipsis ) {
3705 $testingEllipsis = true;
3706 # Save where we are; we will truncate here unless there turn out to
3707 # be so few remaining characters that truncation is not necessary.
3708 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3709 $maybeState = [ $ret, $openTags ]; // save state
3710 }
3711 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3712 # String in fact does need truncation, the truncation point was OK.
3713 list( $ret, $openTags ) = $maybeState; // reload state
3714 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3715 $ret .= $ellipsis; // add ellipsis
3716 break;
3717 }
3718 }
3719 if ( $pos >= $textLen ) {
3720 break; // extra iteration just for above checks
3721 }
3722
3723 # Read the next char...
3724 $ch = $text[$pos];
3725 $lastCh = $pos ? $text[$pos - 1] : '';
3726 $ret .= $ch; // add to result string
3727 if ( $ch == '<' ) {
3728 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3729 $entityState = 0; // for bad HTML
3730 $bracketState = 1; // tag started (checking for backslash)
3731 } elseif ( $ch == '>' ) {
3732 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3733 $entityState = 0; // for bad HTML
3734 $bracketState = 0; // out of brackets
3735 } elseif ( $bracketState == 1 ) {
3736 if ( $ch == '/' ) {
3737 $tagType = 1; // close tag (e.g. "</span>")
3738 } else {
3739 $tagType = 0; // open tag (e.g. "<span>")
3740 $tag .= $ch;
3741 }
3742 $bracketState = 2; // building tag name
3743 } elseif ( $bracketState == 2 ) {
3744 if ( $ch != ' ' ) {
3745 $tag .= $ch;
3746 } else {
3747 // Name found (e.g. "<a href=..."), add on tag attributes...
3748 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3749 }
3750 } elseif ( $bracketState == 0 ) {
3751 if ( $entityState ) {
3752 if ( $ch == ';' ) {
3753 $entityState = 0;
3754 $dispLen++; // entity is one displayed char
3755 }
3756 } else {
3757 if ( $neLength == 0 && !$maybeState ) {
3758 // Save state without $ch. We want to *hit* the first
3759 // display char (to get tags) but not *use* it if truncating.
3760 $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3761 }
3762 if ( $ch == '&' ) {
3763 $entityState = 1; // entity found, (e.g. "&#160;")
3764 } else {
3765 $dispLen++; // this char is displayed
3766 // Add the next $max display text chars after this in one swoop...
3767 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3768 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3769 $dispLen += $skipped;
3770 $pos += $skipped;
3771 }
3772 }
3773 }
3774 }
3775 // Close the last tag if left unclosed by bad HTML
3776 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3777 while ( count( $openTags ) > 0 ) {
3778 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3779 }
3780 return $ret;
3781 }
3782
3783 /**
3784 * truncateHtml() helper function
3785 * like strcspn() but adds the skipped chars to $ret
3786 *
3787 * @param string $ret
3788 * @param string $text
3789 * @param string $search
3790 * @param int $start
3791 * @param null|int $len
3792 * @return int
3793 */
3794 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3795 if ( $len === null ) {
3796 $len = -1; // -1 means "no limit" for strcspn
3797 } elseif ( $len < 0 ) {
3798 $len = 0; // sanity
3799 }
3800 $skipCount = 0;
3801 if ( $start < strlen( $text ) ) {
3802 $skipCount = strcspn( $text, $search, $start, $len );
3803 $ret .= substr( $text, $start, $skipCount );
3804 }
3805 return $skipCount;
3806 }
3807
3808 /**
3809 * truncateHtml() helper function
3810 * (a) push or pop $tag from $openTags as needed
3811 * (b) clear $tag value
3812 * @param string &$tag Current HTML tag name we are looking at
3813 * @param int $tagType (0-open tag, 1-close tag)
3814 * @param string $lastCh Character before the '>' that ended this tag
3815 * @param array &$openTags Open tag stack (not accounting for $tag)
3816 */
3817 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3818 $tag = ltrim( $tag );
3819 if ( $tag != '' ) {
3820 if ( $tagType == 0 && $lastCh != '/' ) {
3821 $openTags[] = $tag; // tag opened (didn't close itself)
3822 } elseif ( $tagType == 1 ) {
3823 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3824 array_pop( $openTags ); // tag closed
3825 }
3826 }
3827 $tag = '';
3828 }
3829 }
3830
3831 /**
3832 * Grammatical transformations, needed for inflected languages
3833 * Invoked by putting {{grammar:case|word}} in a message
3834 *
3835 * @param string $word
3836 * @param string $case
3837 * @return string
3838 */
3839 function convertGrammar( $word, $case ) {
3840 global $wgGrammarForms;
3841 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3842 return $wgGrammarForms[$this->getCode()][$case][$word];
3843 }
3844
3845 return $word;
3846 }
3847 /**
3848 * Get the grammar forms for the content language
3849 * @return array Array of grammar forms
3850 * @since 1.20
3851 */
3852 function getGrammarForms() {
3853 global $wgGrammarForms;
3854 if ( isset( $wgGrammarForms[$this->getCode()] )
3855 && is_array( $wgGrammarForms[$this->getCode()] )
3856 ) {
3857 return $wgGrammarForms[$this->getCode()];
3858 }
3859
3860 return [];
3861 }
3862 /**
3863 * Provides an alternative text depending on specified gender.
3864 * Usage {{gender:username|masculine|feminine|unknown}}.
3865 * username is optional, in which case the gender of current user is used,
3866 * but only in (some) interface messages; otherwise default gender is used.
3867 *
3868 * If no forms are given, an empty string is returned. If only one form is
3869 * given, it will be returned unconditionally. These details are implied by
3870 * the caller and cannot be overridden in subclasses.
3871 *
3872 * If three forms are given, the default is to use the third (unknown) form.
3873 * If fewer than three forms are given, the default is to use the first (masculine) form.
3874 * These details can be overridden in subclasses.
3875 *
3876 * @param string $gender
3877 * @param array $forms
3878 *
3879 * @return string
3880 */
3881 function gender( $gender, $forms ) {
3882 if ( !count( $forms ) ) {
3883 return '';
3884 }
3885 $forms = $this->preConvertPlural( $forms, 2 );
3886 if ( $gender === 'male' ) {
3887 return $forms[0];
3888 }
3889 if ( $gender === 'female' ) {
3890 return $forms[1];
3891 }
3892 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3893 }
3894
3895 /**
3896 * Plural form transformations, needed for some languages.
3897 * For example, there are 3 form of plural in Russian and Polish,
3898 * depending on "count mod 10". See [[w:Plural]]
3899 * For English it is pretty simple.
3900 *
3901 * Invoked by putting {{plural:count|wordform1|wordform2}}
3902 * or {{plural:count|wordform1|wordform2|wordform3}}
3903 *
3904 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3905 *
3906 * @param int $count Non-localized number
3907 * @param array $forms Different plural forms
3908 * @return string Correct form of plural for $count in this language
3909 */
3910 function convertPlural( $count, $forms ) {
3911 // Handle explicit n=pluralform cases
3912 $forms = $this->handleExplicitPluralForms( $count, $forms );
3913 if ( is_string( $forms ) ) {
3914 return $forms;
3915 }
3916 if ( !count( $forms ) ) {
3917 return '';
3918 }
3919
3920 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3921 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3922 return $forms[$pluralForm];
3923 }
3924
3925 /**
3926 * Handles explicit plural forms for Language::convertPlural()
3927 *
3928 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3929 * If an explicitly defined plural form matches the $count, then
3930 * string value returned, otherwise array returned for further consideration
3931 * by CLDR rules or overridden convertPlural().
3932 *
3933 * @since 1.23
3934 *
3935 * @param int $count Non-localized number
3936 * @param array $forms Different plural forms
3937 *
3938 * @return array|string
3939 */
3940 protected function handleExplicitPluralForms( $count, array $forms ) {
3941 foreach ( $forms as $index => $form ) {
3942 if ( preg_match( '/\d+=/i', $form ) ) {
3943 $pos = strpos( $form, '=' );
3944 if ( substr( $form, 0, $pos ) === (string)$count ) {
3945 return substr( $form, $pos + 1 );
3946 }
3947 unset( $forms[$index] );
3948 }
3949 }
3950 return array_values( $forms );
3951 }
3952
3953 /**
3954 * Checks that convertPlural was given an array and pads it to requested
3955 * amount of forms by copying the last one.
3956 *
3957 * @param array $forms Array of forms given to convertPlural
3958 * @param int $count How many forms should there be at least
3959 * @return array Padded array of forms or an exception if not an array
3960 */
3961 protected function preConvertPlural( /* Array */ $forms, $count ) {
3962 while ( count( $forms ) < $count ) {
3963 $forms[] = $forms[count( $forms ) - 1];
3964 }
3965 return $forms;
3966 }
3967
3968 /**
3969 * Wraps argument with unicode control characters for directionality safety
3970 *
3971 * This solves the problem where directionality-neutral characters at the edge of
3972 * the argument string get interpreted with the wrong directionality from the
3973 * enclosing context, giving renderings that look corrupted like "(Ben_(WMF".
3974 *
3975 * The wrapping is LRE...PDF or RLE...PDF, depending on the detected
3976 * directionality of the argument string, using the BIDI algorithm's own "First
3977 * strong directional codepoint" rule. Essentially, this works round the fact that
3978 * there is no embedding equivalent of U+2068 FSI (isolation with heuristic
3979 * direction inference). The latter is cleaner but still not widely supported.
3980 *
3981 * @param string $text Text to wrap
3982 * @return string Text, wrapped in LRE...PDF or RLE...PDF or nothing
3983 */
3984 public function embedBidi( $text = '' ) {
3985 $dir = Language::strongDirFromContent( $text );
3986 if ( $dir === 'ltr' ) {
3987 // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
3988 return self::$lre . $text . self::$pdf;
3989 }
3990 if ( $dir === 'rtl' ) {
3991 // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
3992 return self::$rle . $text . self::$pdf;
3993 }
3994 // No strong directionality: do not wrap
3995 return $text;
3996 }
3997
3998 /**
3999 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
4000 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
4001 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
4002 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
4003 * match up with it.
4004 *
4005 * @param string $str The validated block duration in English
4006 * @return string Somehow translated block duration
4007 * @see LanguageFi.php for example implementation
4008 */
4009 function translateBlockExpiry( $str ) {
4010 $duration = SpecialBlock::getSuggestedDurations( $this );
4011 foreach ( $duration as $show => $value ) {
4012 if ( strcmp( $str, $value ) == 0 ) {
4013 return htmlspecialchars( trim( $show ) );
4014 }
4015 }
4016
4017 if ( wfIsInfinity( $str ) ) {
4018 foreach ( $duration as $show => $value ) {
4019 if ( wfIsInfinity( $value ) ) {
4020 return htmlspecialchars( trim( $show ) );
4021 }
4022 }
4023 }
4024
4025 // If all else fails, return a standard duration or timestamp description.
4026 $time = strtotime( $str, 0 );
4027 if ( $time === false ) { // Unknown format. Return it as-is in case.
4028 return $str;
4029 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
4030 // $time is relative to 0 so it's a duration length.
4031 return $this->formatDuration( $time );
4032 } else { // It's an absolute timestamp.
4033 if ( $time === 0 ) {
4034 // wfTimestamp() handles 0 as current time instead of epoch.
4035 return $this->timeanddate( '19700101000000' );
4036 } else {
4037 return $this->timeanddate( $time );
4038 }
4039 }
4040 }
4041
4042 /**
4043 * languages like Chinese need to be segmented in order for the diff
4044 * to be of any use
4045 *
4046 * @param string $text
4047 * @return string
4048 */
4049 public function segmentForDiff( $text ) {
4050 return $text;
4051 }
4052
4053 /**
4054 * and unsegment to show the result
4055 *
4056 * @param string $text
4057 * @return string
4058 */
4059 public function unsegmentForDiff( $text ) {
4060 return $text;
4061 }
4062
4063 /**
4064 * Return the LanguageConverter used in the Language
4065 *
4066 * @since 1.19
4067 * @return LanguageConverter
4068 */
4069 public function getConverter() {
4070 return $this->mConverter;
4071 }
4072
4073 /**
4074 * convert text to all supported variants
4075 *
4076 * @param string $text
4077 * @return array
4078 */
4079 public function autoConvertToAllVariants( $text ) {
4080 return $this->mConverter->autoConvertToAllVariants( $text );
4081 }
4082
4083 /**
4084 * convert text to different variants of a language.
4085 *
4086 * @param string $text
4087 * @return string
4088 */
4089 public function convert( $text ) {
4090 return $this->mConverter->convert( $text );
4091 }
4092
4093 /**
4094 * Convert a Title object to a string in the preferred variant
4095 *
4096 * @param Title $title
4097 * @return string
4098 */
4099 public function convertTitle( $title ) {
4100 return $this->mConverter->convertTitle( $title );
4101 }
4102
4103 /**
4104 * Convert a namespace index to a string in the preferred variant
4105 *
4106 * @param int $ns
4107 * @return string
4108 */
4109 public function convertNamespace( $ns ) {
4110 return $this->mConverter->convertNamespace( $ns );
4111 }
4112
4113 /**
4114 * Check if this is a language with variants
4115 *
4116 * @return bool
4117 */
4118 public function hasVariants() {
4119 return count( $this->getVariants() ) > 1;
4120 }
4121
4122 /**
4123 * Check if the language has the specific variant
4124 *
4125 * @since 1.19
4126 * @param string $variant
4127 * @return bool
4128 */
4129 public function hasVariant( $variant ) {
4130 return (bool)$this->mConverter->validateVariant( $variant );
4131 }
4132
4133 /**
4134 * Perform output conversion on a string, and encode for safe HTML output.
4135 * @param string $text Text to be converted
4136 * @param bool $isTitle Whether this conversion is for the article title
4137 * @return string
4138 * @todo this should get integrated somewhere sane
4139 */
4140 public function convertHtml( $text, $isTitle = false ) {
4141 return htmlspecialchars( $this->convert( $text, $isTitle ) );
4142 }
4143
4144 /**
4145 * @param string $key
4146 * @return string
4147 */
4148 public function convertCategoryKey( $key ) {
4149 return $this->mConverter->convertCategoryKey( $key );
4150 }
4151
4152 /**
4153 * Get the list of variants supported by this language
4154 * see sample implementation in LanguageZh.php
4155 *
4156 * @return array An array of language codes
4157 */
4158 public function getVariants() {
4159 return $this->mConverter->getVariants();
4160 }
4161
4162 /**
4163 * @return string
4164 */
4165 public function getPreferredVariant() {
4166 return $this->mConverter->getPreferredVariant();
4167 }
4168
4169 /**
4170 * @return string
4171 */
4172 public function getDefaultVariant() {
4173 return $this->mConverter->getDefaultVariant();
4174 }
4175
4176 /**
4177 * @return string
4178 */
4179 public function getURLVariant() {
4180 return $this->mConverter->getURLVariant();
4181 }
4182
4183 /**
4184 * If a language supports multiple variants, it is
4185 * possible that non-existing link in one variant
4186 * actually exists in another variant. this function
4187 * tries to find it. See e.g. LanguageZh.php
4188 * The input parameters may be modified upon return
4189 *
4190 * @param string &$link The name of the link
4191 * @param Title &$nt The title object of the link
4192 * @param bool $ignoreOtherCond To disable other conditions when
4193 * we need to transclude a template or update a category's link
4194 */
4195 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4196 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
4197 }
4198
4199 /**
4200 * returns language specific options used by User::getPageRenderHash()
4201 * for example, the preferred language variant
4202 *
4203 * @return string
4204 */
4205 function getExtraHashOptions() {
4206 return $this->mConverter->getExtraHashOptions();
4207 }
4208
4209 /**
4210 * For languages that support multiple variants, the title of an
4211 * article may be displayed differently in different variants. this
4212 * function returns the apporiate title defined in the body of the article.
4213 *
4214 * @return string
4215 */
4216 public function getParsedTitle() {
4217 return $this->mConverter->getParsedTitle();
4218 }
4219
4220 /**
4221 * Refresh the cache of conversion tables when
4222 * MediaWiki:Conversiontable* is updated.
4223 *
4224 * @param Title $titleobj The Title of the page being updated
4225 */
4226 public function updateConversionTable( Title $title ) {
4227 $this->mConverter->updateConversionTable( $title );
4228 }
4229
4230 /**
4231 * Prepare external link text for conversion. When the text is
4232 * a URL, it shouldn't be converted, and it'll be wrapped in
4233 * the "raw" tag (-{R| }-) to prevent conversion.
4234 *
4235 * This function is called "markNoConversion" for historical
4236 * reasons.
4237 *
4238 * @param string $text Text to be used for external link
4239 * @param bool $noParse Wrap it without confirming it's a real URL first
4240 * @return string The tagged text
4241 */
4242 public function markNoConversion( $text, $noParse = false ) {
4243 // Excluding protocal-relative URLs may avoid many false positives.
4244 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
4245 return $this->mConverter->markNoConversion( $text );
4246 } else {
4247 return $text;
4248 }
4249 }
4250
4251 /**
4252 * A regular expression to match legal word-trailing characters
4253 * which should be merged onto a link of the form [[foo]]bar.
4254 *
4255 * @return string
4256 */
4257 public function linkTrail() {
4258 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
4259 }
4260
4261 /**
4262 * A regular expression character set to match legal word-prefixing
4263 * characters which should be merged onto a link of the form foo[[bar]].
4264 *
4265 * @return string
4266 */
4267 public function linkPrefixCharset() {
4268 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
4269 }
4270
4271 /**
4272 * @deprecated since 1.24, will be removed in 1.25
4273 * @return Language
4274 */
4275 function getLangObj() {
4276 wfDeprecated( __METHOD__, '1.24' );
4277 return $this;
4278 }
4279
4280 /**
4281 * Get the "parent" language which has a converter to convert a "compatible" language
4282 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4283 *
4284 * @return Language|null
4285 * @since 1.22
4286 */
4287 public function getParentLanguage() {
4288 if ( $this->mParentLanguage !== false ) {
4289 return $this->mParentLanguage;
4290 }
4291
4292 $code = explode( '-', $this->getCode() )[0];
4293 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4294 $this->mParentLanguage = null;
4295 return null;
4296 }
4297 $lang = Language::factory( $code );
4298 if ( !$lang->hasVariant( $this->getCode() ) ) {
4299 $this->mParentLanguage = null;
4300 return null;
4301 }
4302
4303 $this->mParentLanguage = $lang;
4304 return $lang;
4305 }
4306
4307 /**
4308 * Get the internal language code for this language object
4309 *
4310 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4311 * htmlspecialchars() or similar
4312 *
4313 * @return string
4314 */
4315 public function getCode() {
4316 return $this->mCode;
4317 }
4318
4319 /**
4320 * Get the code in BCP 47 format which we can use
4321 * inside of html lang="" tags.
4322 *
4323 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4324 * htmlspecialchars() or similar.
4325 *
4326 * @since 1.19
4327 * @return string
4328 */
4329 public function getHtmlCode() {
4330 if ( is_null( $this->mHtmlCode ) ) {
4331 $this->mHtmlCode = wfBCP47( $this->getCode() );
4332 }
4333 return $this->mHtmlCode;
4334 }
4335
4336 /**
4337 * @param string $code
4338 */
4339 public function setCode( $code ) {
4340 $this->mCode = $code;
4341 // Ensure we don't leave incorrect cached data lying around
4342 $this->mHtmlCode = null;
4343 $this->mParentLanguage = false;
4344 }
4345
4346 /**
4347 * Get the language code from a file name. Inverse of getFileName()
4348 * @param string $filename $prefix . $languageCode . $suffix
4349 * @param string $prefix Prefix before the language code
4350 * @param string $suffix Suffix after the language code
4351 * @return string Language code, or false if $prefix or $suffix isn't found
4352 */
4353 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4354 $m = null;
4355 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4356 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4357 if ( !count( $m ) ) {
4358 return false;
4359 }
4360 return str_replace( '_', '-', strtolower( $m[1] ) );
4361 }
4362
4363 /**
4364 * @param string $code
4365 * @return string Name of the language class
4366 */
4367 public static function classFromCode( $code ) {
4368 if ( $code == 'en' ) {
4369 return 'Language';
4370 } else {
4371 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
4372 }
4373 }
4374
4375 /**
4376 * Get the name of a file for a certain language code
4377 * @param string $prefix Prepend this to the filename
4378 * @param string $code Language code
4379 * @param string $suffix Append this to the filename
4380 * @throws MWException
4381 * @return string $prefix . $mangledCode . $suffix
4382 */
4383 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4384 if ( !self::isValidBuiltInCode( $code ) ) {
4385 throw new MWException( "Invalid language code \"$code\"" );
4386 }
4387
4388 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4389 }
4390
4391 /**
4392 * @param string $code
4393 * @return string
4394 */
4395 public static function getMessagesFileName( $code ) {
4396 global $IP;
4397 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4398 Hooks::run( 'Language::getMessagesFileName', [ $code, &$file ] );
4399 return $file;
4400 }
4401
4402 /**
4403 * @param string $code
4404 * @return string
4405 * @since 1.23
4406 */
4407 public static function getJsonMessagesFileName( $code ) {
4408 global $IP;
4409
4410 if ( !self::isValidBuiltInCode( $code ) ) {
4411 throw new MWException( "Invalid language code \"$code\"" );
4412 }
4413
4414 return "$IP/languages/i18n/$code.json";
4415 }
4416
4417 /**
4418 * Get the first fallback for a given language.
4419 *
4420 * @param string $code
4421 *
4422 * @return bool|string
4423 */
4424 public static function getFallbackFor( $code ) {
4425 $fallbacks = self::getFallbacksFor( $code );
4426 if ( $fallbacks ) {
4427 return $fallbacks[0];
4428 }
4429 return false;
4430 }
4431
4432 /**
4433 * Get the ordered list of fallback languages.
4434 *
4435 * @since 1.19
4436 * @param string $code Language code
4437 * @return array Non-empty array, ending in "en"
4438 */
4439 public static function getFallbacksFor( $code ) {
4440 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4441 return [];
4442 }
4443 // For unknown languages, fallbackSequence returns an empty array,
4444 // hardcode fallback to 'en' in that case.
4445 return self::getLocalisationCache()->getItem( $code, 'fallbackSequence' ) ?: [ 'en' ];
4446 }
4447
4448 /**
4449 * Get the ordered list of fallback languages, ending with the fallback
4450 * language chain for the site language.
4451 *
4452 * @since 1.22
4453 * @param string $code Language code
4454 * @return array Array( fallbacks, site fallbacks )
4455 */
4456 public static function getFallbacksIncludingSiteLanguage( $code ) {
4457 global $wgLanguageCode;
4458
4459 // Usually, we will only store a tiny number of fallback chains, so we
4460 // keep them in static memory.
4461 $cacheKey = "{$code}-{$wgLanguageCode}";
4462
4463 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4464 $fallbacks = self::getFallbacksFor( $code );
4465
4466 // Append the site's fallback chain, including the site language itself
4467 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4468 array_unshift( $siteFallbacks, $wgLanguageCode );
4469
4470 // Eliminate any languages already included in the chain
4471 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4472
4473 self::$fallbackLanguageCache[$cacheKey] = [ $fallbacks, $siteFallbacks ];
4474 }
4475 return self::$fallbackLanguageCache[$cacheKey];
4476 }
4477
4478 /**
4479 * Get all messages for a given language
4480 * WARNING: this may take a long time. If you just need all message *keys*
4481 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4482 *
4483 * @param string $code
4484 *
4485 * @return array
4486 */
4487 public static function getMessagesFor( $code ) {
4488 return self::getLocalisationCache()->getItem( $code, 'messages' );
4489 }
4490
4491 /**
4492 * Get a message for a given language
4493 *
4494 * @param string $key
4495 * @param string $code
4496 *
4497 * @return string
4498 */
4499 public static function getMessageFor( $key, $code ) {
4500 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4501 }
4502
4503 /**
4504 * Get all message keys for a given language. This is a faster alternative to
4505 * array_keys( Language::getMessagesFor( $code ) )
4506 *
4507 * @since 1.19
4508 * @param string $code Language code
4509 * @return array Array of message keys (strings)
4510 */
4511 public static function getMessageKeysFor( $code ) {
4512 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4513 }
4514
4515 /**
4516 * @param string $talk
4517 * @return mixed
4518 */
4519 function fixVariableInNamespace( $talk ) {
4520 if ( strpos( $talk, '$1' ) === false ) {
4521 return $talk;
4522 }
4523
4524 global $wgMetaNamespace;
4525 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4526
4527 # Allow grammar transformations
4528 # Allowing full message-style parsing would make simple requests
4529 # such as action=raw much more expensive than they need to be.
4530 # This will hopefully cover most cases.
4531 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4532 [ &$this, 'replaceGrammarInNamespace' ], $talk );
4533 return str_replace( ' ', '_', $talk );
4534 }
4535
4536 /**
4537 * @param string $m
4538 * @return string
4539 */
4540 function replaceGrammarInNamespace( $m ) {
4541 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4542 }
4543
4544 /**
4545 * @throws MWException
4546 * @return array
4547 */
4548 static function getCaseMaps() {
4549 static $wikiUpperChars, $wikiLowerChars;
4550 if ( isset( $wikiUpperChars ) ) {
4551 return [ $wikiUpperChars, $wikiLowerChars ];
4552 }
4553
4554 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4555 if ( $arr === false ) {
4556 throw new MWException(
4557 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4558 }
4559 $wikiUpperChars = $arr['wikiUpperChars'];
4560 $wikiLowerChars = $arr['wikiLowerChars'];
4561 return [ $wikiUpperChars, $wikiLowerChars ];
4562 }
4563
4564 /**
4565 * Decode an expiry (block, protection, etc) which has come from the DB
4566 *
4567 * @param string $expiry Database expiry String
4568 * @param bool|int $format True to process using language functions, or TS_ constant
4569 * to return the expiry in a given timestamp
4570 * @param string $inifinity If $format is not true, use this string for infinite expiry
4571 * @return string
4572 * @since 1.18
4573 */
4574 public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
4575 static $dbInfinity;
4576 if ( $dbInfinity === null ) {
4577 $dbInfinity = wfGetDB( DB_SLAVE )->getInfinity();
4578 }
4579
4580 if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4581 return $format === true
4582 ? $this->getMessageFromDB( 'infiniteblock' )
4583 : $infinity;
4584 } else {
4585 return $format === true
4586 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4587 : wfTimestamp( $format, $expiry );
4588 }
4589 }
4590
4591 /**
4592 * @todo Document
4593 * @param int|float $seconds
4594 * @param array $format Optional
4595 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4596 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4597 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4598 * and friends.
4599 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4600 * or 'avoidminutes'.
4601 * @return string
4602 */
4603 function formatTimePeriod( $seconds, $format = [] ) {
4604 if ( !is_array( $format ) ) {
4605 $format = [ 'avoid' => $format ]; // For backwards compatibility
4606 }
4607 if ( !isset( $format['avoid'] ) ) {
4608 $format['avoid'] = false;
4609 }
4610 if ( !isset( $format['noabbrevs'] ) ) {
4611 $format['noabbrevs'] = false;
4612 }
4613 $secondsMsg = wfMessage(
4614 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4615 $minutesMsg = wfMessage(
4616 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4617 $hoursMsg = wfMessage(
4618 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4619 $daysMsg = wfMessage(
4620 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4621
4622 if ( round( $seconds * 10 ) < 100 ) {
4623 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4624 $s = $secondsMsg->params( $s )->text();
4625 } elseif ( round( $seconds ) < 60 ) {
4626 $s = $this->formatNum( round( $seconds ) );
4627 $s = $secondsMsg->params( $s )->text();
4628 } elseif ( round( $seconds ) < 3600 ) {
4629 $minutes = floor( $seconds / 60 );
4630 $secondsPart = round( fmod( $seconds, 60 ) );
4631 if ( $secondsPart == 60 ) {
4632 $secondsPart = 0;
4633 $minutes++;
4634 }
4635 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4636 $s .= ' ';
4637 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4638 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4639 $hours = floor( $seconds / 3600 );
4640 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4641 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4642 if ( $secondsPart == 60 ) {
4643 $secondsPart = 0;
4644 $minutes++;
4645 }
4646 if ( $minutes == 60 ) {
4647 $minutes = 0;
4648 $hours++;
4649 }
4650 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4651 $s .= ' ';
4652 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4653 if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes' ] ) ) {
4654 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4655 }
4656 } else {
4657 $days = floor( $seconds / 86400 );
4658 if ( $format['avoid'] === 'avoidminutes' ) {
4659 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4660 if ( $hours == 24 ) {
4661 $hours = 0;
4662 $days++;
4663 }
4664 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4665 $s .= ' ';
4666 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4667 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4668 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4669 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4670 if ( $minutes == 60 ) {
4671 $minutes = 0;
4672 $hours++;
4673 }
4674 if ( $hours == 24 ) {
4675 $hours = 0;
4676 $days++;
4677 }
4678 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4679 $s .= ' ';
4680 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4681 $s .= ' ';
4682 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4683 } else {
4684 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4685 $s .= ' ';
4686 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4687 }
4688 }
4689 return $s;
4690 }
4691
4692 /**
4693 * Format a bitrate for output, using an appropriate
4694 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4695 * the magnitude in question.
4696 *
4697 * This use base 1000. For base 1024 use formatSize(), for another base
4698 * see formatComputingNumbers().
4699 *
4700 * @param int $bps
4701 * @return string
4702 */
4703 function formatBitrate( $bps ) {
4704 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4705 }
4706
4707 /**
4708 * @param int $size Size of the unit
4709 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4710 * @param string $messageKey Message key to be uesd
4711 * @return string
4712 */
4713 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4714 if ( $size <= 0 ) {
4715 return str_replace( '$1', $this->formatNum( $size ),
4716 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4717 );
4718 }
4719 $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' ];
4720 $index = 0;
4721
4722 $maxIndex = count( $sizes ) - 1;
4723 while ( $size >= $boundary && $index < $maxIndex ) {
4724 $index++;
4725 $size /= $boundary;
4726 }
4727
4728 // For small sizes no decimal places necessary
4729 $round = 0;
4730 if ( $index > 1 ) {
4731 // For MB and bigger two decimal places are smarter
4732 $round = 2;
4733 }
4734 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4735
4736 $size = round( $size, $round );
4737 $text = $this->getMessageFromDB( $msg );
4738 return str_replace( '$1', $this->formatNum( $size ), $text );
4739 }
4740
4741 /**
4742 * Format a size in bytes for output, using an appropriate
4743 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4744 *
4745 * This method use base 1024. For base 1000 use formatBitrate(), for
4746 * another base see formatComputingNumbers()
4747 *
4748 * @param int $size Size to format
4749 * @return string Plain text (not HTML)
4750 */
4751 function formatSize( $size ) {
4752 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4753 }
4754
4755 /**
4756 * Make a list item, used by various special pages
4757 *
4758 * @param string $page Page link
4759 * @param string $details HTML safe text between brackets
4760 * @param bool $oppositedm Add the direction mark opposite to your
4761 * language, to display text properly
4762 * @return HTML escaped string
4763 */
4764 function specialList( $page, $details, $oppositedm = true ) {
4765 if ( !$details ) {
4766 return $page;
4767 }
4768
4769 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4770 return
4771 $page .
4772 $dirmark .
4773 $this->msg( 'word-separator' )->escaped() .
4774 $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4775 }
4776
4777 /**
4778 * Generate (prev x| next x) (20|50|100...) type links for paging
4779 *
4780 * @param Title $title Title object to link
4781 * @param int $offset
4782 * @param int $limit
4783 * @param array $query Optional URL query parameter string
4784 * @param bool $atend Optional param for specified if this is the last page
4785 * @return string
4786 */
4787 public function viewPrevNext( Title $title, $offset, $limit,
4788 array $query = [], $atend = false
4789 ) {
4790 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4791
4792 # Make 'previous' link
4793 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4794 if ( $offset > 0 ) {
4795 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4796 $query, $prev, 'prevn-title', 'mw-prevlink' );
4797 } else {
4798 $plink = htmlspecialchars( $prev );
4799 }
4800
4801 # Make 'next' link
4802 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4803 if ( $atend ) {
4804 $nlink = htmlspecialchars( $next );
4805 } else {
4806 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4807 $query, $next, 'nextn-title', 'mw-nextlink' );
4808 }
4809
4810 # Make links to set number of items per page
4811 $numLinks = [];
4812 foreach ( [ 20, 50, 100, 250, 500 ] as $num ) {
4813 $numLinks[] = $this->numLink( $title, $offset, $num,
4814 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4815 }
4816
4817 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4818 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4819 }
4820
4821 /**
4822 * Helper function for viewPrevNext() that generates links
4823 *
4824 * @param Title $title Title object to link
4825 * @param int $offset
4826 * @param int $limit
4827 * @param array $query Extra query parameters
4828 * @param string $link Text to use for the link; will be escaped
4829 * @param string $tooltipMsg Name of the message to use as tooltip
4830 * @param string $class Value of the "class" attribute of the link
4831 * @return string HTML fragment
4832 */
4833 private function numLink( Title $title, $offset, $limit, array $query, $link,
4834 $tooltipMsg, $class
4835 ) {
4836 $query = [ 'limit' => $limit, 'offset' => $offset ] + $query;
4837 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4838 ->numParams( $limit )->text();
4839
4840 return Html::element( 'a', [ 'href' => $title->getLocalURL( $query ),
4841 'title' => $tooltip, 'class' => $class ], $link );
4842 }
4843
4844 /**
4845 * Get the conversion rule title, if any.
4846 *
4847 * @return string
4848 */
4849 public function getConvRuleTitle() {
4850 return $this->mConverter->getConvRuleTitle();
4851 }
4852
4853 /**
4854 * Get the compiled plural rules for the language
4855 * @since 1.20
4856 * @return array Associative array with plural form, and plural rule as key-value pairs
4857 */
4858 public function getCompiledPluralRules() {
4859 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4860 $fallbacks = Language::getFallbacksFor( $this->mCode );
4861 if ( !$pluralRules ) {
4862 foreach ( $fallbacks as $fallbackCode ) {
4863 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4864 if ( $pluralRules ) {
4865 break;
4866 }
4867 }
4868 }
4869 return $pluralRules;
4870 }
4871
4872 /**
4873 * Get the plural rules for the language
4874 * @since 1.20
4875 * @return array Associative array with plural form number and plural rule as key-value pairs
4876 */
4877 public function getPluralRules() {
4878 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4879 $fallbacks = Language::getFallbacksFor( $this->mCode );
4880 if ( !$pluralRules ) {
4881 foreach ( $fallbacks as $fallbackCode ) {
4882 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4883 if ( $pluralRules ) {
4884 break;
4885 }
4886 }
4887 }
4888 return $pluralRules;
4889 }
4890
4891 /**
4892 * Get the plural rule types for the language
4893 * @since 1.22
4894 * @return array Associative array with plural form number and plural rule type as key-value pairs
4895 */
4896 public function getPluralRuleTypes() {
4897 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4898 $fallbacks = Language::getFallbacksFor( $this->mCode );
4899 if ( !$pluralRuleTypes ) {
4900 foreach ( $fallbacks as $fallbackCode ) {
4901 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4902 if ( $pluralRuleTypes ) {
4903 break;
4904 }
4905 }
4906 }
4907 return $pluralRuleTypes;
4908 }
4909
4910 /**
4911 * Find the index number of the plural rule appropriate for the given number
4912 * @param int $number
4913 * @return int The index number of the plural rule
4914 */
4915 public function getPluralRuleIndexNumber( $number ) {
4916 $pluralRules = $this->getCompiledPluralRules();
4917 $form = Evaluator::evaluateCompiled( $number, $pluralRules );
4918 return $form;
4919 }
4920
4921 /**
4922 * Find the plural rule type appropriate for the given number
4923 * For example, if the language is set to Arabic, getPluralType(5) should
4924 * return 'few'.
4925 * @since 1.22
4926 * @param int $number
4927 * @return string The name of the plural rule type, e.g. one, two, few, many
4928 */
4929 public function getPluralRuleType( $number ) {
4930 $index = $this->getPluralRuleIndexNumber( $number );
4931 $pluralRuleTypes = $this->getPluralRuleTypes();
4932 if ( isset( $pluralRuleTypes[$index] ) ) {
4933 return $pluralRuleTypes[$index];
4934 } else {
4935 return 'other';
4936 }
4937 }
4938 }