MediaWiki  master
Language.php
Go to the documentation of this file.
1 <?php
25 use CLDRPluralRuleParser\Evaluator;
34 use Wikimedia\Assert\Assert;
35 
42 class Language {
48  public const AS_AUTONYMS = LanguageNameUtils::AUTONYMS;
49 
55  public const ALL = LanguageNameUtils::ALL;
56 
63  public const SUPPORTED = LanguageNameUtils::SUPPORTED;
64 
65  public $mCode;
66 
70  public $mMagicExtensions = [];
71 
72  private $mHtmlCode = null;
73 
78  public $dateFormatStrings = [];
79 
86 
88  protected $namespaceNames;
90 
94  private $transformData = [];
95 
98 
100  private $langNameUtils;
101 
103  private $langFallback;
104 
107 
112 
116  private $hookContainer;
117 
121  private $hookRunner;
122 
128  public const MESSAGES_FALLBACKS = LanguageFallback::MESSAGES;
129 
135  public const STRICT_FALLBACKS = LanguageFallback::STRICT;
136 
140  public const WEEKDAY_MESSAGES = [
141  'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
142  'friday', 'saturday'
143  ];
144 
149 
154  'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
155  ];
156 
161 
165  public const MONTH_MESSAGES = [
166  'january', 'february', 'march', 'april', 'may_long', 'june',
167  'july', 'august', 'september', 'october', 'november',
168  'december'
169  ];
170 
175 
179  public const MONTH_GENITIVE_MESSAGES = [
180  'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
181  'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
182  'december-gen'
183  ];
184 
189 
193  public const MONTH_ABBREVIATED_MESSAGES = [
194  'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
195  'sep', 'oct', 'nov', 'dec'
196  ];
197 
202 
207  'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
208  'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
209  'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
210  'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
211  ];
212 
217 
222  'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
223  'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
224  'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
225  'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
226  'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
227  ];
228 
233 
238  'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
239  'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
240  'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
241  'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
242  'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
243  ];
244 
249 
254  'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
255  'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
256  'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
257  'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
258  ];
259 
264 
268  protected const DURATION_INTERVALS = [
269  'millennia' => 31556952000,
270  'centuries' => 3155695200,
271  'decades' => 315569520,
272  'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
273  'weeks' => 604800,
274  'days' => 86400,
275  'hours' => 3600,
276  'minutes' => 60,
277  'seconds' => 1,
278  ];
279 
286 
290  private const LRE = "\u{202A}"; // U+202A LEFT-TO-RIGHT EMBEDDING
291  private const RLE = "\u{202B}"; // U+202B RIGHT-TO-LEFT EMBEDDING
292  private const PDF = "\u{202C}"; // U+202C POP DIRECTIONAL FORMATTING
293 
305  // @codeCoverageIgnoreStart
306  // phpcs:ignore Generic.Files.LineLength
307  private static $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';
308  // @codeCoverageIgnoreEnd
309 
317  public static function factory( $code ) {
318  return MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $code );
319  }
320 
330  public static function isSupportedLanguage( $code ) {
331  return MediaWikiServices::getInstance()->getLanguageNameUtils()
332  ->isSupportedLanguage( $code );
333  }
334 
350  public static function isWellFormedLanguageTag( $code, $lenient = false ) {
351  $alpha = '[a-z]';
352  $digit = '[0-9]';
353  $alphanum = '[a-z0-9]';
354  $x = 'x'; # private use singleton
355  $singleton = '[a-wy-z]'; # other singleton
356  $s = $lenient ? '[-_]' : '-';
357 
358  $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
359  $script = "$alpha{4}"; # ISO 15924
360  $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
361  $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
362  $extension = "$singleton(?:$s$alphanum{2,8})+";
363  $privateUse = "$x(?:$s$alphanum{1,8})+";
364 
365  # Define certain grandfathered codes, since otherwise the regex is pretty useless.
366  # Since these are limited, this is safe even later changes to the registry --
367  # the only oddity is that it might change the type of the tag, and thus
368  # the results from the capturing groups.
369  # https://www.iana.org/assignments/language-subtag-registry
370 
371  $grandfathered = "en{$s}GB{$s}oed"
372  . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
373  . "|no{$s}(?:bok|nyn)"
374  . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
375  . "|zh{$s}min{$s}nan";
376 
377  $variantList = "$variant(?:$s$variant)*";
378  $extensionList = "$extension(?:$s$extension)*";
379 
380  $langtag = "(?:($language)"
381  . "(?:$s$script)?"
382  . "(?:$s$region)?"
383  . "(?:$s$variantList)?"
384  . "(?:$s$extensionList)?"
385  . "(?:$s$privateUse)?)";
386 
387  # The final breakdown, with capturing groups for each of these components
388  # The variants, extensions, grandfathered, and private-use may have interior '-'
389 
390  $root = "^(?:$langtag|$privateUse|$grandfathered)$";
391 
392  return (bool)preg_match( "/$root/", strtolower( $code ) );
393  }
394 
407  public static function isValidCode( $code ) {
408  return MediaWikiServices::getInstance()->getLanguageNameUtils()->isValidCode( $code );
409  }
410 
422  public static function isValidBuiltInCode( $code ) {
423  return MediaWikiServices::getInstance()->getLanguageNameUtils()
424  ->isValidBuiltInCode( $code );
425  }
426 
437  public static function isKnownLanguageTag( $tag ) {
438  return MediaWikiServices::getInstance()->getLanguageNameUtils()
439  ->isKnownLanguageTag( $tag );
440  }
441 
446  public static function getLocalisationCache() {
447  return MediaWikiServices::getInstance()->getLocalisationCache();
448  }
449 
460  public function __construct(
461  $code = null,
467  ) {
468  if ( !func_num_args() ) {
469  // Old calling convention, deprecated
470  if ( static::class === 'Language' ) {
471  $this->mCode = 'en';
472  } else {
473  $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
474  }
475 
476  $services = MediaWikiServices::getInstance();
477  $this->localisationCache = $services->getLocalisationCache();
478  $this->langNameUtils = $services->getLanguageNameUtils();
479  $this->langFallback = $services->getLanguageFallback();
480  $this->converterFactory = $services->getLanguageConverterFactory();
481  $this->hookContainer = $services->getHookContainer();
482  $this->hookRunner = new HookRunner( $this->hookContainer );
483  return;
484  }
485 
486  Assert::parameter( $code !== null, '$code',
487  'Parameters cannot be null unless all are omitted' );
488  Assert::parameter( $localisationCache !== null, '$localisationCache',
489  'Parameters cannot be null unless all are omitted' );
490  Assert::parameter( $langNameUtils !== null, '$langNameUtils',
491  'Parameters cannot be null unless all are omitted' );
492  Assert::parameter( $langFallback !== null, '$langFallback',
493  'Parameters cannot be null unless all are omitted' );
494  Assert::parameter( $converterFactory !== null, '$converterFactory',
495  'Parameters cannot be null unless all are omitted' );
496  Assert::parameter( $hookContainer !== null, '$hookContainer',
497  'Parameters cannot be null unless all are omitted' );
498 
499  $this->mCode = $code;
500  $this->localisationCache = $localisationCache;
501  $this->langNameUtils = $langNameUtils;
502  $this->langFallback = $langFallback;
503  $this->converterFactory = $converterFactory;
504  $this->hookContainer = $hookContainer;
505  $this->hookRunner = new HookRunner( $hookContainer );
506  }
507 
512  public function __destruct() {
513  foreach ( $this as $name => $value ) {
514  unset( $this->$name );
515  }
516  }
517 
522  public function getFallbackLanguages() {
523  return $this->langFallback->getAll( $this->mCode );
524  }
525 
530  public function getBookstoreList() {
531  return $this->localisationCache->getItem( $this->mCode, 'bookstoreList' );
532  }
533 
540  public function getNamespaces() {
541  if ( $this->namespaceNames === null ) {
543 
544  $validNamespaces = MediaWikiServices::getInstance()->getNamespaceInfo()->
545  getCanonicalNamespaces();
546 
547  $this->namespaceNames = $wgExtraNamespaces +
548  $this->localisationCache->getItem( $this->mCode, 'namespaceNames' );
549  $this->namespaceNames += $validNamespaces;
550 
551  $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
552  if ( $wgMetaNamespaceTalk ) {
553  $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
554  } else {
555  $talk = $this->namespaceNames[NS_PROJECT_TALK];
556  $this->namespaceNames[NS_PROJECT_TALK] =
557  $this->fixVariableInNamespace( $talk );
558  }
559 
560  # Sometimes a language will be localised but not actually exist on this wiki.
561  foreach ( $this->namespaceNames as $key => $text ) {
562  if ( !isset( $validNamespaces[$key] ) ) {
563  unset( $this->namespaceNames[$key] );
564  }
565  }
566 
567  # The above mixing may leave namespaces out of canonical order.
568  # Re-order by namespace ID number...
569  ksort( $this->namespaceNames );
570 
571  $this->getHookRunner()->onLanguageGetNamespaces( $this->namespaceNames );
572  }
573 
574  return $this->namespaceNames;
575  }
576 
581  public function setNamespaces( array $namespaces ) {
582  $this->namespaceNames = $namespaces;
583  $this->mNamespaceIds = null;
584  }
585 
589  public function resetNamespaces() {
590  $this->namespaceNames = null;
591  $this->mNamespaceIds = null;
592  $this->namespaceAliases = null;
593  }
594 
601  public function getFormattedNamespaces() {
602  $ns = $this->getNamespaces();
603  foreach ( $ns as $k => $v ) {
604  $ns[$k] = strtr( $v, '_', ' ' );
605  }
606  return $ns;
607  }
608 
620  public function getNsText( $index ) {
621  $ns = $this->getNamespaces();
622  return $ns[$index] ?? false;
623  }
624 
638  public function getFormattedNsText( $index ) {
639  $ns = $this->getNsText( $index );
640  return strtr( $ns, '_', ' ' );
641  }
642 
651  public function getGenderNsText( $index, $gender ) {
653 
655  (array)$this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
656 
657  return $ns[$index][$gender] ?? $this->getNsText( $index );
658  }
659 
666  public function needsGenderDistinction() {
668  if ( count( $wgExtraGenderNamespaces ) > 0 ) {
669  // $wgExtraGenderNamespaces overrides everything
670  return true;
671  } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
672  // @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
673  // $wgExtraNamespaces overrides any gender aliases specified in i18n files
674  return false;
675  } else {
676  // Check what is in i18n files
677  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
678  return count( $aliases ) > 0;
679  }
680  }
681 
690  public function getLocalNsIndex( $text ) {
691  $lctext = $this->lc( $text );
692  $ids = $this->getNamespaceIds();
693  return $ids[$lctext] ?? false;
694  }
695 
700  public function getNamespaceAliases() {
701  if ( $this->namespaceAliases === null ) {
702  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceAliases' );
703  if ( !$aliases ) {
704  $aliases = [];
705  } else {
706  foreach ( $aliases as $name => $index ) {
707  if ( $index === NS_PROJECT_TALK ) {
708  unset( $aliases[$name] );
709  $name = $this->fixVariableInNamespace( $name );
710  $aliases[$name] = $index;
711  }
712  }
713  }
714 
716  $genders = $wgExtraGenderNamespaces + (array)$this->localisationCache
717  ->getItem( $this->mCode, 'namespaceGenderAliases' );
718  foreach ( $genders as $index => $forms ) {
719  foreach ( $forms as $alias ) {
720  $aliases[$alias] = $index;
721  }
722  }
723 
724  # Also add converted namespace names as aliases, to avoid confusion.
725  $convertedNames = [];
726  foreach ( $this->getConverter()->getVariants() as $variant ) {
727  if ( $variant === $this->mCode ) {
728  continue;
729  }
730  foreach ( $this->getNamespaces() as $ns => $_ ) {
731  $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
732  }
733  }
734 
735  $this->namespaceAliases = $aliases + $convertedNames;
736 
737  // In the case of conflicts between $wgNamespaceAliases and other sources
738  // of aliasing, $wgNamespaceAliases wins.
739  global $wgNamespaceAliases;
740  $this->namespaceAliases = $wgNamespaceAliases + $this->namespaceAliases;
741 
742  # Filter out aliases to namespaces that don't exist, e.g. from extensions
743  # that aren't loaded here but are included in the l10n cache.
744  # (array_intersect preserves keys from its first argument)
745  $this->namespaceAliases = array_intersect(
746  $this->namespaceAliases,
747  array_keys( $this->getNamespaces() )
748  );
749  }
750 
752  }
753 
757  public function getNamespaceIds() {
758  if ( $this->mNamespaceIds === null ) {
759  # Put namespace names and aliases into a hashtable.
760  # If this is too slow, then we should arrange it so that it is done
761  # before caching. The catch is that at pre-cache time, the above
762  # class-specific fixup hasn't been done.
763  $this->mNamespaceIds = [];
764  foreach ( $this->getNamespaces() as $index => $name ) {
765  $this->mNamespaceIds[$this->lc( $name )] = $index;
766  }
767  foreach ( $this->getNamespaceAliases() as $name => $index ) {
768  $this->mNamespaceIds[$this->lc( $name )] = $index;
769  }
770  }
771  return $this->mNamespaceIds;
772  }
773 
781  public function getNsIndex( $text ) {
782  $lctext = $this->lc( $text );
783  $ns = MediaWikiServices::getInstance()->getNamespaceInfo()->
784  getCanonicalIndex( $lctext );
785  if ( $ns !== null ) {
786  return $ns;
787  }
788  $ids = $this->getNamespaceIds();
789  return $ids[$lctext] ?? false;
790  }
791 
799  public function getVariantname( $code, $usemsg = true ) {
800  $msg = "variantname-$code";
801  if ( $usemsg && wfMessage( $msg )->exists() ) {
802  return $this->getMessageFromDB( $msg );
803  }
804  $name = $this->langNameUtils->getLanguageName( $code );
805  if ( $name ) {
806  return $name; # if it's defined as a language name, show that
807  } else {
808  # otherwise, output the language code
809  return $code;
810  }
811  }
812 
816  public function getDatePreferences() {
817  return $this->localisationCache->getItem( $this->mCode, 'datePreferences' );
818  }
819 
823  public function getDateFormats() {
824  return $this->localisationCache->getItem( $this->mCode, 'dateFormats' );
825  }
826 
830  public function getDefaultDateFormat() {
831  $df = $this->localisationCache->getItem( $this->mCode, 'defaultDateFormat' );
832  if ( $df === 'dmy or mdy' ) {
833  global $wgAmericanDates;
834  return $wgAmericanDates ? 'mdy' : 'dmy';
835  } else {
836  return $df;
837  }
838  }
839 
843  public function getDatePreferenceMigrationMap() {
844  return $this->localisationCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
845  }
846 
862  public static function fetchLanguageNames(
863  $inLanguage = LanguageNameUtils::AUTONYMS,
864  $include = 'mw'
865  ) {
866  return MediaWikiServices::getInstance()->getLanguageNameUtils()
867  ->getLanguageNames( $inLanguage, $include );
868  }
869 
879  public static function fetchLanguageName(
880  $code,
881  $inLanguage = LanguageNameUtils::AUTONYMS,
882  $include = LanguageNameUtils::ALL
883  ) {
884  return MediaWikiServices::getInstance()->getLanguageNameUtils()
885  ->getLanguageName( $code, $inLanguage, $include );
886  }
887 
894  public function getMessageFromDB( $msg ) {
895  return $this->msg( $msg )->text();
896  }
897 
904  protected function msg( $msg ) {
905  return wfMessage( $msg )->inLanguage( $this );
906  }
907 
912  public function getMonthName( $key ) {
913  return $this->getMessageFromDB( self::MONTH_MESSAGES[$key - 1] );
914  }
915 
919  public function getMonthNamesArray() {
920  $monthNames = [ '' ];
921  for ( $i = 1; $i < 13; $i++ ) {
922  $monthNames[] = $this->getMonthName( $i );
923  }
924  return $monthNames;
925  }
926 
931  public function getMonthNameGen( $key ) {
932  return $this->getMessageFromDB( self::MONTH_GENITIVE_MESSAGES[$key - 1] );
933  }
934 
939  public function getMonthAbbreviation( $key ) {
940  return $this->getMessageFromDB( self::MONTH_ABBREVIATED_MESSAGES[$key - 1] );
941  }
942 
946  public function getMonthAbbreviationsArray() {
947  $monthNames = [ '' ];
948  for ( $i = 1; $i < 13; $i++ ) {
949  $monthNames[] = $this->getMonthAbbreviation( $i );
950  }
951  return $monthNames;
952  }
953 
958  public function getWeekdayName( $key ) {
959  return $this->getMessageFromDB( self::WEEKDAY_MESSAGES[$key - 1] );
960  }
961 
966  public function getWeekdayAbbreviation( $key ) {
967  return $this->getMessageFromDB( self::WEEKDAY_ABBREVIATED_MESSAGES[$key - 1] );
968  }
969 
974  private function getIranianCalendarMonthName( $key ) {
975  return $this->getMessageFromDB( self::IRANIAN_CALENDAR_MONTHS_MESSAGES[$key - 1] );
976  }
977 
982  private function getHebrewCalendarMonthName( $key ) {
983  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTHS_MESSAGES[$key - 1] );
984  }
985 
990  private function getHebrewCalendarMonthNameGen( $key ) {
991  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES[$key - 1] );
992  }
993 
998  private function getHijriCalendarMonthName( $key ) {
999  return $this->getMessageFromDB( self::HIJRI_CALENDAR_MONTH_MESSAGES[$key - 1] );
1000  }
1001 
1010  private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1011  if ( !$dateTimeObj ) {
1012  $dateTimeObj = DateTime::createFromFormat(
1013  'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1014  );
1015  }
1016  return $dateTimeObj->format( $code );
1017  }
1018 
1089  public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
1090  $s = '';
1091  $raw = false;
1092  $roman = false;
1093  $hebrewNum = false;
1094  $dateTimeObj = false;
1095  $rawToggle = false;
1096  $iranian = false;
1097  $hebrew = false;
1098  $hijri = false;
1099  $thai = false;
1100  $minguo = false;
1101  $tenno = false;
1102 
1103  $usedSecond = false;
1104  $usedMinute = false;
1105  $usedHour = false;
1106  $usedAMPM = false;
1107  $usedDay = false;
1108  $usedWeek = false;
1109  $usedMonth = false;
1110  $usedYear = false;
1111  $usedISOYear = false;
1112  $usedIsLeapYear = false;
1113 
1114  $usedHebrewMonth = false;
1115  $usedIranianMonth = false;
1116  $usedHijriMonth = false;
1117  $usedHebrewYear = false;
1118  $usedIranianYear = false;
1119  $usedHijriYear = false;
1120  $usedTennoYear = false;
1121 
1122  if ( strlen( $ts ) !== 14 ) {
1123  throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1124  }
1125 
1126  if ( !ctype_digit( $ts ) ) {
1127  throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1128  }
1129 
1130  $formatLength = strlen( $format );
1131  for ( $p = 0; $p < $formatLength; $p++ ) {
1132  $num = false;
1133  $code = $format[$p];
1134  if ( $code == 'x' && $p < $formatLength - 1 ) {
1135  $code .= $format[++$p];
1136  }
1137 
1138  if ( ( $code === 'xi'
1139  || $code === 'xj'
1140  || $code === 'xk'
1141  || $code === 'xm'
1142  || $code === 'xo'
1143  || $code === 'xt' )
1144  && $p < $formatLength - 1 ) {
1145  $code .= $format[++$p];
1146  }
1147 
1148  switch ( $code ) {
1149  case 'xx':
1150  $s .= 'x';
1151  break;
1152  case 'xn':
1153  $raw = true;
1154  break;
1155  case 'xN':
1156  $rawToggle = !$rawToggle;
1157  break;
1158  case 'xr':
1159  $roman = true;
1160  break;
1161  case 'xh':
1162  $hebrewNum = true;
1163  break;
1164  case 'xg':
1165  $usedMonth = true;
1166  $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1167  break;
1168  case 'xjx':
1169  $usedHebrewMonth = true;
1170  if ( !$hebrew ) {
1171  $hebrew = self::tsToHebrew( $ts );
1172  }
1173  $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1174  break;
1175  case 'd':
1176  $usedDay = true;
1177  $num = substr( $ts, 6, 2 );
1178  break;
1179  case 'D':
1180  $usedDay = true;
1181  $s .= $this->getWeekdayAbbreviation(
1182  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1183  );
1184  break;
1185  case 'j':
1186  $usedDay = true;
1187  $num = intval( substr( $ts, 6, 2 ) );
1188  break;
1189  case 'xij':
1190  $usedDay = true;
1191  if ( !$iranian ) {
1192  $iranian = self::tsToIranian( $ts );
1193  }
1194  $num = $iranian[2];
1195  break;
1196  case 'xmj':
1197  $usedDay = true;
1198  if ( !$hijri ) {
1199  $hijri = self::tsToHijri( $ts );
1200  }
1201  $num = $hijri[2];
1202  break;
1203  case 'xjj':
1204  $usedDay = true;
1205  if ( !$hebrew ) {
1206  $hebrew = self::tsToHebrew( $ts );
1207  }
1208  $num = $hebrew[2];
1209  break;
1210  case 'l':
1211  $usedDay = true;
1212  $s .= $this->getWeekdayName(
1213  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1214  );
1215  break;
1216  case 'F':
1217  $usedMonth = true;
1218  $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1219  break;
1220  case 'xiF':
1221  $usedIranianMonth = true;
1222  if ( !$iranian ) {
1223  $iranian = self::tsToIranian( $ts );
1224  }
1225  $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1226  break;
1227  case 'xmF':
1228  $usedHijriMonth = true;
1229  if ( !$hijri ) {
1230  $hijri = self::tsToHijri( $ts );
1231  }
1232  $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1233  break;
1234  case 'xjF':
1235  $usedHebrewMonth = true;
1236  if ( !$hebrew ) {
1237  $hebrew = self::tsToHebrew( $ts );
1238  }
1239  $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1240  break;
1241  case 'm':
1242  $usedMonth = true;
1243  $num = substr( $ts, 4, 2 );
1244  break;
1245  case 'M':
1246  $usedMonth = true;
1247  $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1248  break;
1249  case 'n':
1250  $usedMonth = true;
1251  $num = intval( substr( $ts, 4, 2 ) );
1252  break;
1253  case 'xin':
1254  $usedIranianMonth = true;
1255  if ( !$iranian ) {
1256  $iranian = self::tsToIranian( $ts );
1257  }
1258  $num = $iranian[1];
1259  break;
1260  case 'xmn':
1261  $usedHijriMonth = true;
1262  if ( !$hijri ) {
1263  $hijri = self::tsToHijri( $ts );
1264  }
1265  $num = $hijri[1];
1266  break;
1267  case 'xjn':
1268  $usedHebrewMonth = true;
1269  if ( !$hebrew ) {
1270  $hebrew = self::tsToHebrew( $ts );
1271  }
1272  $num = $hebrew[1];
1273  break;
1274  case 'xjt':
1275  $usedHebrewMonth = true;
1276  if ( !$hebrew ) {
1277  $hebrew = self::tsToHebrew( $ts );
1278  }
1279  $num = $hebrew[3];
1280  break;
1281  case 'Y':
1282  $usedYear = true;
1283  $num = substr( $ts, 0, 4 );
1284  break;
1285  case 'xiY':
1286  $usedIranianYear = true;
1287  if ( !$iranian ) {
1288  $iranian = self::tsToIranian( $ts );
1289  }
1290  $num = $iranian[0];
1291  break;
1292  case 'xmY':
1293  $usedHijriYear = true;
1294  if ( !$hijri ) {
1295  $hijri = self::tsToHijri( $ts );
1296  }
1297  $num = $hijri[0];
1298  break;
1299  case 'xjY':
1300  $usedHebrewYear = true;
1301  if ( !$hebrew ) {
1302  $hebrew = self::tsToHebrew( $ts );
1303  }
1304  $num = $hebrew[0];
1305  break;
1306  case 'xkY':
1307  $usedYear = true;
1308  if ( !$thai ) {
1309  $thai = self::tsToYear( $ts, 'thai' );
1310  }
1311  $num = $thai[0];
1312  break;
1313  case 'xoY':
1314  $usedYear = true;
1315  if ( !$minguo ) {
1316  $minguo = self::tsToYear( $ts, 'minguo' );
1317  }
1318  $num = $minguo[0];
1319  break;
1320  case 'xtY':
1321  $usedTennoYear = true;
1322  if ( !$tenno ) {
1323  $tenno = self::tsToYear( $ts, 'tenno' );
1324  }
1325  $num = $tenno[0];
1326  break;
1327  case 'y':
1328  $usedYear = true;
1329  $num = substr( $ts, 2, 2 );
1330  break;
1331  case 'xiy':
1332  $usedIranianYear = true;
1333  if ( !$iranian ) {
1334  $iranian = self::tsToIranian( $ts );
1335  }
1336  $num = substr( $iranian[0], -2 );
1337  break;
1338  case 'xit':
1339  $usedIranianYear = true;
1340  if ( !$iranian ) {
1341  $iranian = self::tsToIranian( $ts );
1342  }
1343  $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
1344  break;
1345  case 'xiz':
1346  $usedIranianYear = true;
1347  if ( !$iranian ) {
1348  $iranian = self::tsToIranian( $ts );
1349  }
1350  $num = $iranian[3];
1351  break;
1352  case 'a':
1353  $usedAMPM = true;
1354  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1355  break;
1356  case 'A':
1357  $usedAMPM = true;
1358  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1359  break;
1360  case 'g':
1361  $usedHour = true;
1362  $h = substr( $ts, 8, 2 );
1363  $num = $h % 12 ?: 12;
1364  break;
1365  case 'G':
1366  $usedHour = true;
1367  $num = intval( substr( $ts, 8, 2 ) );
1368  break;
1369  case 'h':
1370  $usedHour = true;
1371  $h = substr( $ts, 8, 2 );
1372  $num = sprintf( '%02d', $h % 12 ?: 12 );
1373  break;
1374  case 'H':
1375  $usedHour = true;
1376  $num = substr( $ts, 8, 2 );
1377  break;
1378  case 'i':
1379  $usedMinute = true;
1380  $num = substr( $ts, 10, 2 );
1381  break;
1382  case 's':
1383  $usedSecond = true;
1384  $num = substr( $ts, 12, 2 );
1385  break;
1386  case 'c':
1387  case 'r':
1388  $usedSecond = true;
1389  // fall through
1390  case 'e':
1391  case 'O':
1392  case 'P':
1393  case 'T':
1394  $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1395  break;
1396  case 'w':
1397  case 'N':
1398  case 'z':
1399  $usedDay = true;
1400  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1401  break;
1402  case 'W':
1403  $usedWeek = true;
1404  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1405  break;
1406  case 't':
1407  $usedMonth = true;
1408  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1409  break;
1410  case 'L':
1411  $usedIsLeapYear = true;
1412  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1413  break;
1414  case 'o':
1415  $usedISOYear = true;
1416  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1417  break;
1418  case 'U':
1419  $usedSecond = true;
1420  // fall through
1421  case 'I':
1422  case 'Z':
1423  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1424  break;
1425  case '\\':
1426  # Backslash escaping
1427  if ( $p < $formatLength - 1 ) {
1428  $s .= $format[++$p];
1429  } else {
1430  $s .= '\\';
1431  }
1432  break;
1433  case '"':
1434  # Quoted literal
1435  if ( $p < $formatLength - 1 ) {
1436  $endQuote = strpos( $format, '"', $p + 1 );
1437  if ( $endQuote === false ) {
1438  # No terminating quote, assume literal "
1439  $s .= '"';
1440  } else {
1441  $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1442  $p = $endQuote;
1443  }
1444  } else {
1445  # Quote at end of string, assume literal "
1446  $s .= '"';
1447  }
1448  break;
1449  default:
1450  $s .= $format[$p];
1451  }
1452  if ( $num !== false ) {
1453  if ( $rawToggle || $raw ) {
1454  $s .= $num;
1455  $raw = false;
1456  } elseif ( $roman ) {
1457  $s .= self::romanNumeral( $num );
1458  $roman = false;
1459  } elseif ( $hebrewNum ) {
1460  $s .= self::hebrewNumeral( $num );
1461  $hebrewNum = false;
1462  } elseif ( preg_match( '/^[\d.]+$/', $num ) ) {
1463  $s .= $this->formatNumNoSeparators( $num );
1464  } else {
1465  $s .= $num;
1466  }
1467  }
1468  }
1469 
1470  if ( $ttl === 'unused' ) {
1471  // No need to calculate the TTL, the caller wont use it anyway.
1472  } elseif ( $usedSecond ) {
1473  $ttl = 1;
1474  } elseif ( $usedMinute ) {
1475  $ttl = 60 - substr( $ts, 12, 2 );
1476  } elseif ( $usedHour ) {
1477  $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1478  } elseif ( $usedAMPM ) {
1479  $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1480  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1481  } elseif (
1482  $usedDay ||
1483  $usedHebrewMonth ||
1484  $usedIranianMonth ||
1485  $usedHijriMonth ||
1486  $usedHebrewYear ||
1487  $usedIranianYear ||
1488  $usedHijriYear ||
1489  $usedTennoYear
1490  ) {
1491  // @todo Someone who understands the non-Gregorian calendars
1492  // should write proper logic for them so that they don't need purged every day.
1493  $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1494  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1495  } else {
1496  $possibleTtls = [];
1497  $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1498  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1499  if ( $usedWeek ) {
1500  $possibleTtls[] =
1501  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1502  $timeRemainingInDay;
1503  } elseif ( $usedISOYear ) {
1504  // December 28th falls on the last ISO week of the year, every year.
1505  // The last ISO week of a year can be 52 or 53.
1506  $lastWeekOfISOYear = DateTime::createFromFormat(
1507  'Ymd',
1508  substr( $ts, 0, 4 ) . '1228',
1509  $zone ?: new DateTimeZone( 'UTC' )
1510  )->format( 'W' );
1511  $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1512  $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1513  $timeRemainingInWeek =
1514  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1515  + $timeRemainingInDay;
1516  $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1517  }
1518 
1519  if ( $usedMonth ) {
1520  $possibleTtls[] =
1521  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1522  substr( $ts, 6, 2 ) ) * 86400
1523  + $timeRemainingInDay;
1524  } elseif ( $usedYear ) {
1525  $possibleTtls[] =
1526  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1527  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1528  + $timeRemainingInDay;
1529  } elseif ( $usedIsLeapYear ) {
1530  $year = substr( $ts, 0, 4 );
1531  $timeRemainingInYear =
1532  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1533  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1534  + $timeRemainingInDay;
1535  $mod = $year % 4;
1536  if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1537  // this isn't a leap year. see when the next one starts
1538  $nextCandidate = $year - $mod + 4;
1539  if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1540  $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1541  $timeRemainingInYear;
1542  } else {
1543  $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1544  $timeRemainingInYear;
1545  }
1546  } else {
1547  // this is a leap year, so the next year isn't
1548  $possibleTtls[] = $timeRemainingInYear;
1549  }
1550  }
1551 
1552  if ( $possibleTtls ) {
1553  $ttl = min( $possibleTtls );
1554  }
1555  }
1556 
1557  return $s;
1558  }
1559 
1560  private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1561  private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1562 
1575  private static function tsToIranian( $ts ) {
1576  $gy = substr( $ts, 0, 4 ) - 1600;
1577  $gm = substr( $ts, 4, 2 ) - 1;
1578  $gd = substr( $ts, 6, 2 ) - 1;
1579 
1580  # Days passed from the beginning (including leap years)
1581  $gDayNo = 365 * $gy
1582  + floor( ( $gy + 3 ) / 4 )
1583  - floor( ( $gy + 99 ) / 100 )
1584  + floor( ( $gy + 399 ) / 400 );
1585 
1586  // Add days of the past months of this year
1587  for ( $i = 0; $i < $gm; $i++ ) {
1588  $gDayNo += self::$GREG_DAYS[$i];
1589  }
1590 
1591  // Leap years
1592  if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 ) || $gy % 400 == 0 ) ) {
1593  $gDayNo++;
1594  }
1595 
1596  // Days passed in current month
1597  $gDayNo += (int)$gd;
1598 
1599  $jDayNo = $gDayNo - 79;
1600 
1601  $jNp = floor( $jDayNo / 12053 );
1602  $jDayNo %= 12053;
1603 
1604  $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1605  $jDayNo %= 1461;
1606 
1607  if ( $jDayNo >= 366 ) {
1608  $jy += floor( ( $jDayNo - 1 ) / 365 );
1609  $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1610  }
1611 
1612  $jz = $jDayNo;
1613 
1614  for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1615  $jDayNo -= self::$IRANIAN_DAYS[$i];
1616  }
1617 
1618  $jm = $i + 1;
1619  $jd = $jDayNo + 1;
1620 
1621  return [ $jy, $jm, $jd, $jz ];
1622  }
1623 
1635  private static function tsToHijri( $ts ) {
1636  $year = substr( $ts, 0, 4 );
1637  $month = substr( $ts, 4, 2 );
1638  $day = substr( $ts, 6, 2 );
1639 
1640  $zyr = $year;
1641  $zd = $day;
1642  $zm = $month;
1643  $zy = $zyr;
1644 
1645  if (
1646  ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1647  ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1648  ) {
1649  $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1650  (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1651  (int)( ( 3 * (int)( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) / 4 ) +
1652  $zd - 32075;
1653  } else {
1654  $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1655  (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1656  }
1657 
1658  $zl = $zjd - 1948440 + 10632;
1659  $zn = (int)( ( $zl - 1 ) / 10631 );
1660  $zl = $zl - 10631 * $zn + 354;
1661  $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1662  ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1663  $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1664  ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1665  $zm = (int)( ( 24 * $zl ) / 709 );
1666  $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1667  $zy = 30 * $zn + $zj - 30;
1668 
1669  return [ $zy, $zm, $zd ];
1670  }
1671 
1687  private static function tsToHebrew( $ts ) {
1688  # Parse date
1689  $year = substr( $ts, 0, 4 );
1690  $month = substr( $ts, 4, 2 );
1691  $day = substr( $ts, 6, 2 );
1692 
1693  # Calculate Hebrew year
1694  $hebrewYear = $year + 3760;
1695 
1696  # Month number when September = 1, August = 12
1697  $month += 4;
1698  if ( $month > 12 ) {
1699  # Next year
1700  $month -= 12;
1701  $year++;
1702  $hebrewYear++;
1703  }
1704 
1705  # Calculate day of year from 1 September
1706  $dayOfYear = $day;
1707  for ( $i = 1; $i < $month; $i++ ) {
1708  if ( $i == 6 ) {
1709  # February
1710  $dayOfYear += 28;
1711  # Check if the year is leap
1712  if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1713  $dayOfYear++;
1714  }
1715  } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1716  $dayOfYear += 30;
1717  } else {
1718  $dayOfYear += 31;
1719  }
1720  }
1721 
1722  # Calculate the start of the Hebrew year
1723  $start = self::hebrewYearStart( $hebrewYear );
1724 
1725  # Calculate next year's start
1726  if ( $dayOfYear <= $start ) {
1727  # Day is before the start of the year - it is the previous year
1728  # Next year's start
1729  $nextStart = $start;
1730  # Previous year
1731  $year--;
1732  $hebrewYear--;
1733  # Add days since previous year's 1 September
1734  $dayOfYear += 365;
1735  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1736  # Leap year
1737  $dayOfYear++;
1738  }
1739  # Start of the new (previous) year
1740  $start = self::hebrewYearStart( $hebrewYear );
1741  } else {
1742  # Next year's start
1743  $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1744  }
1745 
1746  # Calculate Hebrew day of year
1747  $hebrewDayOfYear = $dayOfYear - $start;
1748 
1749  # Difference between year's days
1750  $diff = $nextStart - $start;
1751  # Add 12 (or 13 for leap years) days to ignore the difference between
1752  # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1753  # difference is only about the year type
1754  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1755  $diff += 13;
1756  } else {
1757  $diff += 12;
1758  }
1759 
1760  # Check the year pattern, and is leap year
1761  # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1762  # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1763  # and non-leap years
1764  $yearPattern = $diff % 30;
1765  # Check if leap year
1766  $isLeap = $diff >= 30;
1767 
1768  # Calculate day in the month from number of day in the Hebrew year
1769  # Don't check Adar - if the day is not in Adar, we will stop before;
1770  # if it is in Adar, we will use it to check if it is Adar I or Adar II
1771  $hebrewDay = $hebrewDayOfYear;
1772  $hebrewMonth = 1;
1773  $days = 0;
1774  while ( $hebrewMonth <= 12 ) {
1775  # Calculate days in this month
1776  if ( $isLeap && $hebrewMonth == 6 ) {
1777  # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1778  $days = 30;
1779  if ( $hebrewDay <= $days ) {
1780  # Day in Adar I
1781  $hebrewMonth = 13;
1782  } else {
1783  # Subtract the days of Adar I
1784  $hebrewDay -= $days;
1785  # Try Adar II
1786  $days = 29;
1787  if ( $hebrewDay <= $days ) {
1788  # Day in Adar II
1789  $hebrewMonth = 14;
1790  }
1791  }
1792  } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1793  # Cheshvan in a complete year (otherwise as the rule below)
1794  $days = 30;
1795  } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1796  # Kislev in an incomplete year (otherwise as the rule below)
1797  $days = 29;
1798  } else {
1799  # Odd months have 30 days, even have 29
1800  $days = 30 - ( $hebrewMonth - 1 ) % 2;
1801  }
1802  if ( $hebrewDay <= $days ) {
1803  # In the current month
1804  break;
1805  } else {
1806  # Subtract the days of the current month
1807  $hebrewDay -= $days;
1808  # Try in the next month
1809  $hebrewMonth++;
1810  }
1811  }
1812 
1813  return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1814  }
1815 
1825  private static function hebrewYearStart( $year ) {
1826  $a = ( 12 * ( $year - 1 ) + 17 ) % 19;
1827  $b = ( $year - 1 ) % 4;
1828  $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1829  if ( $m < 0 ) {
1830  $m--;
1831  }
1832  $Mar = intval( $m );
1833  if ( $m < 0 ) {
1834  $m++;
1835  }
1836  $m -= $Mar;
1837 
1838  $c = ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7;
1839  if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1840  $Mar++;
1841  } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1842  $Mar += 2;
1843  } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1844  $Mar++;
1845  }
1846 
1847  $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1848  return $Mar;
1849  }
1850 
1863  private static function tsToYear( $ts, $cName ) {
1864  $gy = substr( $ts, 0, 4 );
1865  $gm = substr( $ts, 4, 2 );
1866  $gd = substr( $ts, 6, 2 );
1867 
1868  if ( !strcmp( $cName, 'thai' ) ) {
1869  # Thai solar dates
1870  # Add 543 years to the Gregorian calendar
1871  # Months and days are identical
1872  $gy_offset = $gy + 543;
1873  # fix for dates between 1912 and 1941
1874  # https://en.wikipedia.org/?oldid=836596673#New_year
1875  if ( $gy >= 1912 && $gy <= 1940 ) {
1876  if ( $gm <= 3 ) {
1877  $gy_offset--;
1878  }
1879  $gm = ( $gm - 3 ) % 12;
1880  }
1881  } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1882  # Minguo dates
1883  # Deduct 1911 years from the Gregorian calendar
1884  # Months and days are identical
1885  $gy_offset = $gy - 1911;
1886  } elseif ( !strcmp( $cName, 'tenno' ) ) {
1887  # Nengō dates up to Meiji period
1888  # Deduct years from the Gregorian calendar
1889  # depending on the nengo periods
1890  # Months and days are identical
1891  if ( ( $gy < 1912 )
1892  || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1893  || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1894  ) {
1895  # Meiji period
1896  $gy_gannen = $gy - 1868 + 1;
1897  $gy_offset = $gy_gannen;
1898  if ( $gy_gannen == 1 ) {
1899  $gy_offset = '元';
1900  }
1901  $gy_offset = '明治' . $gy_offset;
1902  } elseif (
1903  ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1904  ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1905  ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1906  ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1907  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1908  ) {
1909  # Taishō period
1910  $gy_gannen = $gy - 1912 + 1;
1911  $gy_offset = $gy_gannen;
1912  if ( $gy_gannen == 1 ) {
1913  $gy_offset = '元';
1914  }
1915  $gy_offset = '大正' . $gy_offset;
1916  } elseif (
1917  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1918  ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1919  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1920  ) {
1921  # Shōwa period
1922  $gy_gannen = $gy - 1926 + 1;
1923  $gy_offset = $gy_gannen;
1924  if ( $gy_gannen == 1 ) {
1925  $gy_offset = '元';
1926  }
1927  $gy_offset = '昭和' . $gy_offset;
1928  } elseif (
1929  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd >= 8 ) ) ||
1930  ( ( $gy > 1989 ) && ( $gy < 2019 ) ) ||
1931  ( ( $gy == 2019 ) && ( $gm < 5 ) )
1932  ) {
1933  # Heisei period
1934  $gy_gannen = $gy - 1989 + 1;
1935  $gy_offset = $gy_gannen;
1936  if ( $gy_gannen == 1 ) {
1937  $gy_offset = '元';
1938  }
1939  $gy_offset = '平成' . $gy_offset;
1940  } else {
1941  # Reiwa period
1942  $gy_gannen = $gy - 2019 + 1;
1943  $gy_offset = $gy_gannen;
1944  if ( $gy_gannen == 1 ) {
1945  $gy_offset = '元';
1946  }
1947  $gy_offset = '令和' . $gy_offset;
1948  }
1949  } else {
1950  $gy_offset = $gy;
1951  }
1952 
1953  return [ $gy_offset, $gm, $gd ];
1954  }
1955 
1969  private static function strongDirFromContent( $text = '' ) {
1970  if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
1971  return null;
1972  }
1973  if ( $matches[1] === '' ) {
1974  return 'rtl';
1975  }
1976  return 'ltr';
1977  }
1978 
1986  public static function romanNumeral( $num ) {
1987  static $table = [
1988  [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
1989  [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
1990  [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
1991  [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1992  'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
1993  ];
1994 
1995  $num = intval( $num );
1996  if ( $num > 10000 || $num <= 0 ) {
1997  return $num;
1998  }
1999 
2000  $s = '';
2001  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2002  if ( $num >= $pow10 ) {
2003  $s .= $table[$i][(int)floor( $num / $pow10 )];
2004  }
2005  $num %= $pow10;
2006  }
2007  return $s;
2008  }
2009 
2017  public static function hebrewNumeral( $num ) {
2018  static $table = [
2019  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
2020  [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
2021  [ '',
2022  [ 'ק' ],
2023  [ 'ר' ],
2024  [ 'ש' ],
2025  [ 'ת' ],
2026  [ 'ת', 'ק' ],
2027  [ 'ת', 'ר' ],
2028  [ 'ת', 'ש' ],
2029  [ 'ת', 'ת' ],
2030  [ 'ת', 'ת', 'ק' ],
2031  [ 'ת', 'ת', 'ר' ],
2032  ],
2033  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
2034  ];
2035 
2036  $num = intval( $num );
2037  if ( $num > 9999 || $num <= 0 ) {
2038  return $num;
2039  }
2040 
2041  // Round thousands have special notations
2042  if ( $num === 1000 ) {
2043  return "א' אלף";
2044  } elseif ( $num % 1000 === 0 ) {
2045  return $table[0][$num / 1000] . "' אלפים";
2046  }
2047 
2048  $letters = [];
2049 
2050  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2051  if ( $num >= $pow10 ) {
2052  if ( $num === 15 || $num === 16 ) {
2053  $letters[] = $table[0][9];
2054  $letters[] = $table[0][$num - 9];
2055  $num = 0;
2056  } else {
2057  $letters = array_merge(
2058  $letters,
2059  (array)$table[$i][intval( $num / $pow10 )]
2060  );
2061 
2062  if ( $pow10 === 1000 ) {
2063  $letters[] = "'";
2064  }
2065  }
2066  }
2067 
2068  $num %= $pow10;
2069  }
2070 
2071  $preTransformLength = count( $letters );
2072  if ( $preTransformLength === 1 ) {
2073  // Add geresh (single quote) to one-letter numbers
2074  $letters[] = "'";
2075  } else {
2076  $lastIndex = $preTransformLength - 1;
2077  $letters[$lastIndex] = str_replace(
2078  [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2079  [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2080  $letters[$lastIndex]
2081  );
2082 
2083  // Add gershayim (double quote) to multiple-letter numbers,
2084  // but exclude numbers with only one letter after the thousands
2085  // (1001-1009, 1020, 1030, 2001-2009, etc.)
2086  if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2087  $letters[] = "'";
2088  } else {
2089  array_splice( $letters, -1, 0, '"' );
2090  }
2091  }
2092 
2093  return implode( $letters );
2094  }
2095 
2104  public function userAdjust( $ts, $tz = false ) {
2105  global $wgLocalTZoffset;
2106 
2107  if ( $tz === false ) {
2108  $optionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
2109  $tz = $optionsLookup->getOption(
2110  RequestContext::getMain()->getUser(),
2111  'timecorrection'
2112  );
2113  }
2114 
2115  $data = explode( '|', $tz, 3 );
2116 
2117  if ( $data[0] == 'ZoneInfo' ) {
2118  try {
2119  $userTZ = new DateTimeZone( $data[2] );
2120  $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
2121  $date->setTimezone( $userTZ );
2122  return $date->format( 'YmdHis' );
2123  } catch ( Exception $e ) {
2124  // Unrecognized timezone, default to 'Offset' with the stored offset.
2125  $data[0] = 'Offset';
2126  }
2127  }
2128 
2129  if ( $data[0] == 'System' || $tz == '' ) {
2130  # Global offset in minutes.
2131  $minDiff = $wgLocalTZoffset;
2132  } elseif ( $data[0] == 'Offset' ) {
2133  $minDiff = intval( $data[1] );
2134  } else {
2135  $data = explode( ':', $tz );
2136  if ( count( $data ) == 2 ) {
2137  $data[0] = intval( $data[0] );
2138  $data[1] = intval( $data[1] );
2139  $minDiff = abs( $data[0] ) * 60 + $data[1];
2140  if ( $data[0] < 0 ) {
2141  $minDiff = -$minDiff;
2142  }
2143  } else {
2144  $minDiff = intval( $data[0] ) * 60;
2145  }
2146  }
2147 
2148  # No difference ? Return time unchanged
2149  if ( $minDiff == 0 ) {
2150  return $ts;
2151  }
2152 
2153  Wikimedia\suppressWarnings(); // E_STRICT system time bitching
2154  # Generate an adjusted date; take advantage of the fact that mktime
2155  # will normalize out-of-range values so we don't have to split $minDiff
2156  # into hours and minutes.
2157  $t = mktime( (
2158  (int)substr( $ts, 8, 2 ) ), # Hours
2159  (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2160  (int)substr( $ts, 12, 2 ), # Seconds
2161  (int)substr( $ts, 4, 2 ), # Month
2162  (int)substr( $ts, 6, 2 ), # Day
2163  (int)substr( $ts, 0, 4 ) ); # Year
2164 
2165  $date = date( 'YmdHis', $t );
2166  Wikimedia\restoreWarnings();
2167 
2168  return $date;
2169  }
2170 
2186  public function dateFormat( $usePrefs = true ) {
2187  if ( is_bool( $usePrefs ) ) {
2188  if ( $usePrefs ) {
2189  $datePreference = RequestContext::getMain()
2190  ->getUser()
2191  ->getDatePreference();
2192  } else {
2193  $userOptionsLookup = MediawikiServices::getInstance()->getUserOptionsLookup();
2194  $datePreference = (string)$userOptionsLookup->getDefaultOption( 'date' );
2195  }
2196  } else {
2197  $datePreference = (string)$usePrefs;
2198  }
2199 
2200  // return int
2201  if ( $datePreference == '' ) {
2202  return 'default';
2203  }
2204 
2205  return $datePreference;
2206  }
2207 
2218  public function getDateFormatString( $type, $pref ) {
2219  $wasDefault = false;
2220  if ( $pref == 'default' ) {
2221  $wasDefault = true;
2222  $pref = $this->getDefaultDateFormat();
2223  }
2224 
2225  if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2226  $df = $this->localisationCache
2227  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2228 
2229  if ( $type === 'pretty' && $df === null ) {
2230  $df = $this->getDateFormatString( 'date', $pref );
2231  }
2232 
2233  if ( !$wasDefault && $df === null ) {
2234  $pref = $this->getDefaultDateFormat();
2235  $df = $this->localisationCache
2236  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2237  }
2238 
2239  $this->dateFormatStrings[$type][$pref] = $df;
2240  }
2241  return $this->dateFormatStrings[$type][$pref];
2242  }
2243 
2254  public function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2255  $ts = wfTimestamp( TS_MW, $ts );
2256  if ( $adj ) {
2257  $ts = $this->userAdjust( $ts, $timecorrection );
2258  }
2259  $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2260  return $this->sprintfDate( $df, $ts );
2261  }
2262 
2273  public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2274  $ts = wfTimestamp( TS_MW, $ts );
2275  if ( $adj ) {
2276  $ts = $this->userAdjust( $ts, $timecorrection );
2277  }
2278  $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2279  return $this->sprintfDate( $df, $ts );
2280  }
2281 
2293  public function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2294  $ts = wfTimestamp( TS_MW, $ts );
2295  if ( $adj ) {
2296  $ts = $this->userAdjust( $ts, $timecorrection );
2297  }
2298  $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2299  return $this->sprintfDate( $df, $ts );
2300  }
2301 
2312  public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2313  $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2314 
2315  $segments = [];
2316 
2317  foreach ( $intervals as $intervalName => $intervalValue ) {
2318  // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2319  // duration-years, duration-decades, duration-centuries, duration-millennia
2320  $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2321  $segments[] = $message->inLanguage( $this )->escaped();
2322  }
2323 
2324  return $this->listToText( $segments );
2325  }
2326 
2338  public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2339  if ( empty( $chosenIntervals ) ) {
2340  $chosenIntervals = [
2341  'millennia',
2342  'centuries',
2343  'decades',
2344  'years',
2345  'days',
2346  'hours',
2347  'minutes',
2348  'seconds'
2349  ];
2350  }
2351 
2352  $intervals = array_intersect_key( self::DURATION_INTERVALS,
2353  array_fill_keys( $chosenIntervals, true ) );
2354  $sortedNames = array_keys( $intervals );
2355  $smallestInterval = array_pop( $sortedNames );
2356 
2357  $segments = [];
2358 
2359  foreach ( $intervals as $name => $length ) {
2360  $value = floor( $seconds / $length );
2361 
2362  if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2363  $seconds -= $value * $length;
2364  $segments[$name] = $value;
2365  }
2366  }
2367 
2368  return $segments;
2369  }
2370 
2390  private function internalUserTimeAndDate( $type, $ts, UserIdentity $user, array $options ) {
2391  $ts = wfTimestamp( TS_MW, $ts );
2392  $options += [ 'timecorrection' => true, 'format' => true ];
2393  if ( $options['timecorrection'] !== false ) {
2394  if ( $options['timecorrection'] === true ) {
2395  $offset = MediaWikiServices::getInstance()
2396  ->getUserOptionsLookup()
2397  ->getOption( $user, 'timecorrection' );
2398  } else {
2399  $offset = $options['timecorrection'];
2400  }
2401  $ts = $this->userAdjust( $ts, $offset );
2402  }
2403  if ( $options['format'] === true ) {
2404  $format = MediaWikiServices::getInstance()
2405  ->getUserFactory()
2406  ->newFromUserIdentity( $user )
2407  ->getDatePreference();
2408  } else {
2409  $format = $options['format'];
2410  }
2411  $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2412  return $this->sprintfDate( $df, $ts );
2413  }
2414 
2434  public function userDate( $ts, UserIdentity $user, array $options = [] ) {
2435  return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2436  }
2437 
2457  public function userTime( $ts, UserIdentity $user, array $options = [] ) {
2458  return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2459  }
2460 
2480  public function userTimeAndDate( $ts, UserIdentity $user, array $options = [] ) {
2481  return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2482  }
2483 
2499  public function getHumanTimestamp(
2500  MWTimestamp $time, MWTimestamp $relativeTo = null, UserIdentity $user = null
2501  ) {
2502  if ( $relativeTo === null ) {
2503  $relativeTo = new MWTimestamp();
2504  }
2505  if ( $user === null ) {
2506  $user = RequestContext::getMain()->getUser();
2507  } else {
2508  // For compatibility with the hook signature and self::getHumanTimestampInternal
2509  $user = MediaWikiServices::getInstance()
2510  ->getUserFactory()
2511  ->newFromUserIdentity( $user );
2512  }
2513 
2514  // Adjust for the user's timezone.
2515  $offsetThis = $time->offsetForUser( $user );
2516  $offsetRel = $relativeTo->offsetForUser( $user );
2517 
2518  $ts = '';
2519  if ( $this->getHookRunner()->onGetHumanTimestamp( $ts, $time, $relativeTo, $user, $this ) ) {
2520  $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2521  }
2522 
2523  // Reset the timezone on the objects.
2524  $time->timestamp->sub( $offsetThis );
2525  $relativeTo->timestamp->sub( $offsetRel );
2526 
2527  return $ts;
2528  }
2529 
2541  private function getHumanTimestampInternal(
2542  MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2543  ) {
2544  $diff = $ts->diff( $relativeTo );
2545  $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2546  (int)$relativeTo->timestamp->format( 'w' ) );
2547  $days = $diff->days ?: (int)$diffDay;
2548  if ( $diff->invert || $days > 5
2549  && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2550  ) {
2551  // Timestamps are in different years: use full timestamp
2552  // Also do full timestamp for future dates
2556  $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2557  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2558  } elseif ( $days > 5 ) {
2559  // Timestamps are in same year, but more than 5 days ago: show day and month only.
2560  $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2561  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2562  } elseif ( $days > 1 ) {
2563  // Timestamp within the past week: show the day of the week and time
2564  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2565  $weekday = self::WEEKDAY_MESSAGES[$ts->timestamp->format( 'w' )];
2566  // Messages:
2567  // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2568  $ts = wfMessage( "$weekday-at" )
2569  ->inLanguage( $this )
2570  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2571  ->text();
2572  } elseif ( $days == 1 ) {
2573  // Timestamp was yesterday: say 'yesterday' and the time.
2574  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2575  $ts = wfMessage( 'yesterday-at' )
2576  ->inLanguage( $this )
2577  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2578  ->text();
2579  } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2580  // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2581  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2582  $ts = wfMessage( 'today-at' )
2583  ->inLanguage( $this )
2584  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2585  ->text();
2586 
2587  // From here on in, the timestamp was soon enough ago so that we can simply say
2588  // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2589  } elseif ( $diff->h == 1 ) {
2590  // Less than 90 minutes, but more than an hour ago.
2591  $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2592  } elseif ( $diff->i >= 1 ) {
2593  // A few minutes ago.
2594  $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2595  } elseif ( $diff->s >= 30 ) {
2596  // Less than a minute, but more than 30 sec ago.
2597  $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2598  } else {
2599  // Less than 30 seconds ago.
2600  $ts = wfMessage( 'just-now' )->text();
2601  }
2602 
2603  return $ts;
2604  }
2605 
2613  public function getGroupName( $group ) {
2614  $msg = $this->msg( "group-$group" );
2615  return $msg->isBlank() ? $group : $msg->text();
2616  }
2617 
2622  public function getMessage( $key ) {
2623  return $this->localisationCache->getSubitem( $this->mCode, 'messages', $key );
2624  }
2625 
2629  public function getAllMessages() {
2630  return $this->localisationCache->getItem( $this->mCode, 'messages' );
2631  }
2632 
2639  public function iconv( $in, $out, $string ) {
2640  # Even with //IGNORE iconv can whine about illegal characters in
2641  # *input* string. We just ignore those too.
2642  # REF: https://bugs.php.net/bug.php?id=37166
2643  # REF: https://phabricator.wikimedia.org/T18885
2644  Wikimedia\suppressWarnings();
2645  $text = iconv( $in, $out . '//IGNORE', $string );
2646  Wikimedia\restoreWarnings();
2647  return $text;
2648  }
2649 
2654  public function ucfirst( $str ) {
2655  $octetCode = ord( $str );
2656  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2657  if ( $octetCode < 96 ) {
2658  // Assume this is an uppercase/uncased ASCII character
2659  return (string)$str;
2660  } elseif ( $octetCode < 128 ) {
2661  // Assume this is a lowercase/uncased ASCII character
2662  return ucfirst( $str );
2663  }
2664 
2665  $first = mb_substr( $str, 0, 1 );
2666  return ( strlen( $first ) !== 1 )
2667  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2668  ? $this->mbUpperChar( $first ) . mb_substr( $str, 1 )
2669  // Assume this is a non-multibyte character and LC_CASE is appropriate
2670  : ucfirst( $str );
2671  }
2672 
2678  public function uc( $str, $first = false ) {
2679  if ( $first ) {
2680  return $this->ucfirst( $str );
2681  } else {
2682  return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2683  }
2684  }
2685 
2699  protected function mbUpperChar( $char ) {
2701 
2702  return $wgOverrideUcfirstCharacters[$char] ?? mb_strtoupper( $char );
2703  }
2704 
2709  public function lcfirst( $str ) {
2710  $octetCode = ord( $str );
2711  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2712  if ( $octetCode < 96 ) {
2713  // Assume this is an uppercase/uncased ASCII character
2714  return lcfirst( $str );
2715  } elseif ( $octetCode < 128 ) {
2716  // Assume this is a lowercase/uncased ASCII character
2717  return (string)$str;
2718  }
2719 
2720  return $this->isMultibyte( $str )
2721  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2722  ? mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 )
2723  // Assume this is a non-multibyte character and LC_CASE is appropriate
2724  : lcfirst( $str );
2725  }
2726 
2732  public function lc( $str, $first = false ) {
2733  if ( $first ) {
2734  return $this->lcfirst( $str );
2735  } else {
2736  return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2737  }
2738  }
2739 
2744  private function isMultibyte( $str ) {
2745  return strlen( $str ) !== mb_strlen( $str );
2746  }
2747 
2752  public function ucwords( $str ) {
2753  if ( $this->isMultibyte( $str ) ) {
2754  $str = $this->lc( $str );
2755 
2756  // regexp to find first letter in each word (i.e. after each space)
2757  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2758 
2759  // function to use to capitalize a single char
2760  return preg_replace_callback(
2761  $replaceRegexp,
2762  static function ( $matches ) {
2763  return mb_strtoupper( $matches[0] );
2764  },
2765  $str
2766  );
2767  } else {
2768  return ucwords( strtolower( $str ) );
2769  }
2770  }
2771 
2778  public function ucwordbreaks( $str ) {
2779  if ( $this->isMultibyte( $str ) ) {
2780  $str = $this->lc( $str );
2781 
2782  // since \b doesn't work for UTF-8, we explicitely define word break chars
2783  $breaks = "[ \-\‍(\‍)\}\{\.,\?!]";
2784 
2785  // find first letter after word break
2786  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2787  "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2788 
2789  return preg_replace_callback(
2790  $replaceRegexp,
2791  static function ( $matches ) {
2792  return mb_strtoupper( $matches[0] );
2793  },
2794  $str
2795  );
2796  } else {
2797  return preg_replace_callback(
2798  '/\b([\w\x80-\xff]+)\b/',
2799  function ( $matches ) {
2800  return $this->ucfirst( $matches[1] );
2801  },
2802  $str
2803  );
2804  }
2805  }
2806 
2822  public function caseFold( $s ) {
2823  return $this->uc( $s );
2824  }
2825 
2831  public function checkTitleEncoding( $s ) {
2832  if ( is_array( $s ) ) {
2833  throw new MWException( 'Given array to checkTitleEncoding.' );
2834  }
2835  if ( StringUtils::isUtf8( $s ) ) {
2836  return $s;
2837  }
2838 
2839  return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2840  }
2841 
2845  public function fallback8bitEncoding() {
2846  return $this->localisationCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2847  }
2848 
2857  public function hasWordBreaks() {
2858  return true;
2859  }
2860 
2868  public function segmentByWord( $string ) {
2869  return $string;
2870  }
2871 
2879  public function normalizeForSearch( $string ) {
2880  return self::convertDoubleWidth( $string );
2881  }
2882 
2891  protected static function convertDoubleWidth( $string ) {
2892  static $full = null;
2893  static $half = null;
2894 
2895  if ( $full === null ) {
2896  $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2897  $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2898  $full = str_split( $fullWidth, 3 );
2899  $half = str_split( $halfWidth );
2900  }
2901 
2902  $string = str_replace( $full, $half, $string );
2903  return $string;
2904  }
2905 
2911  protected static function insertSpace( $string, $pattern ) {
2912  $string = preg_replace( $pattern, " $1 ", $string );
2913  $string = preg_replace( '/ +/', ' ', $string );
2914  return $string;
2915  }
2916 
2921  public function convertForSearchResult( $termsArray ) {
2922  # some languages, e.g. Chinese, need to do a conversion
2923  # in order for search results to be displayed correctly
2924  return $termsArray;
2925  }
2926 
2933  public function firstChar( $s ) {
2934  $firstChar = mb_substr( $s, 0, 1 );
2935 
2936  if ( $firstChar === '' || strlen( $firstChar ) != 3 ) {
2937  return $firstChar;
2938  }
2939 
2940  // Break down Hangul syllables to grab the first jamo
2941  $code = mb_ord( $firstChar );
2942  if ( $code < 0xac00 || $code >= 0xd7a4 ) {
2943  return $firstChar;
2944  } elseif ( $code < 0xb098 ) {
2945  return "\u{3131}";
2946  } elseif ( $code < 0xb2e4 ) {
2947  return "\u{3134}";
2948  } elseif ( $code < 0xb77c ) {
2949  return "\u{3137}";
2950  } elseif ( $code < 0xb9c8 ) {
2951  return "\u{3139}";
2952  } elseif ( $code < 0xbc14 ) {
2953  return "\u{3141}";
2954  } elseif ( $code < 0xc0ac ) {
2955  return "\u{3142}";
2956  } elseif ( $code < 0xc544 ) {
2957  return "\u{3145}";
2958  } elseif ( $code < 0xc790 ) {
2959  return "\u{3147}";
2960  } elseif ( $code < 0xcc28 ) {
2961  return "\u{3148}";
2962  } elseif ( $code < 0xce74 ) {
2963  return "\u{314A}";
2964  } elseif ( $code < 0xd0c0 ) {
2965  return "\u{314B}";
2966  } elseif ( $code < 0xd30c ) {
2967  return "\u{314C}";
2968  } elseif ( $code < 0xd558 ) {
2969  return "\u{314D}";
2970  } else {
2971  return "\u{314E}";
2972  }
2973  }
2974 
2984  public function normalize( $s ) {
2985  global $wgAllUnicodeFixes;
2986 
2987  $s = UtfNormal\Validator::cleanUp( $s );
2988  // Optimization: This is disabled by default to avoid negative performance impact.
2989  if ( $wgAllUnicodeFixes ) {
2990  $s = $this->transformUsingPairFile( MediaWiki\Languages\Data\NormalizeAr::class, $s );
2991  $s = $this->transformUsingPairFile( MediaWiki\Languages\Data\NormalizeMl::class, $s );
2992  }
2993 
2994  return $s;
2995  }
2996 
3008  protected function transformUsingPairFile( string $dataClass, string $input ): string {
3009  if ( !isset( $this->transformData[$dataClass] ) ) {
3010  $this->transformData[$dataClass] = new ReplacementArray( $dataClass::PAIRS );
3011  }
3012 
3013  return $this->transformData[$dataClass]->replace( $input );
3014  }
3015 
3021  public function isRTL() {
3022  return $this->localisationCache->getItem( $this->mCode, 'rtl' );
3023  }
3024 
3029  public function getDir() {
3030  return $this->isRTL() ? 'rtl' : 'ltr';
3031  }
3032 
3041  public function alignStart() {
3042  return $this->isRTL() ? 'right' : 'left';
3043  }
3044 
3053  public function alignEnd() {
3054  return $this->isRTL() ? 'left' : 'right';
3055  }
3056 
3068  public function getDirMarkEntity( $opposite = false ) {
3069  if ( $opposite ) {
3070  return $this->isRTL() ? '&lrm;' : '&rlm;';
3071  }
3072  return $this->isRTL() ? '&rlm;' : '&lrm;';
3073  }
3074 
3085  public function getDirMark( $opposite = false ) {
3086  $lrm = "\u{200E}"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3087  $rlm = "\u{200F}"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3088  if ( $opposite ) {
3089  return $this->isRTL() ? $lrm : $rlm;
3090  }
3091  return $this->isRTL() ? $rlm : $lrm;
3092  }
3093 
3101  public function getArrow( $direction = 'forwards' ) {
3102  switch ( $direction ) {
3103  case 'forwards':
3104  return $this->isRTL() ? '←' : '→';
3105  case 'backwards':
3106  return $this->isRTL() ? '→' : '←';
3107  case 'left':
3108  return '←';
3109  case 'right':
3110  return '→';
3111  case 'up':
3112  return '↑';
3113  case 'down':
3114  return '↓';
3115  }
3116  }
3117 
3123  public function linkPrefixExtension() {
3124  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixExtension' );
3125  }
3126 
3131  public function getMagicWords() {
3132  return $this->localisationCache->getItem( $this->mCode, 'magicWords' );
3133  }
3134 
3140  public function getMagic( $mw ) {
3141  $rawEntry = $this->mMagicExtensions[$mw->mId] ??
3142  $this->localisationCache->getSubitem( $this->mCode, 'magicWords', $mw->mId );
3143 
3144  if ( !is_array( $rawEntry ) ) {
3145  wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3146  } else {
3147  $mw->mCaseSensitive = $rawEntry[0];
3148  $mw->mSynonyms = array_slice( $rawEntry, 1 );
3149  }
3150  }
3151 
3157  public function getSpecialPageAliases() {
3158  // Cache aliases because it may be slow to load them
3159  if ( $this->mExtendedSpecialPageAliases === null ) {
3160  // Initialise array
3161  $this->mExtendedSpecialPageAliases =
3162  $this->localisationCache->getItem( $this->mCode, 'specialPageAliases' );
3163  }
3164 
3165  return $this->mExtendedSpecialPageAliases;
3166  }
3167 
3174  public function emphasize( $text ) {
3175  return "<em>$text</em>";
3176  }
3177 
3200  public function formatNum( $number, $noSeparators = null ) {
3201  if ( $noSeparators !== null ) {
3202  wfDeprecated( __METHOD__ . ' with $noSeparators parameter', '1.36' );
3203  } else {
3204  // The legacy default value.
3205  $noSeparators = false;
3206  }
3207  return $this->formatNumInternal( (string)$number, false, $noSeparators );
3208  }
3209 
3219  private function formatNumInternal(
3220  string $number, bool $noTranslate, bool $noSeparators
3221  ): string {
3222  global $wgTranslateNumerals;
3223 
3224  if ( $number === '' ) {
3225  return $number;
3226  }
3227  if ( $number === (string)NAN ) {
3228  return $this->msg( 'formatnum-nan' )->text();
3229  }
3230  if ( $number === (string)INF ) {
3231  return "∞";
3232  }
3233  if ( $number === (string)-INF ) {
3234  return "\u{2212}∞";
3235  }
3236  if ( !is_numeric( $number ) ) {
3237  # T267587: downgrade this to level:warn while we chase down the long
3238  # trail of callers.
3239  # wfDeprecated( 'Language::formatNum with a non-numeric string', '1.36' );
3240  LoggerFactory::getInstance( 'formatnum' )->warning(
3241  'Language::formatNum with non-numeric string',
3242  [ 'number' => $number ]
3243  );
3244  $validNumberRe = '(-(?=[\d\.]))?(\d+|(?=\.\d))(\.\d*)?([Ee][-+]?\d+)?';
3245  // For backwards-compat, apply formatNum piecewise on the valid
3246  // numbers in the string. Don't split on NAN/INF in this legacy
3247  // case as they are likely to be found embedded inside non-numeric
3248  // text.
3249  return preg_replace_callback( "/{$validNumberRe}/", function ( $m ) use ( $noTranslate, $noSeparators ) {
3250  return $this->formatNumInternal( $m[0], $noTranslate, $noSeparators );
3251  }, $number );
3252  }
3253 
3254  if ( !$noSeparators ) {
3255  $separatorTransformTable = $this->separatorTransformTable();
3256  $digitGroupingPattern = $this->digitGroupingPattern();
3257  $code = $this->getCode();
3258  if ( !( $wgTranslateNumerals && $this->langNameUtils->isValidCode( $code ) ) ) {
3259  $code = 'C'; // POSIX system default locale
3260  }
3261 
3262  if ( $digitGroupingPattern ) {
3263  $fmt = new NumberFormatter(
3264  $code, NumberFormatter::PATTERN_DECIMAL, $digitGroupingPattern
3265  );
3266  } else {
3268  $fmt = new NumberFormatter( $code, NumberFormatter::DECIMAL );
3269  }
3270 
3271  // minimumGroupingDigits can be used to suppress groupings below a certain value.
3272  // This is used for languages such as Polish, where one would only write the grouping
3273  // separator for values above 9999 - numbers with more than 4 digits.
3274  // NumberFormatter is yet to support minimumGroupingDigits, ICU has it as experimental feature.
3275  // The attribute value is used by adding it to the grouping separator value. If
3276  // the input number has fewer integer digits, the grouping separator is suppressed.
3277  $minimumGroupingDigits = $this->minimumGroupingDigits() ?? 0;
3278  // Minimum length of a number to do digit grouping on.
3279  // http://unicode.org/reports/tr35/tr35-numbers.html#Examples_of_minimumGroupingDigits
3280  $minimumLength = $minimumGroupingDigits + $fmt->getAttribute( NumberFormatter::GROUPING_SIZE );
3281  if ( $minimumGroupingDigits && !preg_match( '/^\-?\d{' . $minimumLength . '}/', $number ) ) {
3282  // Even if number does not need commafy, do decimal
3283  // separator transformation. For example 1234.56 becomes
3284  // 1234,56 in pl with $minimumGroupingDigits = 2
3285  if ( !$noTranslate ) {
3286  $number = strtr( $number, $separatorTransformTable ?: [] );
3287  }
3288  } elseif ( $number === '-0' ) {
3289  // Special case to ensure we don't lose the minus sign by
3290  // converting to an int.
3291  if ( !$noTranslate ) {
3292  $number = strtr( $number, $separatorTransformTable ?: [] );
3293  }
3294  } else {
3295  // NumberFormatter supports separator transformation,
3296  // but it does not know all languages MW
3297  // supports. Example: arq. Also, languages like pl has
3298  // customisation. So manually set it.
3299  if ( $noTranslate ) {
3300  $fmt->setSymbol(
3301  NumberFormatter::DECIMAL_SEPARATOR_SYMBOL,
3302  '.'
3303  );
3304  $fmt->setSymbol(
3305  NumberFormatter::GROUPING_SEPARATOR_SYMBOL,
3306  ','
3307  );
3308  } elseif ( $separatorTransformTable ) {
3309  $fmt->setSymbol(
3310  NumberFormatter::DECIMAL_SEPARATOR_SYMBOL,
3311  $separatorTransformTable[ '.' ] ?? '.'
3312  );
3313  $fmt->setSymbol(
3314  NumberFormatter::GROUPING_SEPARATOR_SYMBOL,
3315  $separatorTransformTable[ ',' ] ?? ','
3316  );
3317  }
3318 
3319  // Maintain # of digits before and after the decimal point
3320  // (and presence of decimal point)
3321  if ( preg_match( '/^-?(\d*)(\.(\d*))?$/', $number, $m ) ) {
3322  $fmt->setAttribute( NumberFormatter::MIN_INTEGER_DIGITS, strlen( $m[1] ) );
3323  if ( isset( $m[2] ) ) {
3324  $fmt->setAttribute( NumberFormatter::DECIMAL_ALWAYS_SHOWN, true );
3325  }
3326  $fmt->setAttribute( NumberFormatter::FRACTION_DIGITS, strlen( $m[3] ?? '' ) );
3327  }
3328  $number = $fmt->format( $number );
3329  }
3330  }
3331 
3332  if ( !$noTranslate ) {
3333  if ( $wgTranslateNumerals ) {
3334  // This is often unnecessary: PHP's NumberFormatter will often
3335  // do the digit transform itself (T267614)
3336  $s = $this->digitTransformTable();
3337  if ( $s ) {
3338  $number = strtr( $number, $s );
3339  }
3340  }
3341  # T10327: Make our formatted numbers prettier by using a
3342  # proper Unicode 'minus' character.
3343  $number = strtr( $number, [ '-' => "\u{2212}" ] );
3344  }
3345 
3346  // Remove any LRM or RLM characters generated from NumberFormatter,
3347  // since directionality is handled outside of this context.
3348  // Similarly remove \u61C, the "Arabic Letter mark" (unicode 6.3.0)
3349  // https://en.wikipedia.org/wiki/Arabic_letter_mark
3350  // which is added starting PHP 7.3+
3351  $number = strtr( $number, [
3352  "\u{200E}" => '', // LRM
3353  "\u{200F}" => '', // RLM
3354  "\u{061C}" => '', // ALM
3355  ] );
3356 
3357  return $number;
3358  }
3359 
3368  public function formatNumNoSeparators( $number ) {
3369  return $this->formatNumInternal( (string)$number, false, true );
3370  }
3371 
3376  public function parseFormattedNumber( $number ) {
3377  if ( $number === $this->msg( 'formatnum-nan' )->text() ) {
3378  return (string)NAN;
3379  }
3380  if ( $number === "∞" ) {
3381  return (string)INF;
3382  }
3383  // Accept either ASCII hyphen-minus or the unicode minus emitted by
3384  // ::formatNum()
3385  $number = strtr( $number, [ "\u{2212}" => '-' ] );
3386  if ( $number === "-∞" ) {
3387  return (string)-INF;
3388  }
3389  $s = $this->digitTransformTable();
3390  if ( $s ) {
3391  // eliminate empty array values such as ''. (T66347)
3392  $s = array_filter( $s );
3393  $number = strtr( $number, array_flip( $s ) );
3394  }
3395 
3396  $s = $this->separatorTransformTable();
3397  if ( $s ) {
3398  // eliminate empty array values such as ''. (T66347)
3399  $s = array_filter( $s );
3400  $number = strtr( $number, array_flip( $s ) );
3401  }
3402 
3403  $number = strtr( $number, [ ',' => '' ] );
3404  return $number;
3405  }
3406 
3419  public function commafy( $number ) {
3420  wfDeprecated( __METHOD__, '1.36' );
3421  // Validate the input argument.
3422  if ( $number === null || $number === '' ) {
3423  return '';
3424  }
3425  return $this->formatNumInternal( $number, true, false );
3426  }
3427 
3431  public function digitGroupingPattern() {
3432  return $this->localisationCache->getItem( $this->mCode, 'digitGroupingPattern' );
3433  }
3434 
3438  public function digitTransformTable() {
3439  return $this->localisationCache->getItem( $this->mCode, 'digitTransformTable' );
3440  }
3441 
3445  public function separatorTransformTable() {
3446  return $this->localisationCache->getItem( $this->mCode, 'separatorTransformTable' );
3447  }
3448 
3452  public function minimumGroupingDigits() {
3453  return $this->localisationCache->getItem( $this->mCode, 'minimumGroupingDigits' );
3454  }
3455 
3464  public function listToText( array $list ) {
3465  $itemCount = count( $list );
3466  if ( $itemCount < 1 ) {
3467  return '';
3468  }
3469  $text = array_pop( $list );
3470  if ( $itemCount > 1 ) {
3471  $and = $this->msg( 'and' )->escaped();
3472  $space = $this->msg( 'word-separator' )->escaped();
3473  $comma = '';
3474  if ( $itemCount > 2 ) {
3475  $comma = $this->msg( 'comma-separator' )->escaped();
3476  }
3477  $text = implode( $comma, $list ) . $and . $space . $text;
3478  }
3479  return $text;
3480  }
3481 
3488  public function commaList( array $list ) {
3489  return implode(
3490  wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3491  $list
3492  );
3493  }
3494 
3501  public function semicolonList( array $list ) {
3502  return implode(
3503  wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3504  $list
3505  );
3506  }
3507 
3513  public function pipeList( array $list ) {
3514  return implode(
3515  wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3516  $list
3517  );
3518  }
3519 
3535  public function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3536  return $this->truncateInternal(
3537  $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
3538  );
3539  }
3540 
3559  public function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3560  // Passing encoding to mb_strlen and mb_substr is optional.
3561  // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
3562  // explicit specification of encoding is skipped.
3563  // Note: Both multibyte methods are callables invoked in truncateInternal.
3564  return $this->truncateInternal(
3565  $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
3566  );
3567  }
3568 
3585  private function truncateInternal(
3586  $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring
3587  ) {
3588  # Check if there is no need to truncate
3589  if ( $measureLength( $string ) <= abs( $length ) ) {
3590  return $string; // no need to truncate
3591  }
3592 
3593  # Use the localized ellipsis character
3594  if ( $ellipsis == '...' ) {
3595  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3596  }
3597  if ( $length == 0 ) {
3598  return $ellipsis; // convention
3599  }
3600 
3601  $stringOriginal = $string;
3602  # If ellipsis length is >= $length then we can't apply $adjustLength
3603  if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
3604  $string = $ellipsis; // this can be slightly unexpected
3605  # Otherwise, truncate and add ellipsis...
3606  } else {
3607  $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
3608  if ( $length > 0 ) {
3609  $length -= $ellipsisLength;
3610  $string = $getSubstring( $string, 0, $length ); // xyz...
3611  $string = $this->removeBadCharLast( $string );
3612  $string = rtrim( $string ) . $ellipsis;
3613  } else {
3614  $length += $ellipsisLength;
3615  $string = $getSubstring( $string, $length ); // ...xyz
3616  $string = $this->removeBadCharFirst( $string );
3617  $string = $ellipsis . ltrim( $string );
3618  }
3619  }
3620 
3621  # Do not truncate if the ellipsis makes the string longer/equal (T24181).
3622  # This check is *not* redundant if $adjustLength, due to the single case where
3623  # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3624  if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
3625  return $string;
3626  } else {
3627  return $stringOriginal;
3628  }
3629  }
3630 
3638  protected function removeBadCharLast( $string ) {
3639  if ( $string != '' ) {
3640  $char = ord( $string[strlen( $string ) - 1] );
3641  $m = [];
3642  if ( $char >= 0xc0 ) {
3643  # We got the first byte only of a multibyte char; remove it.
3644  $string = substr( $string, 0, -1 );
3645  } elseif ( $char >= 0x80 &&
3646  // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3647  preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3648  '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3649  ) {
3650  # We chopped in the middle of a character; remove it
3651  $string = $m[1];
3652  }
3653  }
3654  return $string;
3655  }
3656 
3664  protected function removeBadCharFirst( $string ) {
3665  if ( $string != '' ) {
3666  $char = ord( $string[0] );
3667  if ( $char >= 0x80 && $char < 0xc0 ) {
3668  # We chopped in the middle of a character; remove the whole thing
3669  $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3670  }
3671  }
3672  return $string;
3673  }
3674 
3690  public function truncateHtml( $text, $length, $ellipsis = '...' ) {
3691  # Use the localized ellipsis character
3692  if ( $ellipsis == '...' ) {
3693  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3694  }
3695  # Check if there is clearly no need to truncate
3696  if ( $length <= 0 ) {
3697  return $ellipsis; // no text shown, nothing to format (convention)
3698  } elseif ( strlen( $text ) <= $length ) {
3699  return $text; // string short enough even *with* HTML (short-circuit)
3700  }
3701 
3702  $dispLen = 0; // innerHTML legth so far
3703  $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3704  $tagType = 0; // 0-open, 1-close
3705  $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3706  $entityState = 0; // 0-not entity, 1-entity
3707  $tag = $ret = ''; // accumulated tag name, accumulated result string
3708  $openTags = []; // open tag stack
3709  $maybeState = null; // possible truncation state
3710 
3711  $textLen = strlen( $text );
3712  $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3713  for ( $pos = 0; true; ++$pos ) {
3714  # Consider truncation once the display length has reached the maximim.
3715  # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3716  # Check that we're not in the middle of a bracket/entity...
3717  if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3718  if ( !$testingEllipsis ) {
3719  $testingEllipsis = true;
3720  # Save where we are; we will truncate here unless there turn out to
3721  # be so few remaining characters that truncation is not necessary.
3722  if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3723  $maybeState = [ $ret, $openTags ]; // save state
3724  }
3725  } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3726  # String in fact does need truncation, the truncation point was OK.
3727  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
3728  list( $ret, $openTags ) = $maybeState; // reload state
3729  $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3730  $ret .= $ellipsis; // add ellipsis
3731  break;
3732  }
3733  }
3734  if ( $pos >= $textLen ) {
3735  break; // extra iteration just for above checks
3736  }
3737 
3738  # Read the next char...
3739  $ch = $text[$pos];
3740  $lastCh = $pos ? $text[$pos - 1] : '';
3741  $ret .= $ch; // add to result string
3742  if ( $ch == '<' ) {
3743  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3744  $entityState = 0; // for bad HTML
3745  $bracketState = 1; // tag started (checking for backslash)
3746  } elseif ( $ch == '>' ) {
3747  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3748  $entityState = 0; // for bad HTML
3749  $bracketState = 0; // out of brackets
3750  } elseif ( $bracketState == 1 ) {
3751  if ( $ch == '/' ) {
3752  $tagType = 1; // close tag (e.g. "</span>")
3753  } else {
3754  $tagType = 0; // open tag (e.g. "<span>")
3755  $tag .= $ch;
3756  }
3757  $bracketState = 2; // building tag name
3758  } elseif ( $bracketState == 2 ) {
3759  if ( $ch != ' ' ) {
3760  $tag .= $ch;
3761  } else {
3762  // Name found (e.g. "<a href=..."), add on tag attributes...
3763  $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3764  }
3765  } elseif ( $bracketState == 0 ) {
3766  if ( $entityState ) {
3767  if ( $ch == ';' ) {
3768  $entityState = 0;
3769  $dispLen++; // entity is one displayed char
3770  }
3771  } else {
3772  if ( $neLength == 0 && !$maybeState ) {
3773  // Save state without $ch. We want to *hit* the first
3774  // display char (to get tags) but not *use* it if truncating.
3775  $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3776  }
3777  if ( $ch == '&' ) {
3778  $entityState = 1; // entity found, (e.g. "&#160;")
3779  } else {
3780  $dispLen++; // this char is displayed
3781  // Add the next $max display text chars after this in one swoop...
3782  $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3783  $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3784  $dispLen += $skipped;
3785  $pos += $skipped;
3786  }
3787  }
3788  }
3789  }
3790  // Close the last tag if left unclosed by bad HTML
3791  $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3792  while ( count( $openTags ) > 0 ) {
3793  $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3794  }
3795  return $ret;
3796  }
3797 
3809  private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3810  if ( $len === null ) {
3811  $len = -1; // -1 means "no limit" for strcspn
3812  } elseif ( $len < 0 ) {
3813  $len = 0; // sanity
3814  }
3815  $skipCount = 0;
3816  if ( $start < strlen( $text ) ) {
3817  $skipCount = strcspn( $text, $search, $start, $len );
3818  $ret .= substr( $text, $start, $skipCount );
3819  }
3820  return $skipCount;
3821  }
3822 
3832  private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3833  $tag = ltrim( $tag );
3834  if ( $tag != '' ) {
3835  if ( $tagType == 0 && $lastCh != '/' ) {
3836  $openTags[] = $tag; // tag opened (didn't close itself)
3837  } elseif ( $tagType == 1 ) {
3838  if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3839  array_pop( $openTags ); // tag closed
3840  }
3841  }
3842  $tag = '';
3843  }
3844  }
3845 
3854  public function convertGrammar( $word, $case ) {
3855  global $wgGrammarForms;
3856  if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3857  return $wgGrammarForms[$this->getCode()][$case][$word];
3858  }
3859 
3860  $grammarTransformations = $this->getGrammarTransformations();
3861 
3862  if ( isset( $grammarTransformations[$case] ) ) {
3863  $forms = $grammarTransformations[$case];
3864 
3865  // Some names of grammar rules are aliases for other rules.
3866  // In such cases the value is a string rather than object,
3867  // so load the actual rules.
3868  if ( is_string( $forms ) ) {
3869  $forms = $grammarTransformations[$forms];
3870  }
3871 
3872  foreach ( array_values( $forms ) as $rule ) {
3873  $form = $rule[0];
3874 
3875  if ( $form === '@metadata' ) {
3876  continue;
3877  }
3878 
3879  $replacement = $rule[1];
3880 
3881  $regex = '/' . addcslashes( $form, '/' ) . '/u';
3882  $patternMatches = preg_match( $regex, $word );
3883 
3884  if ( $patternMatches === false ) {
3885  wfLogWarning(
3886  'An error occurred while processing grammar. ' .
3887  "Word: '$word'. Regex: /$form/."
3888  );
3889  } elseif ( $patternMatches === 1 ) {
3890  $word = preg_replace( $regex, $replacement, $word );
3891 
3892  break;
3893  }
3894  }
3895  }
3896 
3897  return $word;
3898  }
3899 
3905  public function getGrammarForms() {
3906  global $wgGrammarForms;
3907  if ( isset( $wgGrammarForms[$this->getCode()] )
3908  && is_array( $wgGrammarForms[$this->getCode()] )
3909  ) {
3910  return $wgGrammarForms[$this->getCode()];
3911  }
3912 
3913  return [];
3914  }
3915 
3925  public function getGrammarTransformations() {
3926  global $IP;
3927  if ( $this->grammarTransformCache !== null ) {
3928  return $this->grammarTransformCache;
3929  }
3930 
3931  $grammarDataFile = $IP . "/languages/data/grammarTransformations/{$this->getCode()}.json";
3932  $this->grammarTransformCache = is_readable( $grammarDataFile )
3933  ? FormatJson::decode( file_get_contents( $grammarDataFile ), true )
3934  : [];
3935 
3936  if ( $this->grammarTransformCache === null ) {
3937  throw new MWException( "Invalid grammar data for \"{$this->getCode()}\"." );
3938  }
3939 
3940  return $this->grammarTransformCache;
3941  }
3942 
3962  public function gender( $gender, $forms ) {
3963  if ( !count( $forms ) ) {
3964  return '';
3965  }
3966  $forms = $this->preConvertPlural( $forms, 2 );
3967  if ( $gender === 'male' ) {
3968  return $forms[0];
3969  }
3970  if ( $gender === 'female' ) {
3971  return $forms[1];
3972  }
3973  return $forms[2] ?? $forms[0];
3974  }
3975 
3991  public function convertPlural( $count, $forms ) {
3992  // Handle explicit n=pluralform cases
3993  $forms = $this->handleExplicitPluralForms( $count, $forms );
3994  if ( is_string( $forms ) ) {
3995  return $forms;
3996  }
3997  if ( !count( $forms ) ) {
3998  return '';
3999  }
4000 
4001  $pluralForm = $this->getPluralRuleIndexNumber( $count );
4002  $pluralForm = min( $pluralForm, count( $forms ) - 1 );
4003  return $forms[$pluralForm];
4004  }
4005 
4021  protected function handleExplicitPluralForms( $count, array $forms ) {
4022  foreach ( $forms as $index => $form ) {
4023  if ( preg_match( '/\d+=/i', $form ) ) {
4024  $pos = strpos( $form, '=' );
4025  if ( substr( $form, 0, $pos ) === (string)$count ) {
4026  return substr( $form, $pos + 1 );
4027  }
4028  unset( $forms[$index] );
4029  }
4030  }
4031  return array_values( $forms );
4032  }
4033 
4042  protected function preConvertPlural( /* Array */ $forms, $count ) {
4043  return array_pad( $forms, $count, end( $forms ) );
4044  }
4045 
4062  public function embedBidi( $text = '' ) {
4063  $dir = self::strongDirFromContent( $text );
4064  if ( $dir === 'ltr' ) {
4065  // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
4066  return self::LRE . $text . self::PDF;
4067  }
4068  if ( $dir === 'rtl' ) {
4069  // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
4070  return self::RLE . $text . self::PDF;
4071  }
4072  // No strong directionality: do not wrap
4073  return $text;
4074  }
4075 
4089  public function translateBlockExpiry( $str, UserIdentity $user = null, $now = 0 ) {
4090  $duration = SpecialBlock::getSuggestedDurations( $this );
4091  foreach ( $duration as $show => $value ) {
4092  if ( strcmp( $str, $value ) == 0 ) {
4093  return trim( $show );
4094  }
4095  }
4096 
4097  if ( wfIsInfinity( $str ) ) {
4098  foreach ( $duration as $show => $value ) {
4099  if ( wfIsInfinity( $value ) ) {
4100  return trim( $show );
4101  }
4102  }
4103  }
4104 
4105  // If all else fails, return a standard duration or timestamp description.
4106  $time = strtotime( $str, $now );
4107  if ( $time === false ) { // Unknown format. Return it as-is in case.
4108  return $str;
4109  } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
4110  // The result differs based on current time, so the difference
4111  // is a fixed duration length.
4112  return $this->formatDuration( $time - $now );
4113  } else { // It's an absolute timestamp.
4114  if ( $time === 0 ) {
4115  // wfTimestamp() handles 0 as current time instead of epoch.
4116  $time = '19700101000000';
4117  }
4118  if ( $user ) {
4119  return $this->userTimeAndDate( $time, $user );
4120  }
4121  return $this->timeanddate( $time );
4122  }
4123  }
4124 
4132  public function segmentForDiff( $text ) {
4133  return $text;
4134  }
4135 
4142  public function unsegmentForDiff( $text ) {
4143  return $text;
4144  }
4145 
4155  public function getConverter(): ILanguageConverter {
4156  return $this->converterFactory->getLanguageConverter( $this );
4157  }
4158 
4169  public function autoConvert( $text, $variant = false ) {
4170  return $this->getConverter()->autoConvert( $text, $variant );
4171  }
4172 
4181  public function autoConvertToAllVariants( $text ) {
4182  return $this->getConverter()->autoConvertToAllVariants( $text );
4183  }
4184 
4199  public function convert( $text ) {
4200  return $this->getConverter()->convert( $text );
4201  }
4202 
4213  public function convertNamespace( $ns, $variant = null ) {
4214  return $this->getConverter()->convertNamespace( $ns, $variant );
4215  }
4216 
4224  public function hasVariants() {
4225  return count( $this->getVariants() ) > 1;
4226  }
4227 
4240  public function hasVariant( $variant ) {
4241  return $this->getConverter()->hasVariant( $variant );
4242  }
4243 
4253  public function convertHtml( $text ) {
4254  return htmlspecialchars( $this->convert( $text ) );
4255  }
4256 
4263  public function convertCategoryKey( $key ) {
4264  return $this->getConverter()->convertCategoryKey( $key );
4265  }
4266 
4275  public function getVariants() {
4276  return $this->getConverter()->getVariants();
4277  }
4278 
4283  public function getPreferredVariant() {
4284  return $this->getConverter()->getPreferredVariant();
4285  }
4286 
4291  public function getDefaultVariant() {
4292  return $this->getConverter()->getDefaultVariant();
4293  }
4294 
4299  public function getURLVariant() {
4300  return $this->getConverter()->getURLVariant();
4301  }
4302 
4311  public function getExtraHashOptions() {
4312  return $this->getConverter()->getExtraHashOptions();
4313  }
4314 
4321  public function linkTrail() {
4322  return $this->localisationCache->getItem( $this->mCode, 'linkTrail' );
4323  }
4324 
4331  public function linkPrefixCharset() {
4332  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixCharset' );
4333  }
4334 
4343  public function getParentLanguage() {
4344  return MediaWikiServices::getInstance()->getLanguageFactory()
4345  ->getParentLanguage( $this->getCode() );
4346  }
4347 
4355  public function equals( Language $lang ) {
4356  return $lang === $this || $lang->getCode() === $this->mCode;
4357  }
4358 
4367  public function getCode() {
4368  return $this->mCode;
4369  }
4370 
4381  public function getHtmlCode() {
4382  if ( $this->mHtmlCode === null ) {
4383  $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
4384  }
4385  return $this->mHtmlCode;
4386  }
4387 
4395  public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4396  $m = null;
4397  preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4398  preg_quote( $suffix, '/' ) . '/', $filename, $m );
4399  if ( !count( $m ) ) {
4400  return false;
4401  }
4402  return str_replace( '_', '-', strtolower( $m[1] ) );
4403  }
4404 
4415  public static function getFileName( $prefix, $code, $suffix = '.php' ) {
4416  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4417  ->getFileName( $prefix, $code, $suffix );
4418  }
4419 
4425  public static function getMessagesFileName( $code ) {
4426  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4427  ->getMessagesFileName( $code );
4428  }
4429 
4437  public static function getJsonMessagesFileName( $code ) {
4438  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4439  ->getJsonMessagesFileName( $code );
4440  }
4441 
4450  public static function getFallbackFor( $code ) {
4451  return MediaWikiServices::getInstance()->getLanguageFallback()->getFirst( $code )
4452  ?? false;
4453  }
4454 
4467  public static function getFallbacksFor( $code, $mode = LanguageFallback::MESSAGES ) {
4468  return MediaWikiServices::getInstance()->getLanguageFallback()->getAll( $code, $mode );
4469  }
4470 
4481  public static function getFallbacksIncludingSiteLanguage( $code ) {
4482  return MediaWikiServices::getInstance()->getLanguageFallback()
4483  ->getAllIncludingSiteLanguage( $code );
4484  }
4485 
4497  public static function getMessagesFor( $code ) {
4498  return self::getLocalisationCache()->getItem( $code, 'messages' );
4499  }
4500 
4511  public static function getMessageFor( $key, $code ) {
4512  return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4513  }
4514 
4525  public static function getMessageKeysFor( $code ) {
4526  return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
4527  }
4528 
4533  private function fixVariableInNamespace( $talk ) {
4534  if ( strpos( $talk, '$1' ) === false ) {
4535  return $talk;
4536  }
4537 
4538  global $wgMetaNamespace;
4539  $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4540 
4541  # Allow grammar transformations
4542  # Allowing full message-style parsing would make simple requests
4543  # such as action=raw much more expensive than they need to be.
4544  # This will hopefully cover most cases.
4545  $talk = preg_replace_callback(
4546  '/{{grammar:(.*?)\|(.*?)}}/i',
4547  function ( $m ) {
4548  return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4549  },
4550  $talk
4551  );
4552  return str_replace( ' ', '_', $talk );
4553  }
4554 
4567  public function formatExpiry( $expiry, $format = true, $infinity = 'infinity', $user = null ) {
4568  static $dbInfinity;
4569  if ( $dbInfinity === null ) {
4570  $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
4571  }
4572 
4573  if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4574  return $format === true
4575  ? $this->getMessageFromDB( 'infiniteblock' )
4576  : $infinity;
4577  } else {
4578  if ( $format === true ) {
4579  return $user
4580  ? $this->userTimeAndDate( $expiry, $user )
4581  : $this->timeanddate( $expiry, /* User preference timezone */ true );
4582  }
4583  return wfTimestamp( $format, $expiry );
4584  }
4585  }
4586 
4601  public function formatTimePeriod( $seconds, $format = [] ) {
4602  if ( !is_array( $format ) ) {
4603  $format = [ 'avoid' => $format ]; // For backwards compatibility
4604  }
4605  if ( !isset( $format['avoid'] ) ) {
4606  $format['avoid'] = false;
4607  }
4608  if ( !isset( $format['noabbrevs'] ) ) {
4609  $format['noabbrevs'] = false;
4610  }
4611  $secondsMsg = wfMessage(
4612  $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4613  $minutesMsg = wfMessage(
4614  $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4615  $hoursMsg = wfMessage(
4616  $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4617  $daysMsg = wfMessage(
4618  $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4619 
4620  if ( round( $seconds * 10 ) < 100 ) {
4621  $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4622  $s = $secondsMsg->params( $s )->text();
4623  } elseif ( round( $seconds ) < 60 ) {
4624  $s = $this->formatNum( round( $seconds ) );
4625  $s = $secondsMsg->params( $s )->text();
4626  } elseif ( round( $seconds ) < 3600 ) {
4627  $minutes = floor( $seconds / 60 );
4628  $secondsPart = round( fmod( $seconds, 60 ) );
4629  if ( $secondsPart == 60 ) {
4630  $secondsPart = 0;
4631  $minutes++;
4632  }
4633  $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4634  $s .= ' ';
4635  $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4636  } elseif ( round( $seconds ) <= 2 * 86400 ) {
4637  $hours = floor( $seconds / 3600 );
4638  $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4639  $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4640  if ( $secondsPart == 60 ) {
4641  $secondsPart = 0;
4642  $minutes++;
4643  }
4644  if ( $minutes == 60 ) {
4645  $minutes = 0;
4646  $hours++;
4647  }
4648  $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4649  $s .= ' ';
4650  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4651  if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes', 'avoidhours' ] ) ) {
4652  $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4653  }
4654  } else {
4655  $days = floor( $seconds / 86400 );
4656  if ( $format['avoid'] === 'avoidhours' ) {
4657  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4658  if ( $hours == 24 ) {
4659  $hours = 0;
4660  $days++;
4661  }
4662  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4663  } elseif ( $format['avoid'] === 'avoidminutes' ) {
4664  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4665  if ( $hours == 24 ) {
4666  $hours = 0;
4667  $days++;
4668  }
4669  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4670  $s .= ' ';
4671  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4672  } elseif ( $format['avoid'] === 'avoidseconds' ) {
4673  $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4674  $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4675  if ( $minutes == 60 ) {
4676  $minutes = 0;
4677  $hours++;
4678  }
4679  if ( $hours == 24 ) {
4680  $hours = 0;
4681  $days++;
4682  }
4683  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4684  $s .= ' ';
4685  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4686  $s .= ' ';
4687  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4688  } else {
4689  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4690  $s .= ' ';
4691  $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4692  }
4693  }
4694  return $s;
4695  }
4696 
4708  public function formatBitrate( $bps ) {
4709  return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4710  }
4711 
4718  public function formatComputingNumbers( $size, $boundary, $messageKey ) {
4719  if ( $size <= 0 ) {
4720  return str_replace( '$1', $this->formatNum( $size ),
4721  $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4722  );
4723  }
4724  $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'yotta' ];
4725  $index = 0;
4726 
4727  $maxIndex = count( $sizes ) - 1;
4728  while ( $size >= $boundary && $index < $maxIndex ) {
4729  $index++;
4730  $size /= $boundary;
4731  }
4732 
4733  // For small sizes no decimal places necessary
4734  $round = 0;
4735  if ( $index > 1 ) {
4736  // For MB and bigger two decimal places are smarter
4737  $round = 2;
4738  }
4739  $msg = str_replace( '$1', $sizes[$index], $messageKey );
4740 
4741  $size = round( $size, $round );
4742  $text = $this->getMessageFromDB( $msg );
4743  return str_replace( '$1', $this->formatNum( $size ), $text );
4744  }
4745 
4756  public function formatSize( $size ) {
4757  return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4758  }
4759 
4769  public function specialList( $page, $details, $oppositedm = true ) {
4770  if ( !$details ) {
4771  return $page;
4772  }
4773 
4774  $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4775  return $page .
4776  $dirmark .
4777  $this->msg( 'word-separator' )->escaped() .
4778  $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4779  }
4780 
4788  public function getConvRuleTitle() {
4789  return $this->getConverter()->getConvRuleTitle();
4790  }
4791 
4797  public function getCompiledPluralRules() {
4798  $pluralRules =
4799  $this->localisationCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4800  if ( !$pluralRules ) {
4801  $fallbacks = $this->getFallbackLanguages();
4802  foreach ( $fallbacks as $fallbackCode ) {
4803  $pluralRules = $this->localisationCache
4804  ->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4805  if ( $pluralRules ) {
4806  break;
4807  }
4808  }
4809  }
4810  return $pluralRules;
4811  }
4812 
4818  public function getPluralRules() {
4819  $pluralRules =
4820  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4821  if ( !$pluralRules ) {
4822  $fallbacks = $this->getFallbackLanguages();
4823  foreach ( $fallbacks as $fallbackCode ) {
4824  $pluralRules = $this->localisationCache
4825  ->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4826  if ( $pluralRules ) {
4827  break;
4828  }
4829  }
4830  }
4831  return $pluralRules;
4832  }
4833 
4839  public function getPluralRuleTypes() {
4840  $pluralRuleTypes =
4841  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4842  if ( !$pluralRuleTypes ) {
4843  $fallbacks = $this->getFallbackLanguages();
4844  foreach ( $fallbacks as $fallbackCode ) {
4845  $pluralRuleTypes = $this->localisationCache
4846  ->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4847  if ( $pluralRuleTypes ) {
4848  break;
4849  }
4850  }
4851  }
4852  return $pluralRuleTypes;
4853  }
4854 
4860  public function getPluralRuleIndexNumber( $number ) {
4861  $pluralRules = $this->getCompiledPluralRules();
4862  $form = Evaluator::evaluateCompiled( $number, $pluralRules );
4863  return $form;
4864  }
4865 
4874  public function getPluralRuleType( $number ) {
4875  $index = $this->getPluralRuleIndexNumber( $number );
4876  $pluralRuleTypes = $this->getPluralRuleTypes();
4877  return $pluralRuleTypes[$index] ?? 'other';
4878  }
4879 
4886  protected function getHookContainer() {
4887  return $this->hookContainer;
4888  }
4889 
4898  protected function getHookRunner() {
4899  return $this->hookRunner;
4900  }
4901 }
Language\$mCode
$mCode
Definition: Language.php:65
Language\$langFallback
LanguageFallback $langFallback
Definition: Language.php:103
Language\getCodeFromFileName
static getCodeFromFileName( $filename, $prefix='Language', $suffix='.php')
Get the language code from a file name.
Definition: Language.php:4395
Language\getExtraHashOptions
getExtraHashOptions()
returns language specific options used by User::getPageRenderHash() for example, the preferred langua...
Definition: Language.php:4311
Language\lc
lc( $str, $first=false)
Definition: Language.php:2732
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:38
Language\parseFormattedNumber
parseFormattedNumber( $number)
Definition: Language.php:3376
Language\getURLVariant
getURLVariant()
Definition: Language.php:4299
Language\getVariantname
getVariantname( $code, $usemsg=true)
short names for language variants used for language conversion links.
Definition: Language.php:799
Language\$hookContainer
HookContainer $hookContainer
Definition: Language.php:116
Language\getHookRunner
getHookRunner()
Get a HookRunner, for running core hooks.
Definition: Language.php:4898
Language\linkPrefixExtension
linkPrefixExtension()
To allow "foo[[bar]]" to extend the link over the whole word "foobar".
Definition: Language.php:3123
Language\$langNameUtils
LanguageNameUtils $langNameUtils
Definition: Language.php:100
StringUtils\isUtf8
static isUtf8( $value)
Test whether a string is valid UTF-8.
Definition: StringUtils.php:44
Language\truncate_endBracket
truncate_endBracket(&$tag, $tagType, $lastCh, &$openTags)
truncateHtml() helper function (a) push or pop $tag from $openTags as needed (b) clear $tag value
Definition: Language.php:3832
Language\commaList
commaList(array $list)
Take a list of strings and build a locale-friendly comma-separated list, using the local comma-separa...
Definition: Language.php:3488
Language\semicolonList
semicolonList(array $list)
Take a list of strings and build a locale-friendly semicolon-separated list, using the local semicolo...
Definition: Language.php:3501
Language\$mIranianCalendarMonthMsgs
static $mIranianCalendarMonthMsgs
Definition: Language.php:216
Language\$mMonthAbbrevMsgs
static $mMonthAbbrevMsgs
Definition: Language.php:201
Language\formatSize
formatSize( $size)
Format a size in bytes for output, using an appropriate unit (B, KB, MB, GB, TB, PB,...
Definition: Language.php:4756
Language\separatorTransformTable
separatorTransformTable()
Definition: Language.php:3445
Language\WEEKDAY_ABBREVIATED_MESSAGES
const WEEKDAY_ABBREVIATED_MESSAGES
Definition: Language.php:153
Language\resetNamespaces
resetNamespaces()
Resets all of the namespace caches.
Definition: Language.php:589
Language\getConverter
getConverter()
Return the LanguageConverter used in the Language.
Definition: Language.php:4155
Language\hasVariants
hasVariants()
Check if this is a language with variants.
Definition: Language.php:4224
Language\$mWeekdayAbbrevMsgs
static $mWeekdayAbbrevMsgs
Definition: Language.php:160
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:199
Language\preConvertPlural
preConvertPlural($forms, $count)
Checks that convertPlural was given an array and pads it to requested amount of forms by copying the ...
Definition: Language.php:4042
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
Language\convertHtml
convertHtml( $text)
Perform output conversion on a string, and encode for safe HTML output.
Definition: Language.php:4253
Language\minimumGroupingDigits
minimumGroupingDigits()
Definition: Language.php:3452
Language\segmentByWord
segmentByWord( $string)
Some languages such as Chinese require word segmentation, Specify such segmentation when overridden i...
Definition: Language.php:2868
Language\$transformData
ReplacementArray[] $transformData
Definition: Language.php:94
Language\iconv
iconv( $in, $out, $string)
Definition: Language.php:2639
n
while(( $__line=Maintenance::readconsole()) !==false) print n
Definition: eval.php:69
Language\getMessageFromDB
getMessageFromDB( $msg)
Get a message from the MediaWiki namespace.
Definition: Language.php:894
Language\convert
convert( $text)
convert text to different variants of a language.
Definition: Language.php:4199
Language\ALL
const ALL
Return all known languages in fetchLanguageName(s).
Definition: Language.php:55
true
return true
Definition: router.php:90
Language\convertGrammar
convertGrammar( $word, $case)
Grammatical transformations, needed for inflected languages Invoked by putting {{grammar:case|word}} ...
Definition: Language.php:3854
Language\mbUpperChar
mbUpperChar( $char)
Convert character to uppercase, allowing overrides of the default mb_upper behaviour,...
Definition: Language.php:2699
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=LanguageFallback::MESSAGES)
Get the ordered list of fallback languages.
Definition: Language.php:4467
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1665
Language\truncateForVisual
truncateForVisual( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified number of characters, appending an optional string (e....
Definition: Language.php:3559
Language\$mMonthGenMsgs
static $mMonthGenMsgs
Definition: Language.php:188
Language\timeanddate
timeanddate( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2293
Language\$grammarTransformCache
array[] null $grammarTransformCache
Definition: Language.php:106
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1183
Language\MESSAGES_FALLBACKS
const MESSAGES_FALLBACKS
Return a fallback chain for messages in getFallbacksFor.
Definition: Language.php:128
Language\$mHijriCalendarMonthMsgs
static $mHijriCalendarMonthMsgs
Definition: Language.php:263
Language\$namespaceNames
array null $namespaceNames
Definition: Language.php:88
Language\formatNumInternal
formatNumInternal(string $number, bool $noTranslate, bool $noSeparators)
Internal implementation function, shared between commafy, formatNum, and formatNumNoSeparators.
Definition: Language.php:3219
Language\getPreferredVariant
getPreferredVariant()
Definition: Language.php:4283
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1056
User\getDatePreference
getDatePreference()
Get the user's preferred date format.
Definition: User.php:2779
Language\getDefaultVariant
getDefaultVariant()
Definition: Language.php:4291
Language\fallback8bitEncoding
fallback8bitEncoding()
Definition: Language.php:2845
Language\embedBidi
embedBidi( $text='')
Wraps argument with unicode control characters for directionality safety.
Definition: Language.php:4062
Language\truncateInternal
truncateInternal( $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring)
Internal method used for truncation.
Definition: Language.php:3585
Language\formatTimePeriod
formatTimePeriod( $seconds, $format=[])
Formats a time given in seconds into a string representation of that time.
Definition: Language.php:4601
Language\formatBitrate
formatBitrate( $bps)
Format a bitrate for output, using an appropriate unit (bps, kbps, Mbps, Gbps, Tbps,...
Definition: Language.php:4708
Language\equals
equals(Language $lang)
Compare with an other language object.
Definition: Language.php:4355
Language\SUPPORTED
const SUPPORTED
Return in fetchLanguageName(s) only the languages for which we have at least some localisation.
Definition: Language.php:63
Language\getSpecialPageAliases
getSpecialPageAliases()
Get special page names, as an associative array canonical name => array of valid names,...
Definition: Language.php:3157
Language\getGroupName
getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
Definition: Language.php:2613
Language\__construct
__construct( $code=null, LocalisationCache $localisationCache=null, LanguageNameUtils $langNameUtils=null, LanguageFallback $langFallback=null, LanguageConverterFactory $converterFactory=null, HookContainer $hookContainer=null)
Definition: Language.php:460
Language\getMessagesFileName
static getMessagesFileName( $code)
Definition: Language.php:4425
Language\getPluralRuleTypes
getPluralRuleTypes()
Get the plural rule types for the language.
Definition: Language.php:4839
Language\AS_AUTONYMS
const AS_AUTONYMS
Return autonyms in fetchLanguageName(s).
Definition: Language.php:48
Language\specialList
specialList( $page, $details, $oppositedm=true)
Make a list item, used by various special pages.
Definition: Language.php:4769
MediaWiki\Languages\LanguageConverterFactory
An interface for creating language converters.
Definition: LanguageConverterFactory.php:46
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
$separatorTransformTable
$separatorTransformTable
Definition: MessagesAf.php:199
Language\$mHebrewCalendarMonthGenMsgs
static $mHebrewCalendarMonthGenMsgs
Definition: Language.php:248
$wgMetaNamespace
$wgMetaNamespace
Name of the project namespace.
Definition: DefaultSettings.php:4544
Language\checkTitleEncoding
checkTitleEncoding( $s)
TODO: $s is not always a string per T218883.
Definition: Language.php:2831
Language\isWellFormedLanguageTag
static isWellFormedLanguageTag( $code, $lenient=false)
Returns true if a language code string is a well-formed language tag according to RFC 5646.
Definition: Language.php:350
Language\getFormattedNamespaces
getFormattedNamespaces()
A convenience function that returns getNamespaces() with spaces instead of underscores in values.
Definition: Language.php:601
Language\lcfirst
lcfirst( $str)
Definition: Language.php:2709
MediaWiki\Languages\LanguageNameUtils
A service that provides utilities to do with language names and codes.
Definition: LanguageNameUtils.php:42
Language\isKnownLanguageTag
static isKnownLanguageTag( $tag)
Returns true if a language code is an IETF tag known to MediaWiki.
Definition: Language.php:437
Language\emphasize
emphasize( $text)
Italic is unsuitable for some languages.
Definition: Language.php:3174
Language\getFallbackLanguages
getFallbackLanguages()
Definition: Language.php:522
Language\getDurationIntervals
getDurationIntervals( $seconds, array $chosenIntervals=[])
Takes a number of seconds and returns an array with a set of corresponding intervals.
Definition: Language.php:2338
Language\caseFold
caseFold( $s)
Return a case-folded representation of $s.
Definition: Language.php:2822
Language\segmentForDiff
segmentForDiff( $text)
languages like Chinese need to be segmented in order for the diff to be of any use
Definition: Language.php:4132
Language\needsGenderDistinction
needsGenderDistinction()
Whether this language uses gender-dependent namespace aliases.
Definition: Language.php:666
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:146
Language\getLocalisationCache
static getLocalisationCache()
Definition: Language.php:446
MWException
MediaWiki exception.
Definition: MWException.php:29
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:997
Language\tsToIranian
static tsToIranian( $ts)
Algorithm by Roozbeh Pournader and Mohammad Toossi to convert Gregorian dates to Iranian dates.
Definition: Language.php:1575
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
Language\unsegmentForDiff
unsegmentForDiff( $text)
and unsegment to show the result
Definition: Language.php:4142
Language\autoConvert
autoConvert( $text, $variant=false)
convert text to a variant
Definition: Language.php:4169
Language\truncateHtml
truncateHtml( $text, $length, $ellipsis='...')
Truncate a string of valid HTML to a specified length in bytes, appending an optional string (e....
Definition: Language.php:3690
Language\normalize
normalize( $s)
Convert a UTF-8 string to normal form C.
Definition: Language.php:2984
Language\getBookstoreList
getBookstoreList()
Exports $wgBookstoreListEn.
Definition: Language.php:530
Language\userDate
userDate( $ts, UserIdentity $user, array $options=[])
Get the formatted date for the given timestamp and formatted for the given user.
Definition: Language.php:2434
Language\$mHebrewCalendarMonthMsgs
static $mHebrewCalendarMonthMsgs
Definition: Language.php:232
Language\DURATION_INTERVALS
const DURATION_INTERVALS
Definition: Language.php:268
Language\pipeList
pipeList(array $list)
Same as commaList, but separate it with the pipe instead.
Definition: Language.php:3513
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2200
Language\convertForSearchResult
convertForSearchResult( $termsArray)
Definition: Language.php:2921
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4511
$matches
$matches
Definition: NoLocalSettings.php:24
Language\getGenderNsText
getGenderNsText( $index, $gender)
Returns gender-dependent namespace alias if available.
Definition: Language.php:651
Language\getHumanTimestamp
getHumanTimestamp(MWTimestamp $time, MWTimestamp $relativeTo=null, UserIdentity $user=null)
Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
Definition: Language.php:2499
Language\listToText
listToText(array $list)
Take a list of strings and build a locale-friendly comma-separated list, using the local comma-separa...
Definition: Language.php:3464
Language\getHtmlCode
getHtmlCode()
Get the code in BCP 47 format which we can use inside of html lang="" tags.
Definition: Language.php:4381
Language\getNamespaceAliases
getNamespaceAliases()
Definition: Language.php:700
NS_PROJECT
const NS_PROJECT
Definition: Defines.php:68
Language\$mExtendedSpecialPageAliases
array[] $mExtendedSpecialPageAliases
memoize
Definition: Language.php:85
Language\getLocalNsIndex
getLocalNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:690
MediaWiki
A helper class for throttling authentication attempts.
Language\$mMonthMsgs
static $mMonthMsgs
Definition: Language.php:174
Language\truncateForDatabase
truncateForDatabase( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified length in bytes, appending an optional string (e....
Definition: Language.php:3535
Language\getAllMessages
getAllMessages()
Definition: Language.php:2629
Language\getMagic
getMagic( $mw)
Fill a MagicWord object with data from here.
Definition: Language.php:3140
Language\userTime
userTime( $ts, UserIdentity $user, array $options=[])
Get the formatted time for the given timestamp and formatted for the given user.
Definition: Language.php:2457
$wgOverrideUcfirstCharacters
array $wgOverrideUcfirstCharacters
List of Unicode characters for which capitalization is overridden in Language::ucfirst.
Definition: DefaultSettings.php:3728
Language\isRTL
isRTL()
For right-to-left language support.
Definition: Language.php:3021
Language\getNsIndex
getNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:781
Language\MONTH_GENITIVE_MESSAGES
const MONTH_GENITIVE_MESSAGES
Definition: Language.php:179
Language\getNamespaceIds
getNamespaceIds()
Definition: Language.php:757
Language\getPluralRuleIndexNumber
getPluralRuleIndexNumber( $number)
Find the index number of the plural rule appropriate for the given number.
Definition: Language.php:4860
Language\HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
const HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
Definition: Language.php:237
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
Language\convertDoubleWidth
static convertDoubleWidth( $string)
convert double-width roman characters to single-width.
Definition: Language.php:2891
Language\getCompiledPluralRules
getCompiledPluralRules()
Get the compiled plural rules for the language.
Definition: Language.php:4797
Language\getHumanTimestampInternal
getHumanTimestampInternal(MWTimestamp $ts, MWTimestamp $relativeTo, User $user)
Convert an MWTimestamp into a pretty human-readable timestamp using the given user preferences and re...
Definition: Language.php:2541
Language\convertCategoryKey
convertCategoryKey( $key)
Definition: Language.php:4263
Language\digitGroupingPattern
digitGroupingPattern()
Definition: Language.php:3431
Language\$hookRunner
HookRunner $hookRunner
Definition: Language.php:121
Language\ucwords
ucwords( $str)
Definition: Language.php:2752
Language\getPluralRules
getPluralRules()
Get the plural rules for the language.
Definition: Language.php:4818
Language\getArrow
getArrow( $direction='forwards')
An arrow, depending on the language direction.
Definition: Language.php:3101
Language\uc
uc( $str, $first=false)
Definition: Language.php:2678
Language\formatNumNoSeparators
formatNumNoSeparators( $number)
Front-end for non-commafied formatNum.
Definition: Language.php:3368
$wgTranslateNumerals
$wgTranslateNumerals
For Hindi and Arabic use local numerals instead of Western style (0-9) numerals in interface.
Definition: DefaultSettings.php:3570
Language\$mHtmlCode
$mHtmlCode
Definition: Language.php:72
Language\MONTH_ABBREVIATED_MESSAGES
const MONTH_ABBREVIATED_MESSAGES
Definition: Language.php:193
$digitGroupingPattern
$digitGroupingPattern
Definition: MessagesAr.php:473
$wgNamespaceAliases
$wgNamespaceAliases
Define extra namespace aliases.
Definition: DefaultSettings.php:4619
Language\isValidBuiltInCode
static isValidBuiltInCode( $code)
Returns true if a language code is of a valid form for the purposes of internal customisation of Medi...
Definition: Language.php:422
Language\$converterFactory
LanguageConverterFactory $converterFactory
Definition: Language.php:111
Language\formatDuration
formatDuration( $seconds, array $chosenIntervals=[])
Takes a number of seconds and turns it into a text using values such as hours and minutes.
Definition: Language.php:2312
Language\setNamespaces
setNamespaces(array $namespaces)
Arbitrarily set all of the namespace names at once.
Definition: Language.php:581
Language\linkPrefixCharset
linkPrefixCharset()
A regular expression character set to match legal word-prefixing characters which should be merged on...
Definition: Language.php:4331
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
ReplacementArray
Wrapper around strtr() that holds replacements.
Definition: ReplacementArray.php:24
Language\fixVariableInNamespace
fixVariableInNamespace( $talk)
Definition: Language.php:4533
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:29
Language\ucwordbreaks
ucwordbreaks( $str)
capitalize words at word breaks
Definition: Language.php:2778
Language\getNsText
getNsText( $index)
Get a namespace value by key.
Definition: Language.php:620
$wgLocalTZoffset
$wgLocalTZoffset
Set an offset from UTC in minutes to use for the default timezone setting for anonymous users and new...
Definition: DefaultSettings.php:3715
Language\getCode
getCode()
Get the internal language code for this language object.
Definition: Language.php:4367
Language\LRE
const LRE
Unicode directional formatting characters, for embedBidi()
Definition: Language.php:290
Language\getPluralRuleType
getPluralRuleType( $number)
Find the plural rule type appropriate for the given number For example, if the language is set to Ara...
Definition: Language.php:4874
Language\dateFormat
dateFormat( $usePrefs=true)
This is meant to be used by time(), date(), and timeanddate() to get the date preference they're supp...
Definition: Language.php:2186
$wgMetaNamespaceTalk
$wgMetaNamespaceTalk
Name of the project talk namespace.
Definition: DefaultSettings.php:4553
Language\transformUsingPairFile
transformUsingPairFile(string $dataClass, string $input)
Transform a string using serialized data stored in the given file (which must be in the serialized su...
Definition: Language.php:3008
Language\hebrewNumeral
static hebrewNumeral( $num)
Hebrew Gematria number formatting up to 9999.
Definition: Language.php:2017
Language\internalUserTimeAndDate
internalUserTimeAndDate( $type, $ts, UserIdentity $user, array $options)
Internal helper function for userDate(), userTime() and userTimeAndDate()
Definition: Language.php:2390
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2522
Language\getFormattedNsText
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with '_' changed to ' ',...
Definition: Language.php:638
Language\getMessagesFor
static getMessagesFor( $code)
Get all messages for a given language WARNING: this may take a long time.
Definition: Language.php:4497
Language\handleExplicitPluralForms
handleExplicitPluralForms( $count, array $forms)
Handles explicit plural forms for Language::convertPlural()
Definition: Language.php:4021
Language\RLE
const RLE
Definition: Language.php:291
Language\getFileName
static getFileName( $prefix, $code, $suffix='.php')
Get the name of a file for a certain language code.
Definition: Language.php:4415
LocalisationCache
Class for caching the contents of localisation files, Messages*.php and *.i18n.php.
Definition: LocalisationCache.php:43
Language\MONTH_MESSAGES
const MONTH_MESSAGES
Definition: Language.php:165
Language\getHookContainer
getHookContainer()
Get a HookContainer, for hook metadata and running extension hooks.
Definition: Language.php:4886
Language\HEBREW_CALENDAR_MONTHS_MESSAGES
const HEBREW_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:221
NS_USER
const NS_USER
Definition: Defines.php:66
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
Language\getDirMark
getDirMark( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3085
Language\normalizeForSearch
normalizeForSearch( $string)
Some languages have special punctuation need to be normalized.
Definition: Language.php:2879
Language\isValidCode
static isValidCode( $code)
Returns true if a language code string is of a valid form, whether or not it exists.
Definition: Language.php:407
Language\userAdjust
userAdjust( $ts, $tz=false)
Used by date() and time() to adjust the time output.
Definition: Language.php:2104
Language\formatComputingNumbers
formatComputingNumbers( $size, $boundary, $messageKey)
Definition: Language.php:4718
$userOptionsLookup
UserOptionsLookup $userOptionsLookup
Definition: ApiWatchlistTrait.php:33
Language\userTimeAndDate
userTimeAndDate( $ts, UserIdentity $user, array $options=[])
Get the formatted date and time for the given timestamp and formatted for the given user.
Definition: Language.php:2480
Language\getFallbackFor
static getFallbackFor( $code)
Get the first fallback for a given language.
Definition: Language.php:4450
Language\getParentLanguage
getParentLanguage()
Get the "parent" language which has a converter to convert a "compatible" language (in another varian...
Definition: Language.php:4343
Language\$dateFormatStrings
$dateFormatStrings
memoize
Definition: Language.php:78
Language\hasWordBreaks
hasWordBreaks()
Most writing systems use whitespace to break up words.
Definition: Language.php:2857
Language\getDir
getDir()
Return the correct HTML 'dir' attribute value for this language.
Definition: Language.php:3029
Language\date
date( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2254
Language\alignEnd
alignEnd()
Return 'right' or 'left' as appropriate alignment for line-end for this language's text direction.
Definition: Language.php:3053
Language\truncate_skip
truncate_skip(&$ret, $text, $search, $start, $len=null)
truncateHtml() helper function like strcspn() but adds the skipped chars to $ret
Definition: Language.php:3809
Language\getVariants
getVariants()
Get the list of variants supported by this language see sample implementation in LanguageZh....
Definition: Language.php:4275
Language\convertPlural
convertPlural( $count, $forms)
Plural form transformations, needed for some languages.
Definition: Language.php:3991
Language\getFallbacksIncludingSiteLanguage
static getFallbacksIncludingSiteLanguage( $code)
Get the ordered list of fallback languages, ending with the fallback language chain for the site lang...
Definition: Language.php:4481
$wgGrammarForms
$wgGrammarForms
Some languages need different word forms, usually for different cases.
Definition: DefaultSettings.php:3454
Language\getGrammarForms
getGrammarForms()
Get the grammar forms for the content language.
Definition: Language.php:3905
Language\removeBadCharFirst
removeBadCharFirst( $string)
Remove bytes that represent an incomplete Unicode character at the start of string (e....
Definition: Language.php:3664
Language\$strongDirRegex
static $strongDirRegex
Directionality test regex for embedBidi().
Definition: Language.php:307
LanguageCode\bcp47
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: LanguageCode.php:175
$wgExtraGenderNamespaces
$wgExtraGenderNamespaces
Same as above, but for namespaces with gender distinction.
Definition: DefaultSettings.php:4596
Language\getMessage
getMessage( $key)
Definition: Language.php:2622
Language\getGrammarTransformations
getGrammarTransformations()
Get the grammar transformations data for the language.
Definition: Language.php:3925
Language\getMessageKeysFor
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4525
Language\getJsonMessagesFileName
static getJsonMessagesFileName( $code)
Definition: Language.php:4437
Language\IRANIAN_CALENDAR_MONTHS_MESSAGES
const IRANIAN_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:206
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:67
Language\firstChar
firstChar( $s)
Get the first character of a string.
Definition: Language.php:2933
Language\getNamespaces
getNamespaces()
Returns an array of localised namespaces indexed by their numbers.
Definition: Language.php:540
Language\$localisationCache
LocalisationCache $localisationCache
Definition: Language.php:97
SpecialBlock\getSuggestedDurations
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
Definition: SpecialBlock.php:946
Language\removeBadCharLast
removeBadCharLast( $string)
Remove bytes that represent an incomplete Unicode character at the end of string (e....
Definition: Language.php:3638
Language\romanNumeral
static romanNumeral( $num)
Roman number formatting up to 10000.
Definition: Language.php:1986
Language\getConvRuleTitle
getConvRuleTitle()
Get the conversion rule title, if any.
Definition: Language.php:4788
Language\formatExpiry
formatExpiry( $expiry, $format=true, $infinity='infinity', $user=null)
Decode an expiry (block, protection, etc) which has come from the DB.
Definition: Language.php:4567
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:317
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Language\translateBlockExpiry
translateBlockExpiry( $str, UserIdentity $user=null, $now=0)
Definition: Language.php:4089
Language\PDF
const PDF
Definition: Language.php:292
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1043
Language\$namespaceAliases
$namespaceAliases
Definition: Language.php:89
Language\tsToHijri
static tsToHijri( $ts)
Converting Gregorian dates to Hijri dates.
Definition: Language.php:1635
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:557
$t
$t
Definition: testCompression.php:74
Language\time
time( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2273
Language\formatNum
formatNum( $number, $noSeparators=null)
Normally we output all numbers in plain en_US style, that is 293,291.235 for two hundred ninety-three...
Definition: Language.php:3200
$minimumGroupingDigits
$minimumGroupingDigits
Definition: MessagesBg.php:223
Language\insertSpace
static insertSpace( $string, $pattern)
Definition: Language.php:2911
Language\isMultibyte
isMultibyte( $str)
Definition: Language.php:2744
Language\alignStart
alignStart()
Return 'left' or 'right' as appropriate alignment for line-start for this language's text direction.
Definition: Language.php:3041
Language\isSupportedLanguage
static isSupportedLanguage( $code)
Checks whether any localisation is available for that language tag in MediaWiki (MessagesXx....
Definition: Language.php:330
Language\$mWeekdayMsgs
static $mWeekdayMsgs
Definition: Language.php:148
NS_PROJECT_TALK
const NS_PROJECT_TALK
Definition: Defines.php:69
Language\digitTransformTable
digitTransformTable()
Definition: Language.php:3438
Language\tsToYear
static tsToYear( $ts, $cName)
Algorithm to convert Gregorian dates to Thai solar dates, Minguo dates or Minguo dates.
Definition: Language.php:1863
Language\getDirMarkEntity
getDirMarkEntity( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3068
Language\strongDirFromContent
static strongDirFromContent( $text='')
Gets directionality of the first strongly directional codepoint, for embedBidi()
Definition: Language.php:1969
Language\hebrewYearStart
static hebrewYearStart( $year)
This calculates the Hebrew year start, as days since 1 September.
Definition: Language.php:1825
Language\$mNamespaceIds
$mNamespaceIds
Definition: Language.php:89
$IP
$IP
Definition: WebStart.php:49
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:68
Language\getDateFormatString
getDateFormatString( $type, $pref)
Get a format string for a given type and preference.
Definition: Language.php:2218
Language\getMagicWords
getMagicWords()
Get all magic words from cache.
Definition: Language.php:3131
Language\hasVariant
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: Language.php:4240
Language\__destruct
__destruct()
Reduce memory usage.
Definition: Language.php:512
Language\commafy
commafy( $number)
Adds commas to a given number.
Definition: Language.php:3419
Language\HIJRI_CALENDAR_MONTH_MESSAGES
const HIJRI_CALENDAR_MONTH_MESSAGES
Definition: Language.php:253
Language\STRICT_FALLBACKS
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:135
$wgExtraNamespaces
$wgExtraNamespaces
Additional namespaces.
Definition: DefaultSettings.php:4588
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
Language\$durationIntervals
static array $durationIntervals
Definition: Language.php:285
Language\tsToHebrew
static tsToHebrew( $ts)
Converting Gregorian dates to Hebrew dates.
Definition: Language.php:1687
Language\autoConvertToAllVariants
autoConvertToAllVariants( $text)
convert text to all supported variants
Definition: Language.php:4181
MWTimestamp\offsetForUser
offsetForUser(UserIdentity $user)
Adjust the timestamp depending on the given user's preferences.
Definition: MWTimestamp.php:85
Language\linkTrail
linkTrail()
A regular expression to match legal word-trailing characters which should be merged onto a link of th...
Definition: Language.php:4321
$wgAllUnicodeFixes
$wgAllUnicodeFixes
Set this to always convert certain Unicode sequences to modern ones regardless of the content languag...
Definition: DefaultSettings.php:3532
Language\ucfirst
ucfirst( $str)
Definition: Language.php:2654
Language\$mMagicExtensions
$mMagicExtensions
Definition: Language.php:70
Language\gender
gender( $gender, $forms)
Provides an alternative text depending on specified gender.
Definition: Language.php:3962
Language\WEEKDAY_MESSAGES
const WEEKDAY_MESSAGES
Definition: Language.php:140
$type
$type
Definition: testCompression.php:52
Language\convertNamespace
convertNamespace( $ns, $variant=null)
Convert a namespace index to a string in the preferred variant.
Definition: Language.php:4213