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 
95  public $transformData = [];
96 
99 
101  private $langNameUtils;
102 
104  private $langFallback;
105 
108 
113 
117  private $hookContainer;
118 
122  private $hookRunner;
123 
129  public const MESSAGES_FALLBACKS = LanguageFallback::MESSAGES;
130 
136  public const STRICT_FALLBACKS = LanguageFallback::STRICT;
137 
141  public const WEEKDAY_MESSAGES = [
142  'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
143  'friday', 'saturday'
144  ];
145 
150 
155  'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
156  ];
157 
162 
166  public const MONTH_MESSAGES = [
167  'january', 'february', 'march', 'april', 'may_long', 'june',
168  'july', 'august', 'september', 'october', 'november',
169  'december'
170  ];
171 
176 
180  public const MONTH_GENITIVE_MESSAGES = [
181  'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
182  'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
183  'december-gen'
184  ];
185 
190 
194  public const MONTH_ABBREVIATED_MESSAGES = [
195  'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
196  'sep', 'oct', 'nov', 'dec'
197  ];
198 
203 
208  'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
209  'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
210  'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
211  'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
212  ];
213 
218 
223  'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
224  'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
225  'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
226  'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
227  'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
228  ];
229 
234 
239  'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
240  'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
241  'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
242  'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
243  'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
244  ];
245 
250 
255  'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
256  'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
257  'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
258  'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
259  ];
260 
265 
269  protected const DURATION_INTERVALS = [
270  'millennia' => 31556952000,
271  'centuries' => 3155695200,
272  'decades' => 315569520,
273  'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
274  'weeks' => 604800,
275  'days' => 86400,
276  'hours' => 3600,
277  'minutes' => 60,
278  'seconds' => 1,
279  ];
280 
287 
291  private const LRE = "\u{202A}"; // U+202A LEFT-TO-RIGHT EMBEDDING
292  private const RLE = "\u{202B}"; // U+202B RIGHT-TO-LEFT EMBEDDING
293  private const PDF = "\u{202C}"; // U+202C POP DIRECTIONAL FORMATTING
294 
306  // @codeCoverageIgnoreStart
307  // phpcs:ignore Generic.Files.LineLength
308  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';
309  // @codeCoverageIgnoreEnd
310 
318  public static function factory( $code ) {
319  return MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $code );
320  }
321 
331  public static function isSupportedLanguage( $code ) {
332  return MediaWikiServices::getInstance()->getLanguageNameUtils()
333  ->isSupportedLanguage( $code );
334  }
335 
351  public static function isWellFormedLanguageTag( $code, $lenient = false ) {
352  $alpha = '[a-z]';
353  $digit = '[0-9]';
354  $alphanum = '[a-z0-9]';
355  $x = 'x'; # private use singleton
356  $singleton = '[a-wy-z]'; # other singleton
357  $s = $lenient ? '[-_]' : '-';
358 
359  $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
360  $script = "$alpha{4}"; # ISO 15924
361  $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
362  $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
363  $extension = "$singleton(?:$s$alphanum{2,8})+";
364  $privateUse = "$x(?:$s$alphanum{1,8})+";
365 
366  # Define certain grandfathered codes, since otherwise the regex is pretty useless.
367  # Since these are limited, this is safe even later changes to the registry --
368  # the only oddity is that it might change the type of the tag, and thus
369  # the results from the capturing groups.
370  # https://www.iana.org/assignments/language-subtag-registry
371 
372  $grandfathered = "en{$s}GB{$s}oed"
373  . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
374  . "|no{$s}(?:bok|nyn)"
375  . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
376  . "|zh{$s}min{$s}nan";
377 
378  $variantList = "$variant(?:$s$variant)*";
379  $extensionList = "$extension(?:$s$extension)*";
380 
381  $langtag = "(?:($language)"
382  . "(?:$s$script)?"
383  . "(?:$s$region)?"
384  . "(?:$s$variantList)?"
385  . "(?:$s$extensionList)?"
386  . "(?:$s$privateUse)?)";
387 
388  # The final breakdown, with capturing groups for each of these components
389  # The variants, extensions, grandfathered, and private-use may have interior '-'
390 
391  $root = "^(?:$langtag|$privateUse|$grandfathered)$";
392 
393  return (bool)preg_match( "/$root/", strtolower( $code ) );
394  }
395 
408  public static function isValidCode( $code ) {
409  return MediaWikiServices::getInstance()->getLanguageNameUtils()->isValidCode( $code );
410  }
411 
423  public static function isValidBuiltInCode( $code ) {
424  return MediaWikiServices::getInstance()->getLanguageNameUtils()
425  ->isValidBuiltInCode( $code );
426  }
427 
438  public static function isKnownLanguageTag( $tag ) {
439  return MediaWikiServices::getInstance()->getLanguageNameUtils()
440  ->isKnownLanguageTag( $tag );
441  }
442 
447  public static function getLocalisationCache() {
448  return MediaWikiServices::getInstance()->getLocalisationCache();
449  }
450 
461  public function __construct(
462  $code = null,
468  ) {
469  if ( !func_num_args() ) {
470  // Old calling convention, deprecated
471  if ( static::class === 'Language' ) {
472  $this->mCode = 'en';
473  } else {
474  $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
475  }
476 
477  $services = MediaWikiServices::getInstance();
478  $this->localisationCache = $services->getLocalisationCache();
479  $this->langNameUtils = $services->getLanguageNameUtils();
480  $this->langFallback = $services->getLanguageFallback();
481  $this->converterFactory = $services->getLanguageConverterFactory();
482  $this->hookContainer = $services->getHookContainer();
483  $this->hookRunner = new HookRunner( $this->hookContainer );
484  return;
485  }
486 
487  Assert::parameter( $code !== null, '$code',
488  'Parameters cannot be null unless all are omitted' );
489  Assert::parameter( $localisationCache !== null, '$localisationCache',
490  'Parameters cannot be null unless all are omitted' );
491  Assert::parameter( $langNameUtils !== null, '$langNameUtils',
492  'Parameters cannot be null unless all are omitted' );
493  Assert::parameter( $langFallback !== null, '$langFallback',
494  'Parameters cannot be null unless all are omitted' );
495  Assert::parameter( $converterFactory !== null, '$converterFactory',
496  'Parameters cannot be null unless all are omitted' );
497  Assert::parameter( $hookContainer !== null, '$hookContainer',
498  'Parameters cannot be null unless all are omitted' );
499 
500  $this->mCode = $code;
501  $this->localisationCache = $localisationCache;
502  $this->langNameUtils = $langNameUtils;
503  $this->langFallback = $langFallback;
504  $this->converterFactory = $converterFactory;
505  $this->hookContainer = $hookContainer;
506  $this->hookRunner = new HookRunner( $hookContainer );
507  }
508 
513  public function __destruct() {
514  foreach ( $this as $name => $value ) {
515  unset( $this->$name );
516  }
517  }
518 
523  public function getFallbackLanguages() {
524  return $this->langFallback->getAll( $this->mCode );
525  }
526 
531  public function getBookstoreList() {
532  return $this->localisationCache->getItem( $this->mCode, 'bookstoreList' );
533  }
534 
541  public function getNamespaces() {
542  if ( $this->namespaceNames === null ) {
544 
545  $validNamespaces = MediaWikiServices::getInstance()->getNamespaceInfo()->
546  getCanonicalNamespaces();
547 
548  $this->namespaceNames = $wgExtraNamespaces +
549  $this->localisationCache->getItem( $this->mCode, 'namespaceNames' );
550  $this->namespaceNames += $validNamespaces;
551 
552  $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
553  if ( $wgMetaNamespaceTalk ) {
554  $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
555  } else {
556  $talk = $this->namespaceNames[NS_PROJECT_TALK];
557  $this->namespaceNames[NS_PROJECT_TALK] =
558  $this->fixVariableInNamespace( $talk );
559  }
560 
561  # Sometimes a language will be localised but not actually exist on this wiki.
562  foreach ( $this->namespaceNames as $key => $text ) {
563  if ( !isset( $validNamespaces[$key] ) ) {
564  unset( $this->namespaceNames[$key] );
565  }
566  }
567 
568  # The above mixing may leave namespaces out of canonical order.
569  # Re-order by namespace ID number...
570  ksort( $this->namespaceNames );
571 
572  $this->getHookRunner()->onLanguageGetNamespaces( $this->namespaceNames );
573  }
574 
575  return $this->namespaceNames;
576  }
577 
582  public function setNamespaces( array $namespaces ) {
583  $this->namespaceNames = $namespaces;
584  $this->mNamespaceIds = null;
585  }
586 
590  public function resetNamespaces() {
591  $this->namespaceNames = null;
592  $this->mNamespaceIds = null;
593  $this->namespaceAliases = null;
594  }
595 
602  public function getFormattedNamespaces() {
603  $ns = $this->getNamespaces();
604  foreach ( $ns as $k => $v ) {
605  $ns[$k] = strtr( $v, '_', ' ' );
606  }
607  return $ns;
608  }
609 
621  public function getNsText( $index ) {
622  $ns = $this->getNamespaces();
623  return $ns[$index] ?? false;
624  }
625 
639  public function getFormattedNsText( $index ) {
640  $ns = $this->getNsText( $index );
641  return strtr( $ns, '_', ' ' );
642  }
643 
652  public function getGenderNsText( $index, $gender ) {
654 
656  (array)$this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
657 
658  return $ns[$index][$gender] ?? $this->getNsText( $index );
659  }
660 
667  public function needsGenderDistinction() {
669  if ( count( $wgExtraGenderNamespaces ) > 0 ) {
670  // $wgExtraGenderNamespaces overrides everything
671  return true;
672  } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
673  // @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
674  // $wgExtraNamespaces overrides any gender aliases specified in i18n files
675  return false;
676  } else {
677  // Check what is in i18n files
678  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
679  return count( $aliases ) > 0;
680  }
681  }
682 
691  public function getLocalNsIndex( $text ) {
692  $lctext = $this->lc( $text );
693  $ids = $this->getNamespaceIds();
694  return $ids[$lctext] ?? false;
695  }
696 
701  public function getNamespaceAliases() {
702  if ( $this->namespaceAliases === null ) {
703  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceAliases' );
704  if ( !$aliases ) {
705  $aliases = [];
706  } else {
707  foreach ( $aliases as $name => $index ) {
708  if ( $index === NS_PROJECT_TALK ) {
709  unset( $aliases[$name] );
710  $name = $this->fixVariableInNamespace( $name );
711  $aliases[$name] = $index;
712  }
713  }
714  }
715 
717  $genders = $wgExtraGenderNamespaces + (array)$this->localisationCache
718  ->getItem( $this->mCode, 'namespaceGenderAliases' );
719  foreach ( $genders as $index => $forms ) {
720  foreach ( $forms as $alias ) {
721  $aliases[$alias] = $index;
722  }
723  }
724 
725  # Also add converted namespace names as aliases, to avoid confusion.
726  $convertedNames = [];
727  foreach ( $this->getConverter()->getVariants() as $variant ) {
728  if ( $variant === $this->mCode ) {
729  continue;
730  }
731  foreach ( $this->getNamespaces() as $ns => $_ ) {
732  $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
733  }
734  }
735 
736  $this->namespaceAliases = $aliases + $convertedNames;
737 
738  // In the case of conflicts between $wgNamespaceAliases and other sources
739  // of aliasing, $wgNamespaceAliases wins.
740  global $wgNamespaceAliases;
741  $this->namespaceAliases = $wgNamespaceAliases + $this->namespaceAliases;
742 
743  # Filter out aliases to namespaces that don't exist, e.g. from extensions
744  # that aren't loaded here but are included in the l10n cache.
745  # (array_intersect preserves keys from its first argument)
746  $this->namespaceAliases = array_intersect(
747  $this->namespaceAliases,
748  array_keys( $this->getNamespaces() )
749  );
750  }
751 
753  }
754 
758  public function getNamespaceIds() {
759  if ( $this->mNamespaceIds === null ) {
760  # Put namespace names and aliases into a hashtable.
761  # If this is too slow, then we should arrange it so that it is done
762  # before caching. The catch is that at pre-cache time, the above
763  # class-specific fixup hasn't been done.
764  $this->mNamespaceIds = [];
765  foreach ( $this->getNamespaces() as $index => $name ) {
766  $this->mNamespaceIds[$this->lc( $name )] = $index;
767  }
768  foreach ( $this->getNamespaceAliases() as $name => $index ) {
769  $this->mNamespaceIds[$this->lc( $name )] = $index;
770  }
771  }
772  return $this->mNamespaceIds;
773  }
774 
782  public function getNsIndex( $text ) {
783  $lctext = $this->lc( $text );
784  $ns = MediaWikiServices::getInstance()->getNamespaceInfo()->
785  getCanonicalIndex( $lctext );
786  if ( $ns !== null ) {
787  return $ns;
788  }
789  $ids = $this->getNamespaceIds();
790  return $ids[$lctext] ?? false;
791  }
792 
800  public function getVariantname( $code, $usemsg = true ) {
801  $msg = "variantname-$code";
802  if ( $usemsg && wfMessage( $msg )->exists() ) {
803  return $this->getMessageFromDB( $msg );
804  }
805  $name = $this->langNameUtils->getLanguageName( $code );
806  if ( $name ) {
807  return $name; # if it's defined as a language name, show that
808  } else {
809  # otherwise, output the language code
810  return $code;
811  }
812  }
813 
817  public function getDatePreferences() {
818  return $this->localisationCache->getItem( $this->mCode, 'datePreferences' );
819  }
820 
824  public function getDateFormats() {
825  return $this->localisationCache->getItem( $this->mCode, 'dateFormats' );
826  }
827 
831  public function getDefaultDateFormat() {
832  $df = $this->localisationCache->getItem( $this->mCode, 'defaultDateFormat' );
833  if ( $df === 'dmy or mdy' ) {
834  global $wgAmericanDates;
835  return $wgAmericanDates ? 'mdy' : 'dmy';
836  } else {
837  return $df;
838  }
839  }
840 
844  public function getDatePreferenceMigrationMap() {
845  return $this->localisationCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
846  }
847 
863  public static function fetchLanguageNames(
864  $inLanguage = LanguageNameUtils::AUTONYMS,
865  $include = 'mw'
866  ) {
867  return MediaWikiServices::getInstance()->getLanguageNameUtils()
868  ->getLanguageNames( $inLanguage, $include );
869  }
870 
880  public static function fetchLanguageName(
881  $code,
882  $inLanguage = LanguageNameUtils::AUTONYMS,
883  $include = LanguageNameUtils::ALL
884  ) {
885  return MediaWikiServices::getInstance()->getLanguageNameUtils()
886  ->getLanguageName( $code, $inLanguage, $include );
887  }
888 
895  public function getMessageFromDB( $msg ) {
896  return $this->msg( $msg )->text();
897  }
898 
905  protected function msg( $msg ) {
906  return wfMessage( $msg )->inLanguage( $this );
907  }
908 
913  public function getMonthName( $key ) {
914  return $this->getMessageFromDB( self::MONTH_MESSAGES[$key - 1] );
915  }
916 
920  public function getMonthNamesArray() {
921  $monthNames = [ '' ];
922  for ( $i = 1; $i < 13; $i++ ) {
923  $monthNames[] = $this->getMonthName( $i );
924  }
925  return $monthNames;
926  }
927 
932  public function getMonthNameGen( $key ) {
933  return $this->getMessageFromDB( self::MONTH_GENITIVE_MESSAGES[$key - 1] );
934  }
935 
940  public function getMonthAbbreviation( $key ) {
941  return $this->getMessageFromDB( self::MONTH_ABBREVIATED_MESSAGES[$key - 1] );
942  }
943 
947  public function getMonthAbbreviationsArray() {
948  $monthNames = [ '' ];
949  for ( $i = 1; $i < 13; $i++ ) {
950  $monthNames[] = $this->getMonthAbbreviation( $i );
951  }
952  return $monthNames;
953  }
954 
959  public function getWeekdayName( $key ) {
960  return $this->getMessageFromDB( self::WEEKDAY_MESSAGES[$key - 1] );
961  }
962 
967  public function getWeekdayAbbreviation( $key ) {
968  return $this->getMessageFromDB( self::WEEKDAY_ABBREVIATED_MESSAGES[$key - 1] );
969  }
970 
975  private function getIranianCalendarMonthName( $key ) {
976  return $this->getMessageFromDB( self::IRANIAN_CALENDAR_MONTHS_MESSAGES[$key - 1] );
977  }
978 
983  private function getHebrewCalendarMonthName( $key ) {
984  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTHS_MESSAGES[$key - 1] );
985  }
986 
991  private function getHebrewCalendarMonthNameGen( $key ) {
992  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES[$key - 1] );
993  }
994 
999  private function getHijriCalendarMonthName( $key ) {
1000  return $this->getMessageFromDB( self::HIJRI_CALENDAR_MONTH_MESSAGES[$key - 1] );
1001  }
1002 
1011  private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1012  if ( !$dateTimeObj ) {
1013  $dateTimeObj = DateTime::createFromFormat(
1014  'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1015  );
1016  }
1017  return $dateTimeObj->format( $code );
1018  }
1019 
1090  public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
1091  $s = '';
1092  $raw = false;
1093  $roman = false;
1094  $hebrewNum = false;
1095  $dateTimeObj = false;
1096  $rawToggle = false;
1097  $iranian = false;
1098  $hebrew = false;
1099  $hijri = false;
1100  $thai = false;
1101  $minguo = false;
1102  $tenno = false;
1103 
1104  $usedSecond = false;
1105  $usedMinute = false;
1106  $usedHour = false;
1107  $usedAMPM = false;
1108  $usedDay = false;
1109  $usedWeek = false;
1110  $usedMonth = false;
1111  $usedYear = false;
1112  $usedISOYear = false;
1113  $usedIsLeapYear = false;
1114 
1115  $usedHebrewMonth = false;
1116  $usedIranianMonth = false;
1117  $usedHijriMonth = false;
1118  $usedHebrewYear = false;
1119  $usedIranianYear = false;
1120  $usedHijriYear = false;
1121  $usedTennoYear = false;
1122 
1123  if ( strlen( $ts ) !== 14 ) {
1124  throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1125  }
1126 
1127  if ( !ctype_digit( $ts ) ) {
1128  throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1129  }
1130 
1131  $formatLength = strlen( $format );
1132  for ( $p = 0; $p < $formatLength; $p++ ) {
1133  $num = false;
1134  $code = $format[$p];
1135  if ( $code == 'x' && $p < $formatLength - 1 ) {
1136  $code .= $format[++$p];
1137  }
1138 
1139  if ( ( $code === 'xi'
1140  || $code === 'xj'
1141  || $code === 'xk'
1142  || $code === 'xm'
1143  || $code === 'xo'
1144  || $code === 'xt' )
1145  && $p < $formatLength - 1 ) {
1146  $code .= $format[++$p];
1147  }
1148 
1149  switch ( $code ) {
1150  case 'xx':
1151  $s .= 'x';
1152  break;
1153  case 'xn':
1154  $raw = true;
1155  break;
1156  case 'xN':
1157  $rawToggle = !$rawToggle;
1158  break;
1159  case 'xr':
1160  $roman = true;
1161  break;
1162  case 'xh':
1163  $hebrewNum = true;
1164  break;
1165  case 'xg':
1166  $usedMonth = true;
1167  $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1168  break;
1169  case 'xjx':
1170  $usedHebrewMonth = true;
1171  if ( !$hebrew ) {
1172  $hebrew = self::tsToHebrew( $ts );
1173  }
1174  $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1175  break;
1176  case 'd':
1177  $usedDay = true;
1178  $num = substr( $ts, 6, 2 );
1179  break;
1180  case 'D':
1181  $usedDay = true;
1182  $s .= $this->getWeekdayAbbreviation(
1183  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1184  );
1185  break;
1186  case 'j':
1187  $usedDay = true;
1188  $num = intval( substr( $ts, 6, 2 ) );
1189  break;
1190  case 'xij':
1191  $usedDay = true;
1192  if ( !$iranian ) {
1193  $iranian = self::tsToIranian( $ts );
1194  }
1195  $num = $iranian[2];
1196  break;
1197  case 'xmj':
1198  $usedDay = true;
1199  if ( !$hijri ) {
1200  $hijri = self::tsToHijri( $ts );
1201  }
1202  $num = $hijri[2];
1203  break;
1204  case 'xjj':
1205  $usedDay = true;
1206  if ( !$hebrew ) {
1207  $hebrew = self::tsToHebrew( $ts );
1208  }
1209  $num = $hebrew[2];
1210  break;
1211  case 'l':
1212  $usedDay = true;
1213  $s .= $this->getWeekdayName(
1214  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1215  );
1216  break;
1217  case 'F':
1218  $usedMonth = true;
1219  $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1220  break;
1221  case 'xiF':
1222  $usedIranianMonth = true;
1223  if ( !$iranian ) {
1224  $iranian = self::tsToIranian( $ts );
1225  }
1226  $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1227  break;
1228  case 'xmF':
1229  $usedHijriMonth = true;
1230  if ( !$hijri ) {
1231  $hijri = self::tsToHijri( $ts );
1232  }
1233  $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1234  break;
1235  case 'xjF':
1236  $usedHebrewMonth = true;
1237  if ( !$hebrew ) {
1238  $hebrew = self::tsToHebrew( $ts );
1239  }
1240  $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1241  break;
1242  case 'm':
1243  $usedMonth = true;
1244  $num = substr( $ts, 4, 2 );
1245  break;
1246  case 'M':
1247  $usedMonth = true;
1248  $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1249  break;
1250  case 'n':
1251  $usedMonth = true;
1252  $num = intval( substr( $ts, 4, 2 ) );
1253  break;
1254  case 'xin':
1255  $usedIranianMonth = true;
1256  if ( !$iranian ) {
1257  $iranian = self::tsToIranian( $ts );
1258  }
1259  $num = $iranian[1];
1260  break;
1261  case 'xmn':
1262  $usedHijriMonth = true;
1263  if ( !$hijri ) {
1264  $hijri = self::tsToHijri( $ts );
1265  }
1266  $num = $hijri[1];
1267  break;
1268  case 'xjn':
1269  $usedHebrewMonth = true;
1270  if ( !$hebrew ) {
1271  $hebrew = self::tsToHebrew( $ts );
1272  }
1273  $num = $hebrew[1];
1274  break;
1275  case 'xjt':
1276  $usedHebrewMonth = true;
1277  if ( !$hebrew ) {
1278  $hebrew = self::tsToHebrew( $ts );
1279  }
1280  $num = $hebrew[3];
1281  break;
1282  case 'Y':
1283  $usedYear = true;
1284  $num = substr( $ts, 0, 4 );
1285  break;
1286  case 'xiY':
1287  $usedIranianYear = true;
1288  if ( !$iranian ) {
1289  $iranian = self::tsToIranian( $ts );
1290  }
1291  $num = $iranian[0];
1292  break;
1293  case 'xmY':
1294  $usedHijriYear = true;
1295  if ( !$hijri ) {
1296  $hijri = self::tsToHijri( $ts );
1297  }
1298  $num = $hijri[0];
1299  break;
1300  case 'xjY':
1301  $usedHebrewYear = true;
1302  if ( !$hebrew ) {
1303  $hebrew = self::tsToHebrew( $ts );
1304  }
1305  $num = $hebrew[0];
1306  break;
1307  case 'xkY':
1308  $usedYear = true;
1309  if ( !$thai ) {
1310  $thai = self::tsToYear( $ts, 'thai' );
1311  }
1312  $num = $thai[0];
1313  break;
1314  case 'xoY':
1315  $usedYear = true;
1316  if ( !$minguo ) {
1317  $minguo = self::tsToYear( $ts, 'minguo' );
1318  }
1319  $num = $minguo[0];
1320  break;
1321  case 'xtY':
1322  $usedTennoYear = true;
1323  if ( !$tenno ) {
1324  $tenno = self::tsToYear( $ts, 'tenno' );
1325  }
1326  $num = $tenno[0];
1327  break;
1328  case 'y':
1329  $usedYear = true;
1330  $num = substr( $ts, 2, 2 );
1331  break;
1332  case 'xiy':
1333  $usedIranianYear = true;
1334  if ( !$iranian ) {
1335  $iranian = self::tsToIranian( $ts );
1336  }
1337  $num = substr( $iranian[0], -2 );
1338  break;
1339  case 'xit':
1340  $usedIranianYear = true;
1341  if ( !$iranian ) {
1342  $iranian = self::tsToIranian( $ts );
1343  }
1344  $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
1345  break;
1346  case 'xiz':
1347  $usedIranianYear = true;
1348  if ( !$iranian ) {
1349  $iranian = self::tsToIranian( $ts );
1350  }
1351  $num = $iranian[3];
1352  break;
1353  case 'a':
1354  $usedAMPM = true;
1355  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1356  break;
1357  case 'A':
1358  $usedAMPM = true;
1359  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1360  break;
1361  case 'g':
1362  $usedHour = true;
1363  $h = substr( $ts, 8, 2 );
1364  $num = $h % 12 ?: 12;
1365  break;
1366  case 'G':
1367  $usedHour = true;
1368  $num = intval( substr( $ts, 8, 2 ) );
1369  break;
1370  case 'h':
1371  $usedHour = true;
1372  $h = substr( $ts, 8, 2 );
1373  $num = sprintf( '%02d', $h % 12 ?: 12 );
1374  break;
1375  case 'H':
1376  $usedHour = true;
1377  $num = substr( $ts, 8, 2 );
1378  break;
1379  case 'i':
1380  $usedMinute = true;
1381  $num = substr( $ts, 10, 2 );
1382  break;
1383  case 's':
1384  $usedSecond = true;
1385  $num = substr( $ts, 12, 2 );
1386  break;
1387  case 'c':
1388  case 'r':
1389  $usedSecond = true;
1390  // fall through
1391  case 'e':
1392  case 'O':
1393  case 'P':
1394  case 'T':
1395  $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1396  break;
1397  case 'w':
1398  case 'N':
1399  case 'z':
1400  $usedDay = true;
1401  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1402  break;
1403  case 'W':
1404  $usedWeek = true;
1405  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1406  break;
1407  case 't':
1408  $usedMonth = true;
1409  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1410  break;
1411  case 'L':
1412  $usedIsLeapYear = true;
1413  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1414  break;
1415  case 'o':
1416  $usedISOYear = true;
1417  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1418  break;
1419  case 'U':
1420  $usedSecond = true;
1421  // fall through
1422  case 'I':
1423  case 'Z':
1424  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1425  break;
1426  case '\\':
1427  # Backslash escaping
1428  if ( $p < $formatLength - 1 ) {
1429  $s .= $format[++$p];
1430  } else {
1431  $s .= '\\';
1432  }
1433  break;
1434  case '"':
1435  # Quoted literal
1436  if ( $p < $formatLength - 1 ) {
1437  $endQuote = strpos( $format, '"', $p + 1 );
1438  if ( $endQuote === false ) {
1439  # No terminating quote, assume literal "
1440  $s .= '"';
1441  } else {
1442  $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1443  $p = $endQuote;
1444  }
1445  } else {
1446  # Quote at end of string, assume literal "
1447  $s .= '"';
1448  }
1449  break;
1450  default:
1451  $s .= $format[$p];
1452  }
1453  if ( $num !== false ) {
1454  if ( $rawToggle || $raw ) {
1455  $s .= $num;
1456  $raw = false;
1457  } elseif ( $roman ) {
1458  $s .= self::romanNumeral( $num );
1459  $roman = false;
1460  } elseif ( $hebrewNum ) {
1461  $s .= self::hebrewNumeral( $num );
1462  $hebrewNum = false;
1463  } elseif ( preg_match( '/^[\d.]+$/', $num ) ) {
1464  $s .= $this->formatNumNoSeparators( $num );
1465  } else {
1466  $s .= $num;
1467  }
1468  }
1469  }
1470 
1471  if ( $ttl === 'unused' ) {
1472  // No need to calculate the TTL, the caller wont use it anyway.
1473  } elseif ( $usedSecond ) {
1474  $ttl = 1;
1475  } elseif ( $usedMinute ) {
1476  $ttl = 60 - substr( $ts, 12, 2 );
1477  } elseif ( $usedHour ) {
1478  $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1479  } elseif ( $usedAMPM ) {
1480  $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1481  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1482  } elseif (
1483  $usedDay ||
1484  $usedHebrewMonth ||
1485  $usedIranianMonth ||
1486  $usedHijriMonth ||
1487  $usedHebrewYear ||
1488  $usedIranianYear ||
1489  $usedHijriYear ||
1490  $usedTennoYear
1491  ) {
1492  // @todo Someone who understands the non-Gregorian calendars
1493  // should write proper logic for them so that they don't need purged every day.
1494  $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1495  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1496  } else {
1497  $possibleTtls = [];
1498  $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1499  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1500  if ( $usedWeek ) {
1501  $possibleTtls[] =
1502  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1503  $timeRemainingInDay;
1504  } elseif ( $usedISOYear ) {
1505  // December 28th falls on the last ISO week of the year, every year.
1506  // The last ISO week of a year can be 52 or 53.
1507  $lastWeekOfISOYear = DateTime::createFromFormat(
1508  'Ymd',
1509  substr( $ts, 0, 4 ) . '1228',
1510  $zone ?: new DateTimeZone( 'UTC' )
1511  )->format( 'W' );
1512  $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1513  $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1514  $timeRemainingInWeek =
1515  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1516  + $timeRemainingInDay;
1517  $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1518  }
1519 
1520  if ( $usedMonth ) {
1521  $possibleTtls[] =
1522  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1523  substr( $ts, 6, 2 ) ) * 86400
1524  + $timeRemainingInDay;
1525  } elseif ( $usedYear ) {
1526  $possibleTtls[] =
1527  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1528  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1529  + $timeRemainingInDay;
1530  } elseif ( $usedIsLeapYear ) {
1531  $year = substr( $ts, 0, 4 );
1532  $timeRemainingInYear =
1533  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1534  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1535  + $timeRemainingInDay;
1536  $mod = $year % 4;
1537  if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1538  // this isn't a leap year. see when the next one starts
1539  $nextCandidate = $year - $mod + 4;
1540  if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1541  $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1542  $timeRemainingInYear;
1543  } else {
1544  $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1545  $timeRemainingInYear;
1546  }
1547  } else {
1548  // this is a leap year, so the next year isn't
1549  $possibleTtls[] = $timeRemainingInYear;
1550  }
1551  }
1552 
1553  if ( $possibleTtls ) {
1554  $ttl = min( $possibleTtls );
1555  }
1556  }
1557 
1558  return $s;
1559  }
1560 
1561  private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1562  private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1563 
1576  private static function tsToIranian( $ts ) {
1577  $gy = substr( $ts, 0, 4 ) - 1600;
1578  $gm = substr( $ts, 4, 2 ) - 1;
1579  $gd = substr( $ts, 6, 2 ) - 1;
1580 
1581  # Days passed from the beginning (including leap years)
1582  $gDayNo = 365 * $gy
1583  + floor( ( $gy + 3 ) / 4 )
1584  - floor( ( $gy + 99 ) / 100 )
1585  + floor( ( $gy + 399 ) / 400 );
1586 
1587  // Add days of the past months of this year
1588  for ( $i = 0; $i < $gm; $i++ ) {
1589  $gDayNo += self::$GREG_DAYS[$i];
1590  }
1591 
1592  // Leap years
1593  if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1594  $gDayNo++;
1595  }
1596 
1597  // Days passed in current month
1598  $gDayNo += (int)$gd;
1599 
1600  $jDayNo = $gDayNo - 79;
1601 
1602  $jNp = floor( $jDayNo / 12053 );
1603  $jDayNo %= 12053;
1604 
1605  $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1606  $jDayNo %= 1461;
1607 
1608  if ( $jDayNo >= 366 ) {
1609  $jy += floor( ( $jDayNo - 1 ) / 365 );
1610  $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1611  }
1612 
1613  $jz = $jDayNo;
1614 
1615  for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1616  $jDayNo -= self::$IRANIAN_DAYS[$i];
1617  }
1618 
1619  $jm = $i + 1;
1620  $jd = $jDayNo + 1;
1621 
1622  return [ $jy, $jm, $jd, $jz ];
1623  }
1624 
1636  private static function tsToHijri( $ts ) {
1637  $year = substr( $ts, 0, 4 );
1638  $month = substr( $ts, 4, 2 );
1639  $day = substr( $ts, 6, 2 );
1640 
1641  $zyr = $year;
1642  $zd = $day;
1643  $zm = $month;
1644  $zy = $zyr;
1645 
1646  if (
1647  ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1648  ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1649  ) {
1650  $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1651  (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1652  (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1653  $zd - 32075;
1654  } else {
1655  $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1656  (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1657  }
1658 
1659  $zl = $zjd - 1948440 + 10632;
1660  $zn = (int)( ( $zl - 1 ) / 10631 );
1661  $zl = $zl - 10631 * $zn + 354;
1662  $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1663  ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1664  $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1665  ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1666  $zm = (int)( ( 24 * $zl ) / 709 );
1667  $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1668  $zy = 30 * $zn + $zj - 30;
1669 
1670  return [ $zy, $zm, $zd ];
1671  }
1672 
1688  private static function tsToHebrew( $ts ) {
1689  # Parse date
1690  $year = substr( $ts, 0, 4 );
1691  $month = substr( $ts, 4, 2 );
1692  $day = substr( $ts, 6, 2 );
1693 
1694  # Calculate Hebrew year
1695  $hebrewYear = $year + 3760;
1696 
1697  # Month number when September = 1, August = 12
1698  $month += 4;
1699  if ( $month > 12 ) {
1700  # Next year
1701  $month -= 12;
1702  $year++;
1703  $hebrewYear++;
1704  }
1705 
1706  # Calculate day of year from 1 September
1707  $dayOfYear = $day;
1708  for ( $i = 1; $i < $month; $i++ ) {
1709  if ( $i == 6 ) {
1710  # February
1711  $dayOfYear += 28;
1712  # Check if the year is leap
1713  if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1714  $dayOfYear++;
1715  }
1716  } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1717  $dayOfYear += 30;
1718  } else {
1719  $dayOfYear += 31;
1720  }
1721  }
1722 
1723  # Calculate the start of the Hebrew year
1724  $start = self::hebrewYearStart( $hebrewYear );
1725 
1726  # Calculate next year's start
1727  if ( $dayOfYear <= $start ) {
1728  # Day is before the start of the year - it is the previous year
1729  # Next year's start
1730  $nextStart = $start;
1731  # Previous year
1732  $year--;
1733  $hebrewYear--;
1734  # Add days since previous year's 1 September
1735  $dayOfYear += 365;
1736  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1737  # Leap year
1738  $dayOfYear++;
1739  }
1740  # Start of the new (previous) year
1741  $start = self::hebrewYearStart( $hebrewYear );
1742  } else {
1743  # Next year's start
1744  $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1745  }
1746 
1747  # Calculate Hebrew day of year
1748  $hebrewDayOfYear = $dayOfYear - $start;
1749 
1750  # Difference between year's days
1751  $diff = $nextStart - $start;
1752  # Add 12 (or 13 for leap years) days to ignore the difference between
1753  # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1754  # difference is only about the year type
1755  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1756  $diff += 13;
1757  } else {
1758  $diff += 12;
1759  }
1760 
1761  # Check the year pattern, and is leap year
1762  # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1763  # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1764  # and non-leap years
1765  $yearPattern = $diff % 30;
1766  # Check if leap year
1767  $isLeap = $diff >= 30;
1768 
1769  # Calculate day in the month from number of day in the Hebrew year
1770  # Don't check Adar - if the day is not in Adar, we will stop before;
1771  # if it is in Adar, we will use it to check if it is Adar I or Adar II
1772  $hebrewDay = $hebrewDayOfYear;
1773  $hebrewMonth = 1;
1774  $days = 0;
1775  while ( $hebrewMonth <= 12 ) {
1776  # Calculate days in this month
1777  if ( $isLeap && $hebrewMonth == 6 ) {
1778  # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1779  $days = 30;
1780  if ( $hebrewDay <= $days ) {
1781  # Day in Adar I
1782  $hebrewMonth = 13;
1783  } else {
1784  # Subtract the days of Adar I
1785  $hebrewDay -= $days;
1786  # Try Adar II
1787  $days = 29;
1788  if ( $hebrewDay <= $days ) {
1789  # Day in Adar II
1790  $hebrewMonth = 14;
1791  }
1792  }
1793  } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1794  # Cheshvan in a complete year (otherwise as the rule below)
1795  $days = 30;
1796  } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1797  # Kislev in an incomplete year (otherwise as the rule below)
1798  $days = 29;
1799  } else {
1800  # Odd months have 30 days, even have 29
1801  $days = 30 - ( $hebrewMonth - 1 ) % 2;
1802  }
1803  if ( $hebrewDay <= $days ) {
1804  # In the current month
1805  break;
1806  } else {
1807  # Subtract the days of the current month
1808  $hebrewDay -= $days;
1809  # Try in the next month
1810  $hebrewMonth++;
1811  }
1812  }
1813 
1814  return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1815  }
1816 
1826  private static function hebrewYearStart( $year ) {
1827  $a = ( 12 * ( $year - 1 ) + 17 ) % 19;
1828  $b = ( $year - 1 ) % 4;
1829  $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1830  if ( $m < 0 ) {
1831  $m--;
1832  }
1833  $Mar = intval( $m );
1834  if ( $m < 0 ) {
1835  $m++;
1836  }
1837  $m -= $Mar;
1838 
1839  $c = ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7;
1840  if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1841  $Mar++;
1842  } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1843  $Mar += 2;
1844  } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1845  $Mar++;
1846  }
1847 
1848  $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1849  return $Mar;
1850  }
1851 
1864  private static function tsToYear( $ts, $cName ) {
1865  $gy = substr( $ts, 0, 4 );
1866  $gm = substr( $ts, 4, 2 );
1867  $gd = substr( $ts, 6, 2 );
1868 
1869  if ( !strcmp( $cName, 'thai' ) ) {
1870  # Thai solar dates
1871  # Add 543 years to the Gregorian calendar
1872  # Months and days are identical
1873  $gy_offset = $gy + 543;
1874  # fix for dates between 1912 and 1941
1875  # https://en.wikipedia.org/?oldid=836596673#New_year
1876  if ( $gy >= 1912 && $gy <= 1940 ) {
1877  if ( $gm <= 3 ) {
1878  $gy_offset--;
1879  }
1880  $gm = ( $gm - 3 ) % 12;
1881  }
1882  } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1883  # Minguo dates
1884  # Deduct 1911 years from the Gregorian calendar
1885  # Months and days are identical
1886  $gy_offset = $gy - 1911;
1887  } elseif ( !strcmp( $cName, 'tenno' ) ) {
1888  # Nengō dates up to Meiji period
1889  # Deduct years from the Gregorian calendar
1890  # depending on the nengo periods
1891  # Months and days are identical
1892  if ( ( $gy < 1912 )
1893  || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1894  || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1895  ) {
1896  # Meiji period
1897  $gy_gannen = $gy - 1868 + 1;
1898  $gy_offset = $gy_gannen;
1899  if ( $gy_gannen == 1 ) {
1900  $gy_offset = '元';
1901  }
1902  $gy_offset = '明治' . $gy_offset;
1903  } elseif (
1904  ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1905  ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1906  ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1907  ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1908  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1909  ) {
1910  # Taishō period
1911  $gy_gannen = $gy - 1912 + 1;
1912  $gy_offset = $gy_gannen;
1913  if ( $gy_gannen == 1 ) {
1914  $gy_offset = '元';
1915  }
1916  $gy_offset = '大正' . $gy_offset;
1917  } elseif (
1918  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1919  ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1920  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1921  ) {
1922  # Shōwa period
1923  $gy_gannen = $gy - 1926 + 1;
1924  $gy_offset = $gy_gannen;
1925  if ( $gy_gannen == 1 ) {
1926  $gy_offset = '元';
1927  }
1928  $gy_offset = '昭和' . $gy_offset;
1929  } elseif (
1930  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd >= 8 ) ) ||
1931  ( ( $gy > 1989 ) && ( $gy < 2019 ) ) ||
1932  ( ( $gy == 2019 ) && ( $gm < 5 ) )
1933  ) {
1934  # Heisei period
1935  $gy_gannen = $gy - 1989 + 1;
1936  $gy_offset = $gy_gannen;
1937  if ( $gy_gannen == 1 ) {
1938  $gy_offset = '元';
1939  }
1940  $gy_offset = '平成' . $gy_offset;
1941  } else {
1942  # Reiwa period
1943  $gy_gannen = $gy - 2019 + 1;
1944  $gy_offset = $gy_gannen;
1945  if ( $gy_gannen == 1 ) {
1946  $gy_offset = '元';
1947  }
1948  $gy_offset = '令和' . $gy_offset;
1949  }
1950  } else {
1951  $gy_offset = $gy;
1952  }
1953 
1954  return [ $gy_offset, $gm, $gd ];
1955  }
1956 
1970  private static function strongDirFromContent( $text = '' ) {
1971  if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
1972  return null;
1973  }
1974  if ( $matches[1] === '' ) {
1975  return 'rtl';
1976  }
1977  return 'ltr';
1978  }
1979 
1987  public static function romanNumeral( $num ) {
1988  static $table = [
1989  [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
1990  [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
1991  [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
1992  [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1993  'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
1994  ];
1995 
1996  $num = intval( $num );
1997  if ( $num > 10000 || $num <= 0 ) {
1998  return $num;
1999  }
2000 
2001  $s = '';
2002  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2003  if ( $num >= $pow10 ) {
2004  $s .= $table[$i][(int)floor( $num / $pow10 )];
2005  }
2006  $num %= $pow10;
2007  }
2008  return $s;
2009  }
2010 
2018  public static function hebrewNumeral( $num ) {
2019  static $table = [
2020  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
2021  [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
2022  [ '',
2023  [ 'ק' ],
2024  [ 'ר' ],
2025  [ 'ש' ],
2026  [ 'ת' ],
2027  [ 'ת', 'ק' ],
2028  [ 'ת', 'ר' ],
2029  [ 'ת', 'ש' ],
2030  [ 'ת', 'ת' ],
2031  [ 'ת', 'ת', 'ק' ],
2032  [ 'ת', 'ת', 'ר' ],
2033  ],
2034  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
2035  ];
2036 
2037  $num = intval( $num );
2038  if ( $num > 9999 || $num <= 0 ) {
2039  return $num;
2040  }
2041 
2042  // Round thousands have special notations
2043  if ( $num === 1000 ) {
2044  return "א' אלף";
2045  } elseif ( $num % 1000 === 0 ) {
2046  return $table[0][$num / 1000] . "' אלפים";
2047  }
2048 
2049  $letters = [];
2050 
2051  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2052  if ( $num >= $pow10 ) {
2053  if ( $num === 15 || $num === 16 ) {
2054  $letters[] = $table[0][9];
2055  $letters[] = $table[0][$num - 9];
2056  $num = 0;
2057  } else {
2058  $letters = array_merge(
2059  $letters,
2060  (array)$table[$i][intval( $num / $pow10 )]
2061  );
2062 
2063  if ( $pow10 === 1000 ) {
2064  $letters[] = "'";
2065  }
2066  }
2067  }
2068 
2069  $num %= $pow10;
2070  }
2071 
2072  $preTransformLength = count( $letters );
2073  if ( $preTransformLength === 1 ) {
2074  // Add geresh (single quote) to one-letter numbers
2075  $letters[] = "'";
2076  } else {
2077  $lastIndex = $preTransformLength - 1;
2078  $letters[$lastIndex] = str_replace(
2079  [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2080  [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2081  $letters[$lastIndex]
2082  );
2083 
2084  // Add gershayim (double quote) to multiple-letter numbers,
2085  // but exclude numbers with only one letter after the thousands
2086  // (1001-1009, 1020, 1030, 2001-2009, etc.)
2087  if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2088  $letters[] = "'";
2089  } else {
2090  array_splice( $letters, -1, 0, '"' );
2091  }
2092  }
2093 
2094  return implode( $letters );
2095  }
2096 
2105  public function userAdjust( $ts, $tz = false ) {
2106  global $wgLocalTZoffset;
2107 
2108  if ( $tz === false ) {
2109  $optionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
2110  $tz = $optionsLookup->getOption(
2111  RequestContext::getMain()->getUser(),
2112  'timecorrection'
2113  );
2114  }
2115 
2116  $data = explode( '|', $tz, 3 );
2117 
2118  if ( $data[0] == 'ZoneInfo' ) {
2119  try {
2120  $userTZ = new DateTimeZone( $data[2] );
2121  $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
2122  $date->setTimezone( $userTZ );
2123  return $date->format( 'YmdHis' );
2124  } catch ( Exception $e ) {
2125  // Unrecognized timezone, default to 'Offset' with the stored offset.
2126  $data[0] = 'Offset';
2127  }
2128  }
2129 
2130  // @phan-suppress-next-line PhanSuspiciousValueComparison
2131  if ( $data[0] == 'System' || $tz == '' ) {
2132  # Global offset in minutes.
2133  $minDiff = $wgLocalTZoffset;
2134  } elseif ( $data[0] == 'Offset' ) {
2135  $minDiff = intval( $data[1] );
2136  } else {
2137  $data = explode( ':', $tz );
2138  if ( count( $data ) == 2 ) {
2139  $data[0] = intval( $data[0] );
2140  $data[1] = intval( $data[1] );
2141  $minDiff = abs( $data[0] ) * 60 + $data[1];
2142  if ( $data[0] < 0 ) {
2143  $minDiff = -$minDiff;
2144  }
2145  } else {
2146  $minDiff = intval( $data[0] ) * 60;
2147  }
2148  }
2149 
2150  # No difference ? Return time unchanged
2151  if ( $minDiff == 0 ) {
2152  return $ts;
2153  }
2154 
2155  Wikimedia\suppressWarnings(); // E_STRICT system time bitching
2156  # Generate an adjusted date; take advantage of the fact that mktime
2157  # will normalize out-of-range values so we don't have to split $minDiff
2158  # into hours and minutes.
2159  $t = mktime( (
2160  (int)substr( $ts, 8, 2 ) ), # Hours
2161  (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2162  (int)substr( $ts, 12, 2 ), # Seconds
2163  (int)substr( $ts, 4, 2 ), # Month
2164  (int)substr( $ts, 6, 2 ), # Day
2165  (int)substr( $ts, 0, 4 ) ); # Year
2166 
2167  $date = date( 'YmdHis', $t );
2168  Wikimedia\restoreWarnings();
2169 
2170  return $date;
2171  }
2172 
2188  public function dateFormat( $usePrefs = true ) {
2189  if ( is_bool( $usePrefs ) ) {
2190  if ( $usePrefs ) {
2191  $datePreference = RequestContext::getMain()
2192  ->getUser()
2193  ->getDatePreference();
2194  } else {
2195  $userOptionsLookup = MediawikiServices::getInstance()->getUserOptionsLookup();
2196  $datePreference = (string)$userOptionsLookup->getDefaultOption( 'date' );
2197  }
2198  } else {
2199  $datePreference = (string)$usePrefs;
2200  }
2201 
2202  // return int
2203  if ( $datePreference == '' ) {
2204  return 'default';
2205  }
2206 
2207  return $datePreference;
2208  }
2209 
2220  public function getDateFormatString( $type, $pref ) {
2221  $wasDefault = false;
2222  if ( $pref == 'default' ) {
2223  $wasDefault = true;
2224  $pref = $this->getDefaultDateFormat();
2225  }
2226 
2227  if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2228  $df = $this->localisationCache
2229  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2230 
2231  if ( $type === 'pretty' && $df === null ) {
2232  $df = $this->getDateFormatString( 'date', $pref );
2233  }
2234 
2235  if ( !$wasDefault && $df === null ) {
2236  $pref = $this->getDefaultDateFormat();
2237  $df = $this->localisationCache
2238  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2239  }
2240 
2241  $this->dateFormatStrings[$type][$pref] = $df;
2242  }
2243  return $this->dateFormatStrings[$type][$pref];
2244  }
2245 
2256  public function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2257  $ts = wfTimestamp( TS_MW, $ts );
2258  if ( $adj ) {
2259  $ts = $this->userAdjust( $ts, $timecorrection );
2260  }
2261  $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2262  return $this->sprintfDate( $df, $ts );
2263  }
2264 
2275  public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2276  $ts = wfTimestamp( TS_MW, $ts );
2277  if ( $adj ) {
2278  $ts = $this->userAdjust( $ts, $timecorrection );
2279  }
2280  $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2281  return $this->sprintfDate( $df, $ts );
2282  }
2283 
2295  public function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2296  $ts = wfTimestamp( TS_MW, $ts );
2297  if ( $adj ) {
2298  $ts = $this->userAdjust( $ts, $timecorrection );
2299  }
2300  $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2301  return $this->sprintfDate( $df, $ts );
2302  }
2303 
2314  public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2315  $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2316 
2317  $segments = [];
2318 
2319  foreach ( $intervals as $intervalName => $intervalValue ) {
2320  // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2321  // duration-years, duration-decades, duration-centuries, duration-millennia
2322  $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2323  $segments[] = $message->inLanguage( $this )->escaped();
2324  }
2325 
2326  return $this->listToText( $segments );
2327  }
2328 
2340  public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2341  if ( empty( $chosenIntervals ) ) {
2342  $chosenIntervals = [
2343  'millennia',
2344  'centuries',
2345  'decades',
2346  'years',
2347  'days',
2348  'hours',
2349  'minutes',
2350  'seconds'
2351  ];
2352  }
2353 
2354  $intervals = array_intersect_key( self::DURATION_INTERVALS,
2355  array_fill_keys( $chosenIntervals, true ) );
2356  $sortedNames = array_keys( $intervals );
2357  $smallestInterval = array_pop( $sortedNames );
2358 
2359  $segments = [];
2360 
2361  foreach ( $intervals as $name => $length ) {
2362  $value = floor( $seconds / $length );
2363 
2364  if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2365  $seconds -= $value * $length;
2366  $segments[$name] = $value;
2367  }
2368  }
2369 
2370  return $segments;
2371  }
2372 
2392  private function internalUserTimeAndDate( $type, $ts, UserIdentity $user, array $options ) {
2393  $ts = wfTimestamp( TS_MW, $ts );
2394  $options += [ 'timecorrection' => true, 'format' => true ];
2395  if ( $options['timecorrection'] !== false ) {
2396  if ( $options['timecorrection'] === true ) {
2397  $offset = MediaWikiServices::getInstance()
2398  ->getUserOptionsLookup()
2399  ->getOption( $user, 'timecorrection' );
2400  } else {
2401  $offset = $options['timecorrection'];
2402  }
2403  $ts = $this->userAdjust( $ts, $offset );
2404  }
2405  if ( $options['format'] === true ) {
2406  $format = MediaWikiServices::getInstance()
2407  ->getUserFactory()
2408  ->newFromUserIdentity( $user )
2409  ->getDatePreference();
2410  } else {
2411  $format = $options['format'];
2412  }
2413  $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2414  return $this->sprintfDate( $df, $ts );
2415  }
2416 
2436  public function userDate( $ts, UserIdentity $user, array $options = [] ) {
2437  return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2438  }
2439 
2459  public function userTime( $ts, UserIdentity $user, array $options = [] ) {
2460  return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2461  }
2462 
2482  public function userTimeAndDate( $ts, UserIdentity $user, array $options = [] ) {
2483  return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2484  }
2485 
2501  public function getHumanTimestamp(
2502  MWTimestamp $time, MWTimestamp $relativeTo = null, UserIdentity $user = null
2503  ) {
2504  if ( $relativeTo === null ) {
2505  $relativeTo = new MWTimestamp();
2506  }
2507  if ( $user === null ) {
2508  $user = RequestContext::getMain()->getUser();
2509  } else {
2510  // For compatibility with the hook signature and self::getHumanTimestampInternal
2511  $user = MediaWikiServices::getInstance()
2512  ->getUserFactory()
2513  ->newFromUserIdentity( $user );
2514  }
2515 
2516  // Adjust for the user's timezone.
2517  $offsetThis = $time->offsetForUser( $user );
2518  $offsetRel = $relativeTo->offsetForUser( $user );
2519 
2520  $ts = '';
2521  if ( $this->getHookRunner()->onGetHumanTimestamp( $ts, $time, $relativeTo, $user, $this ) ) {
2522  $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2523  }
2524 
2525  // Reset the timezone on the objects.
2526  $time->timestamp->sub( $offsetThis );
2527  $relativeTo->timestamp->sub( $offsetRel );
2528 
2529  return $ts;
2530  }
2531 
2543  private function getHumanTimestampInternal(
2544  MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2545  ) {
2546  $diff = $ts->diff( $relativeTo );
2547  $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2548  (int)$relativeTo->timestamp->format( 'w' ) );
2549  $days = $diff->days ?: (int)$diffDay;
2550  if ( $diff->invert || $days > 5
2551  && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2552  ) {
2553  // Timestamps are in different years: use full timestamp
2554  // Also do full timestamp for future dates
2558  $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2559  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2560  } elseif ( $days > 5 ) {
2561  // Timestamps are in same year, but more than 5 days ago: show day and month only.
2562  $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2563  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2564  } elseif ( $days > 1 ) {
2565  // Timestamp within the past week: show the day of the week and time
2566  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2567  $weekday = self::WEEKDAY_MESSAGES[$ts->timestamp->format( 'w' )];
2568  // Messages:
2569  // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2570  $ts = wfMessage( "$weekday-at" )
2571  ->inLanguage( $this )
2572  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2573  ->text();
2574  } elseif ( $days == 1 ) {
2575  // Timestamp was yesterday: say 'yesterday' and the time.
2576  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2577  $ts = wfMessage( 'yesterday-at' )
2578  ->inLanguage( $this )
2579  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2580  ->text();
2581  } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2582  // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2583  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2584  $ts = wfMessage( 'today-at' )
2585  ->inLanguage( $this )
2586  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2587  ->text();
2588 
2589  // From here on in, the timestamp was soon enough ago so that we can simply say
2590  // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2591  } elseif ( $diff->h == 1 ) {
2592  // Less than 90 minutes, but more than an hour ago.
2593  $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2594  } elseif ( $diff->i >= 1 ) {
2595  // A few minutes ago.
2596  $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2597  } elseif ( $diff->s >= 30 ) {
2598  // Less than a minute, but more than 30 sec ago.
2599  $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2600  } else {
2601  // Less than 30 seconds ago.
2602  $ts = wfMessage( 'just-now' )->text();
2603  }
2604 
2605  return $ts;
2606  }
2607 
2612  public function getMessage( $key ) {
2613  return $this->localisationCache->getSubitem( $this->mCode, 'messages', $key );
2614  }
2615 
2619  public function getAllMessages() {
2620  return $this->localisationCache->getItem( $this->mCode, 'messages' );
2621  }
2622 
2629  public function iconv( $in, $out, $string ) {
2630  # Even with //IGNORE iconv can whine about illegal characters in
2631  # *input* string. We just ignore those too.
2632  # REF: https://bugs.php.net/bug.php?id=37166
2633  # REF: https://phabricator.wikimedia.org/T18885
2634  Wikimedia\suppressWarnings();
2635  $text = iconv( $in, $out . '//IGNORE', $string );
2636  Wikimedia\restoreWarnings();
2637  return $text;
2638  }
2639 
2644  public function ucfirst( $str ) {
2645  $octetCode = ord( $str );
2646  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2647  if ( $octetCode < 96 ) {
2648  // Assume this is an uppercase/uncased ASCII character
2649  return (string)$str;
2650  } elseif ( $octetCode < 128 ) {
2651  // Assume this is a lowercase/uncased ASCII character
2652  return ucfirst( $str );
2653  }
2654 
2655  $first = mb_substr( $str, 0, 1 );
2656  return ( strlen( $first ) !== 1 )
2657  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2658  ? $this->mbUpperChar( $first ) . mb_substr( $str, 1 )
2659  // Assume this is a non-multibyte character and LC_CASE is appropriate
2660  : ucfirst( $str );
2661  }
2662 
2668  public function uc( $str, $first = false ) {
2669  if ( $first ) {
2670  return $this->ucfirst( $str );
2671  } else {
2672  return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2673  }
2674  }
2675 
2689  protected function mbUpperChar( $char ) {
2691 
2692  return $wgOverrideUcfirstCharacters[$char] ?? mb_strtoupper( $char );
2693  }
2694 
2699  public function lcfirst( $str ) {
2700  $octetCode = ord( $str );
2701  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2702  if ( $octetCode < 96 ) {
2703  // Assume this is an uppercase/uncased ASCII character
2704  return lcfirst( $str );
2705  } elseif ( $octetCode < 128 ) {
2706  // Assume this is a lowercase/uncased ASCII character
2707  return (string)$str;
2708  }
2709 
2710  return $this->isMultibyte( $str )
2711  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2712  ? mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 )
2713  // Assume this is a non-multibyte character and LC_CASE is appropriate
2714  : lcfirst( $str );
2715  }
2716 
2722  public function lc( $str, $first = false ) {
2723  if ( $first ) {
2724  return $this->lcfirst( $str );
2725  } else {
2726  return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2727  }
2728  }
2729 
2734  private function isMultibyte( $str ) {
2735  return strlen( $str ) !== mb_strlen( $str );
2736  }
2737 
2742  public function ucwords( $str ) {
2743  if ( $this->isMultibyte( $str ) ) {
2744  $str = $this->lc( $str );
2745 
2746  // regexp to find first letter in each word (i.e. after each space)
2747  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2748 
2749  // function to use to capitalize a single char
2750  return preg_replace_callback(
2751  $replaceRegexp,
2752  static function ( $matches ) {
2753  return mb_strtoupper( $matches[0] );
2754  },
2755  $str
2756  );
2757  } else {
2758  return ucwords( strtolower( $str ) );
2759  }
2760  }
2761 
2768  public function ucwordbreaks( $str ) {
2769  if ( $this->isMultibyte( $str ) ) {
2770  $str = $this->lc( $str );
2771 
2772  // since \b doesn't work for UTF-8, we explicitely define word break chars
2773  $breaks = "[ \-\‍(\‍)\}\{\.,\?!]";
2774 
2775  // find first letter after word break
2776  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2777  "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2778 
2779  return preg_replace_callback(
2780  $replaceRegexp,
2781  static function ( $matches ) {
2782  return mb_strtoupper( $matches[0] );
2783  },
2784  $str
2785  );
2786  } else {
2787  return preg_replace_callback(
2788  '/\b([\w\x80-\xff]+)\b/',
2789  function ( $matches ) {
2790  return $this->ucfirst( $matches[1] );
2791  },
2792  $str
2793  );
2794  }
2795  }
2796 
2812  public function caseFold( $s ) {
2813  return $this->uc( $s );
2814  }
2815 
2821  public function checkTitleEncoding( $s ) {
2822  if ( is_array( $s ) ) {
2823  throw new MWException( 'Given array to checkTitleEncoding.' );
2824  }
2825  if ( StringUtils::isUtf8( $s ) ) {
2826  return $s;
2827  }
2828 
2829  return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2830  }
2831 
2835  public function fallback8bitEncoding() {
2836  return $this->localisationCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2837  }
2838 
2847  public function hasWordBreaks() {
2848  return true;
2849  }
2850 
2858  public function segmentByWord( $string ) {
2859  return $string;
2860  }
2861 
2869  public function normalizeForSearch( $string ) {
2870  return self::convertDoubleWidth( $string );
2871  }
2872 
2881  protected static function convertDoubleWidth( $string ) {
2882  static $full = null;
2883  static $half = null;
2884 
2885  if ( $full === null ) {
2886  $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2887  $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2888  $full = str_split( $fullWidth, 3 );
2889  $half = str_split( $halfWidth );
2890  }
2891 
2892  $string = str_replace( $full, $half, $string );
2893  return $string;
2894  }
2895 
2901  protected static function insertSpace( $string, $pattern ) {
2902  $string = preg_replace( $pattern, " $1 ", $string );
2903  $string = preg_replace( '/ +/', ' ', $string );
2904  return $string;
2905  }
2906 
2911  public function convertForSearchResult( $termsArray ) {
2912  # some languages, e.g. Chinese, need to do a conversion
2913  # in order for search results to be displayed correctly
2914  return $termsArray;
2915  }
2916 
2923  public function firstChar( $s ) {
2924  $firstChar = mb_substr( $s, 0, 1 );
2925 
2926  if ( $firstChar !== false ) {
2927  if ( strlen( $firstChar ) != 3 ) {
2928  return $firstChar;
2929  }
2930 
2931  // Break down Hangul syllables to grab the first jamo
2932  $code = mb_ord( $firstChar );
2933  if ( $code < 0xac00 || $code >= 0xd7a4 ) {
2934  return $firstChar;
2935  } elseif ( $code < 0xb098 ) {
2936  return "\u{3131}";
2937  } elseif ( $code < 0xb2e4 ) {
2938  return "\u{3134}";
2939  } elseif ( $code < 0xb77c ) {
2940  return "\u{3137}";
2941  } elseif ( $code < 0xb9c8 ) {
2942  return "\u{3139}";
2943  } elseif ( $code < 0xbc14 ) {
2944  return "\u{3141}";
2945  } elseif ( $code < 0xc0ac ) {
2946  return "\u{3142}";
2947  } elseif ( $code < 0xc544 ) {
2948  return "\u{3145}";
2949  } elseif ( $code < 0xc790 ) {
2950  return "\u{3147}";
2951  } elseif ( $code < 0xcc28 ) {
2952  return "\u{3148}";
2953  } elseif ( $code < 0xce74 ) {
2954  return "\u{314A}";
2955  } elseif ( $code < 0xd0c0 ) {
2956  return "\u{314B}";
2957  } elseif ( $code < 0xd30c ) {
2958  return "\u{314C}";
2959  } elseif ( $code < 0xd558 ) {
2960  return "\u{314D}";
2961  } else {
2962  return "\u{314E}";
2963  }
2964  }
2965 
2966  return '';
2967  }
2968 
2980  public function normalize( $s ) {
2981  global $wgAllUnicodeFixes, $IP;
2982 
2983  $s = UtfNormal\Validator::cleanUp( $s );
2984  if ( $wgAllUnicodeFixes ) {
2985  $s = $this->transformUsingPairFile( 'normalize-ar.php', $s, $IP );
2986  $s = $this->transformUsingPairFile( 'normalize-ml.php', $s, $IP );
2987  }
2988 
2989  return $s;
2990  }
2991 
3007  protected function transformUsingPairFile( $file, $string, $basePath = null ) {
3008  if ( isset( $this->transformData[$file] ) ) {
3009  wfDeprecated(
3010  'Modification of Language::$transformData is deprecated since MediaWiki 1.35',
3011  '1.35'
3012  );
3013  return $this->transformData[$file]->replace( $string );
3014  }
3015 
3016  if ( $basePath === null ) {
3017  wfDeprecated( __METHOD__ . ' without $basePath', '1.35' );
3018  global $IP;
3019  $basePath = $IP;
3020  }
3021 
3022  if (
3023  $basePath === null
3024  || $basePath === ''
3025  || !file_exists( "{$basePath}/languages/data/{$file}" )
3026  ) {
3027  return $string;
3028  }
3029 
3030  if ( !isset( $this->transformData[$basePath][$file] ) ) {
3031  $data = require "{$basePath}/languages/data/{$file}";
3032  $this->transformData[$basePath][$file] = new ReplacementArray( $data );
3033  }
3034 
3035  return $this->transformData[$basePath][$file]->replace( $string );
3036  }
3037 
3043  public function isRTL() {
3044  return $this->localisationCache->getItem( $this->mCode, 'rtl' );
3045  }
3046 
3051  public function getDir() {
3052  return $this->isRTL() ? 'rtl' : 'ltr';
3053  }
3054 
3063  public function alignStart() {
3064  return $this->isRTL() ? 'right' : 'left';
3065  }
3066 
3075  public function alignEnd() {
3076  return $this->isRTL() ? 'left' : 'right';
3077  }
3078 
3090  public function getDirMarkEntity( $opposite = false ) {
3091  if ( $opposite ) {
3092  return $this->isRTL() ? '&lrm;' : '&rlm;';
3093  }
3094  return $this->isRTL() ? '&rlm;' : '&lrm;';
3095  }
3096 
3107  public function getDirMark( $opposite = false ) {
3108  $lrm = "\u{200E}"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3109  $rlm = "\u{200F}"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3110  if ( $opposite ) {
3111  return $this->isRTL() ? $lrm : $rlm;
3112  }
3113  return $this->isRTL() ? $rlm : $lrm;
3114  }
3115 
3123  public function getArrow( $direction = 'forwards' ) {
3124  switch ( $direction ) {
3125  case 'forwards':
3126  return $this->isRTL() ? '←' : '→';
3127  case 'backwards':
3128  return $this->isRTL() ? '→' : '←';
3129  case 'left':
3130  return '←';
3131  case 'right':
3132  return '→';
3133  case 'up':
3134  return '↑';
3135  case 'down':
3136  return '↓';
3137  }
3138  }
3139 
3145  public function linkPrefixExtension() {
3146  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixExtension' );
3147  }
3148 
3153  public function getMagicWords() {
3154  return $this->localisationCache->getItem( $this->mCode, 'magicWords' );
3155  }
3156 
3162  public function getMagic( $mw ) {
3163  $rawEntry = $this->mMagicExtensions[$mw->mId] ??
3164  $this->localisationCache->getSubitem( $this->mCode, 'magicWords', $mw->mId );
3165 
3166  if ( !is_array( $rawEntry ) ) {
3167  wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3168  } else {
3169  $mw->mCaseSensitive = $rawEntry[0];
3170  $mw->mSynonyms = array_slice( $rawEntry, 1 );
3171  }
3172  }
3173 
3179  public function getSpecialPageAliases() {
3180  // Cache aliases because it may be slow to load them
3181  if ( $this->mExtendedSpecialPageAliases === null ) {
3182  // Initialise array
3183  $this->mExtendedSpecialPageAliases =
3184  $this->localisationCache->getItem( $this->mCode, 'specialPageAliases' );
3185  }
3186 
3187  return $this->mExtendedSpecialPageAliases;
3188  }
3189 
3196  public function emphasize( $text ) {
3197  return "<em>$text</em>";
3198  }
3199 
3222  public function formatNum( $number, $noSeparators = null ) {
3223  if ( $noSeparators !== null ) {
3224  wfDeprecated( __METHOD__ . ' with $noSeparators parameter', '1.36' );
3225  } else {
3226  // The legacy default value.
3227  $noSeparators = false;
3228  }
3229  return $this->formatNumInternal( (string)$number, false, $noSeparators );
3230  }
3231 
3241  private function formatNumInternal(
3242  string $number, bool $noTranslate, bool $noSeparators
3243  ): string {
3244  global $wgTranslateNumerals;
3245 
3246  if ( $number === '' ) {
3247  return $number;
3248  }
3249  if ( $number === (string)NAN ) {
3250  return $this->msg( 'formatnum-nan' )->text();
3251  }
3252  if ( $number === (string)INF ) {
3253  return "∞";
3254  }
3255  if ( $number === (string)-INF ) {
3256  return "\u{2212}∞";
3257  }
3258  if ( !is_numeric( $number ) ) {
3259  # T267587: downgrade this to level:warn while we chase down the long
3260  # trail of callers.
3261  # wfDeprecated( 'Language::formatNum with a non-numeric string', '1.36' );
3262  LoggerFactory::getInstance( 'formatnum' )->warning(
3263  'Language::formatNum with non-numeric string',
3264  [ 'number' => $number ]
3265  );
3266  $validNumberRe = '(-(?=[\d\.]))?(\d+|(?=\.\d))(\.\d*)?([Ee][-+]?\d+)?';
3267  // For backwards-compat, apply formatNum piecewise on the valid
3268  // numbers in the string. Don't split on NAN/INF in this legacy
3269  // case as they are likely to be found embedded inside non-numeric
3270  // text.
3271  return preg_replace_callback( "/{$validNumberRe}/", function ( $m ) use ( $noTranslate, $noSeparators ) {
3272  return $this->formatNumInternal( $m[0], $noTranslate, $noSeparators );
3273  }, $number );
3274  }
3275 
3276  if ( !$noSeparators ) {
3277  $separatorTransformTable = $this->separatorTransformTable();
3278  $digitGroupingPattern = $this->digitGroupingPattern();
3279  $code = $this->getCode();
3280  if ( !( $wgTranslateNumerals && $this->langNameUtils->isValidCode( $code ) ) ) {
3281  $code = 'C'; // POSIX system default locale
3282  }
3283 
3284  if ( $digitGroupingPattern ) {
3285  $fmt = new NumberFormatter(
3286  $code, NumberFormatter::PATTERN_DECIMAL, $digitGroupingPattern
3287  );
3288  } else {
3290  $fmt = new NumberFormatter( $code, NumberFormatter::DECIMAL );
3291  }
3292 
3293  // minimumGroupingDigits can be used to suppress groupings below a certain value.
3294  // This is used for languages such as Polish, where one would only write the grouping
3295  // separator for values above 9999 - numbers with more than 4 digits.
3296  // NumberFormatter is yet to support minimumGroupingDigits, ICU has it as experimental feature.
3297  // The attribute value is used by adding it to the grouping separator value. If
3298  // the input number has fewer integer digits, the grouping separator is suppressed.
3299  $minimumGroupingDigits = $this->minimumGroupingDigits() ?? 0;
3300  // Minimum length of a number to do digit grouping on.
3301  // http://unicode.org/reports/tr35/tr35-numbers.html#Examples_of_minimumGroupingDigits
3302  $minimumLength = $minimumGroupingDigits + $fmt->getAttribute( NumberFormatter::GROUPING_SIZE );
3303  if ( $minimumGroupingDigits && !preg_match( '/^\-?\d{' . $minimumLength . '}/', $number ) ) {
3304  // Even if number does not need commafy, do decimal
3305  // separator transformation. For example 1234.56 becomes
3306  // 1234,56 in pl with $minimumGroupingDigits = 2
3307  if ( !$noTranslate ) {
3308  $number = strtr( $number, $separatorTransformTable ?: [] );
3309  }
3310  } elseif ( $number === '-0' ) {
3311  // Special case to ensure we don't lose the minus sign by
3312  // converting to an int.
3313  if ( !$noTranslate ) {
3314  $number = strtr( $number, $separatorTransformTable ?: [] );
3315  }
3316  } else {
3317  // NumberFormatter supports separator transformation,
3318  // but it does not know all languages MW
3319  // supports. Example: arq. Also, languages like pl has
3320  // customisation. So manually set it.
3321  if ( $noTranslate ) {
3322  $fmt->setSymbol(
3323  NumberFormatter::DECIMAL_SEPARATOR_SYMBOL,
3324  '.'
3325  );
3326  $fmt->setSymbol(
3327  NumberFormatter::GROUPING_SEPARATOR_SYMBOL,
3328  ','
3329  );
3330  } elseif ( $separatorTransformTable ) {
3331  $fmt->setSymbol(
3332  NumberFormatter::DECIMAL_SEPARATOR_SYMBOL,
3333  $separatorTransformTable[ '.' ] ?? '.'
3334  );
3335  $fmt->setSymbol(
3336  NumberFormatter::GROUPING_SEPARATOR_SYMBOL,
3337  $separatorTransformTable[ ',' ] ?? ','
3338  );
3339  }
3340 
3341  // Maintain # of digits before and after the decimal point
3342  // (and presence of decimal point)
3343  if ( preg_match( '/^-?(\d*)(\.(\d*))?$/', $number, $m ) ) {
3344  $fmt->setAttribute( NumberFormatter::MIN_INTEGER_DIGITS, strlen( $m[1] ) );
3345  if ( isset( $m[2] ) ) {
3346  $fmt->setAttribute( NumberFormatter::DECIMAL_ALWAYS_SHOWN, true );
3347  }
3348  $fmt->setAttribute( NumberFormatter::FRACTION_DIGITS, strlen( $m[3] ?? '' ) );
3349  }
3350  $number = $fmt->format( $number );
3351  }
3352  }
3353 
3354  if ( !$noTranslate ) {
3355  if ( $wgTranslateNumerals ) {
3356  // This is often unnecessary: PHP's NumberFormatter will often
3357  // do the digit transform itself (T267614)
3358  $s = $this->digitTransformTable();
3359  if ( $s ) {
3360  $number = strtr( $number, $s );
3361  }
3362  }
3363  # T10327: Make our formatted numbers prettier by using a
3364  # proper Unicode 'minus' character.
3365  $number = strtr( $number, [ '-' => "\u{2212}" ] );
3366  }
3367 
3368  // Remove any LRM or RLM characters generated from NumberFormatter,
3369  // since directionality is handled outside of this context.
3370  // Similarly remove \u61C, the "Arabic Letter mark" (unicode 6.3.0)
3371  // https://en.wikipedia.org/wiki/Arabic_letter_mark
3372  // which is added starting PHP 7.3+
3373  $number = strtr( $number, [
3374  "\u{200E}" => '', // LRM
3375  "\u{200F}" => '', // RLM
3376  "\u{061C}" => '', // ALM
3377  ] );
3378 
3379  return $number;
3380  }
3381 
3390  public function formatNumNoSeparators( $number ) {
3391  return $this->formatNumInternal( (string)$number, false, true );
3392  }
3393 
3398  public function parseFormattedNumber( $number ) {
3399  if ( $number === $this->msg( 'formatnum-nan' )->text() ) {
3400  return (string)NAN;
3401  }
3402  if ( $number === "∞" ) {
3403  return (string)INF;
3404  }
3405  // Accept either ASCII hyphen-minus or the unicode minus emitted by
3406  // ::formatNum()
3407  $number = strtr( $number, [ "\u{2212}" => '-' ] );
3408  if ( $number === "-∞" ) {
3409  return (string)-INF;
3410  }
3411  $s = $this->digitTransformTable();
3412  if ( $s ) {
3413  // eliminate empty array values such as ''. (T66347)
3414  $s = array_filter( $s );
3415  $number = strtr( $number, array_flip( $s ) );
3416  }
3417 
3418  $s = $this->separatorTransformTable();
3419  if ( $s ) {
3420  // eliminate empty array values such as ''. (T66347)
3421  $s = array_filter( $s );
3422  $number = strtr( $number, array_flip( $s ) );
3423  }
3424 
3425  $number = strtr( $number, [ ',' => '' ] );
3426  return $number;
3427  }
3428 
3441  public function commafy( $number ) {
3442  wfDeprecated( __METHOD__, '1.36' );
3443  // Validate the input argument.
3444  if ( $number === null || $number === '' ) {
3445  return '';
3446  }
3447  return $this->formatNumInternal( $number, true, false );
3448  }
3449 
3453  public function digitGroupingPattern() {
3454  return $this->localisationCache->getItem( $this->mCode, 'digitGroupingPattern' );
3455  }
3456 
3460  public function digitTransformTable() {
3461  return $this->localisationCache->getItem( $this->mCode, 'digitTransformTable' );
3462  }
3463 
3467  public function separatorTransformTable() {
3468  return $this->localisationCache->getItem( $this->mCode, 'separatorTransformTable' );
3469  }
3470 
3474  public function minimumGroupingDigits() {
3475  return $this->localisationCache->getItem( $this->mCode, 'minimumGroupingDigits' );
3476  }
3477 
3486  public function listToText( array $list ) {
3487  $itemCount = count( $list );
3488  if ( $itemCount < 1 ) {
3489  return '';
3490  }
3491  $text = array_pop( $list );
3492  if ( $itemCount > 1 ) {
3493  $and = $this->msg( 'and' )->escaped();
3494  $space = $this->msg( 'word-separator' )->escaped();
3495  $comma = '';
3496  if ( $itemCount > 2 ) {
3497  $comma = $this->msg( 'comma-separator' )->escaped();
3498  }
3499  $text = implode( $comma, $list ) . $and . $space . $text;
3500  }
3501  return $text;
3502  }
3503 
3510  public function commaList( array $list ) {
3511  return implode(
3512  wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3513  $list
3514  );
3515  }
3516 
3523  public function semicolonList( array $list ) {
3524  return implode(
3525  wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3526  $list
3527  );
3528  }
3529 
3535  public function pipeList( array $list ) {
3536  return implode(
3537  wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3538  $list
3539  );
3540  }
3541 
3557  public function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3558  return $this->truncateInternal(
3559  $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
3560  );
3561  }
3562 
3581  public function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3582  // Passing encoding to mb_strlen and mb_substr is optional.
3583  // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
3584  // explicit specification of encoding is skipped.
3585  // Note: Both multibyte methods are callables invoked in truncateInternal.
3586  return $this->truncateInternal(
3587  $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
3588  );
3589  }
3590 
3607  private function truncateInternal(
3608  $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring
3609  ) {
3610  # Check if there is no need to truncate
3611  if ( $measureLength( $string ) <= abs( $length ) ) {
3612  return $string; // no need to truncate
3613  }
3614 
3615  # Use the localized ellipsis character
3616  if ( $ellipsis == '...' ) {
3617  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3618  }
3619  if ( $length == 0 ) {
3620  return $ellipsis; // convention
3621  }
3622 
3623  $stringOriginal = $string;
3624  # If ellipsis length is >= $length then we can't apply $adjustLength
3625  if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
3626  $string = $ellipsis; // this can be slightly unexpected
3627  # Otherwise, truncate and add ellipsis...
3628  } else {
3629  $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
3630  if ( $length > 0 ) {
3631  $length -= $ellipsisLength;
3632  $string = $getSubstring( $string, 0, $length ); // xyz...
3633  $string = $this->removeBadCharLast( $string );
3634  $string = rtrim( $string ) . $ellipsis;
3635  } else {
3636  $length += $ellipsisLength;
3637  $string = $getSubstring( $string, $length ); // ...xyz
3638  $string = $this->removeBadCharFirst( $string );
3639  $string = $ellipsis . ltrim( $string );
3640  }
3641  }
3642 
3643  # Do not truncate if the ellipsis makes the string longer/equal (T24181).
3644  # This check is *not* redundant if $adjustLength, due to the single case where
3645  # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3646  if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
3647  return $string;
3648  } else {
3649  return $stringOriginal;
3650  }
3651  }
3652 
3660  protected function removeBadCharLast( $string ) {
3661  if ( $string != '' ) {
3662  $char = ord( $string[strlen( $string ) - 1] );
3663  $m = [];
3664  if ( $char >= 0xc0 ) {
3665  # We got the first byte only of a multibyte char; remove it.
3666  $string = substr( $string, 0, -1 );
3667  } elseif ( $char >= 0x80 &&
3668  // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3669  preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3670  '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3671  ) {
3672  # We chopped in the middle of a character; remove it
3673  $string = $m[1];
3674  }
3675  }
3676  return $string;
3677  }
3678 
3686  protected function removeBadCharFirst( $string ) {
3687  if ( $string != '' ) {
3688  $char = ord( $string[0] );
3689  if ( $char >= 0x80 && $char < 0xc0 ) {
3690  # We chopped in the middle of a character; remove the whole thing
3691  $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3692  }
3693  }
3694  return $string;
3695  }
3696 
3712  public function truncateHtml( $text, $length, $ellipsis = '...' ) {
3713  # Use the localized ellipsis character
3714  if ( $ellipsis == '...' ) {
3715  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3716  }
3717  # Check if there is clearly no need to truncate
3718  if ( $length <= 0 ) {
3719  return $ellipsis; // no text shown, nothing to format (convention)
3720  } elseif ( strlen( $text ) <= $length ) {
3721  return $text; // string short enough even *with* HTML (short-circuit)
3722  }
3723 
3724  $dispLen = 0; // innerHTML legth so far
3725  $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3726  $tagType = 0; // 0-open, 1-close
3727  $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3728  $entityState = 0; // 0-not entity, 1-entity
3729  $tag = $ret = ''; // accumulated tag name, accumulated result string
3730  $openTags = []; // open tag stack
3731  $maybeState = null; // possible truncation state
3732 
3733  $textLen = strlen( $text );
3734  $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3735  for ( $pos = 0; true; ++$pos ) {
3736  # Consider truncation once the display length has reached the maximim.
3737  # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3738  # Check that we're not in the middle of a bracket/entity...
3739  if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3740  if ( !$testingEllipsis ) {
3741  $testingEllipsis = true;
3742  # Save where we are; we will truncate here unless there turn out to
3743  # be so few remaining characters that truncation is not necessary.
3744  if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3745  $maybeState = [ $ret, $openTags ]; // save state
3746  }
3747  } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3748  # String in fact does need truncation, the truncation point was OK.
3749  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
3750  list( $ret, $openTags ) = $maybeState; // reload state
3751  $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3752  $ret .= $ellipsis; // add ellipsis
3753  break;
3754  }
3755  }
3756  if ( $pos >= $textLen ) {
3757  break; // extra iteration just for above checks
3758  }
3759 
3760  # Read the next char...
3761  $ch = $text[$pos];
3762  $lastCh = $pos ? $text[$pos - 1] : '';
3763  $ret .= $ch; // add to result string
3764  if ( $ch == '<' ) {
3765  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3766  $entityState = 0; // for bad HTML
3767  $bracketState = 1; // tag started (checking for backslash)
3768  } elseif ( $ch == '>' ) {
3769  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3770  $entityState = 0; // for bad HTML
3771  $bracketState = 0; // out of brackets
3772  } elseif ( $bracketState == 1 ) {
3773  if ( $ch == '/' ) {
3774  $tagType = 1; // close tag (e.g. "</span>")
3775  } else {
3776  $tagType = 0; // open tag (e.g. "<span>")
3777  $tag .= $ch;
3778  }
3779  $bracketState = 2; // building tag name
3780  } elseif ( $bracketState == 2 ) {
3781  if ( $ch != ' ' ) {
3782  $tag .= $ch;
3783  } else {
3784  // Name found (e.g. "<a href=..."), add on tag attributes...
3785  $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3786  }
3787  } elseif ( $bracketState == 0 ) {
3788  if ( $entityState ) {
3789  if ( $ch == ';' ) {
3790  $entityState = 0;
3791  $dispLen++; // entity is one displayed char
3792  }
3793  } else {
3794  if ( $neLength == 0 && !$maybeState ) {
3795  // Save state without $ch. We want to *hit* the first
3796  // display char (to get tags) but not *use* it if truncating.
3797  $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3798  }
3799  if ( $ch == '&' ) {
3800  $entityState = 1; // entity found, (e.g. "&#160;")
3801  } else {
3802  $dispLen++; // this char is displayed
3803  // Add the next $max display text chars after this in one swoop...
3804  $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3805  $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3806  $dispLen += $skipped;
3807  $pos += $skipped;
3808  }
3809  }
3810  }
3811  }
3812  // Close the last tag if left unclosed by bad HTML
3813  $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3814  while ( count( $openTags ) > 0 ) {
3815  $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3816  }
3817  return $ret;
3818  }
3819 
3831  private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3832  if ( $len === null ) {
3833  $len = -1; // -1 means "no limit" for strcspn
3834  } elseif ( $len < 0 ) {
3835  $len = 0; // sanity
3836  }
3837  $skipCount = 0;
3838  if ( $start < strlen( $text ) ) {
3839  $skipCount = strcspn( $text, $search, $start, $len );
3840  $ret .= substr( $text, $start, $skipCount );
3841  }
3842  return $skipCount;
3843  }
3844 
3854  private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3855  $tag = ltrim( $tag );
3856  if ( $tag != '' ) {
3857  if ( $tagType == 0 && $lastCh != '/' ) {
3858  $openTags[] = $tag; // tag opened (didn't close itself)
3859  } elseif ( $tagType == 1 ) {
3860  if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3861  array_pop( $openTags ); // tag closed
3862  }
3863  }
3864  $tag = '';
3865  }
3866  }
3867 
3876  public function convertGrammar( $word, $case ) {
3877  global $wgGrammarForms;
3878  if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3879  return $wgGrammarForms[$this->getCode()][$case][$word];
3880  }
3881 
3882  $grammarTransformations = $this->getGrammarTransformations();
3883 
3884  if ( isset( $grammarTransformations[$case] ) ) {
3885  $forms = $grammarTransformations[$case];
3886 
3887  // Some names of grammar rules are aliases for other rules.
3888  // In such cases the value is a string rather than object,
3889  // so load the actual rules.
3890  if ( is_string( $forms ) ) {
3891  $forms = $grammarTransformations[$forms];
3892  }
3893 
3894  foreach ( array_values( $forms ) as $rule ) {
3895  $form = $rule[0];
3896 
3897  if ( $form === '@metadata' ) {
3898  continue;
3899  }
3900 
3901  $replacement = $rule[1];
3902 
3903  $regex = '/' . addcslashes( $form, '/' ) . '/u';
3904  $patternMatches = preg_match( $regex, $word );
3905 
3906  if ( $patternMatches === false ) {
3907  wfLogWarning(
3908  'An error occurred while processing grammar. ' .
3909  "Word: '$word'. Regex: /$form/."
3910  );
3911  } elseif ( $patternMatches === 1 ) {
3912  $word = preg_replace( $regex, $replacement, $word );
3913 
3914  break;
3915  }
3916  }
3917  }
3918 
3919  return $word;
3920  }
3921 
3927  public function getGrammarForms() {
3928  global $wgGrammarForms;
3929  if ( isset( $wgGrammarForms[$this->getCode()] )
3930  && is_array( $wgGrammarForms[$this->getCode()] )
3931  ) {
3932  return $wgGrammarForms[$this->getCode()];
3933  }
3934 
3935  return [];
3936  }
3937 
3947  public function getGrammarTransformations() {
3948  if ( $this->grammarTransformCache !== null ) {
3949  return $this->grammarTransformCache;
3950  }
3951 
3952  $grammarDataFile = __DIR__ . "/data/grammarTransformations/{$this->getCode()}.json";
3953 
3954  $this->grammarTransformCache = is_readable( $grammarDataFile )
3955  ? FormatJson::decode( file_get_contents( $grammarDataFile ), true )
3956  : [];
3957 
3958  if ( $this->grammarTransformCache === null ) {
3959  throw new MWException( "Invalid grammar data for \"{$this->getCode()}\"." );
3960  }
3961 
3962  return $this->grammarTransformCache;
3963  }
3964 
3984  public function gender( $gender, $forms ) {
3985  if ( !count( $forms ) ) {
3986  return '';
3987  }
3988  $forms = $this->preConvertPlural( $forms, 2 );
3989  if ( $gender === 'male' ) {
3990  return $forms[0];
3991  }
3992  if ( $gender === 'female' ) {
3993  return $forms[1];
3994  }
3995  return $forms[2] ?? $forms[0];
3996  }
3997 
4013  public function convertPlural( $count, $forms ) {
4014  // Handle explicit n=pluralform cases
4015  $forms = $this->handleExplicitPluralForms( $count, $forms );
4016  if ( is_string( $forms ) ) {
4017  return $forms;
4018  }
4019  if ( !count( $forms ) ) {
4020  return '';
4021  }
4022 
4023  $pluralForm = $this->getPluralRuleIndexNumber( $count );
4024  $pluralForm = min( $pluralForm, count( $forms ) - 1 );
4025  return $forms[$pluralForm];
4026  }
4027 
4043  protected function handleExplicitPluralForms( $count, array $forms ) {
4044  foreach ( $forms as $index => $form ) {
4045  if ( preg_match( '/\d+=/i', $form ) ) {
4046  $pos = strpos( $form, '=' );
4047  if ( substr( $form, 0, $pos ) === (string)$count ) {
4048  return substr( $form, $pos + 1 );
4049  }
4050  unset( $forms[$index] );
4051  }
4052  }
4053  return array_values( $forms );
4054  }
4055 
4064  protected function preConvertPlural( /* Array */ $forms, $count ) {
4065  return array_pad( $forms, $count, end( $forms ) );
4066  }
4067 
4084  public function embedBidi( $text = '' ) {
4085  $dir = self::strongDirFromContent( $text );
4086  if ( $dir === 'ltr' ) {
4087  // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
4088  return self::LRE . $text . self::PDF;
4089  }
4090  if ( $dir === 'rtl' ) {
4091  // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
4092  return self::RLE . $text . self::PDF;
4093  }
4094  // No strong directionality: do not wrap
4095  return $text;
4096  }
4097 
4111  public function translateBlockExpiry( $str, UserIdentity $user = null, $now = 0 ) {
4112  $duration = SpecialBlock::getSuggestedDurations( $this );
4113  foreach ( $duration as $show => $value ) {
4114  if ( strcmp( $str, $value ) == 0 ) {
4115  return trim( $show );
4116  }
4117  }
4118 
4119  if ( wfIsInfinity( $str ) ) {
4120  foreach ( $duration as $show => $value ) {
4121  if ( wfIsInfinity( $value ) ) {
4122  return trim( $show );
4123  }
4124  }
4125  }
4126 
4127  // If all else fails, return a standard duration or timestamp description.
4128  $time = strtotime( $str, $now );
4129  if ( $time === false ) { // Unknown format. Return it as-is in case.
4130  return $str;
4131  } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
4132  // The result differs based on current time, so the difference
4133  // is a fixed duration length.
4134  return $this->formatDuration( $time - $now );
4135  } else { // It's an absolute timestamp.
4136  if ( $time === 0 ) {
4137  // wfTimestamp() handles 0 as current time instead of epoch.
4138  $time = '19700101000000';
4139  }
4140  if ( $user ) {
4141  return $this->userTimeAndDate( $time, $user );
4142  }
4143  return $this->timeanddate( $time );
4144  }
4145  }
4146 
4154  public function segmentForDiff( $text ) {
4155  return $text;
4156  }
4157 
4164  public function unsegmentForDiff( $text ) {
4165  return $text;
4166  }
4167 
4177  public function getConverter(): ILanguageConverter {
4178  return $this->converterFactory->getLanguageConverter( $this );
4179  }
4180 
4191  public function autoConvert( $text, $variant = false ) {
4192  return $this->getConverter()->autoConvert( $text, $variant );
4193  }
4194 
4203  public function autoConvertToAllVariants( $text ) {
4204  return $this->getConverter()->autoConvertToAllVariants( $text );
4205  }
4206 
4221  public function convert( $text ) {
4222  return $this->getConverter()->convert( $text );
4223  }
4224 
4235  public function convertNamespace( $ns, $variant = null ) {
4236  return $this->getConverter()->convertNamespace( $ns, $variant );
4237  }
4238 
4246  public function hasVariants() {
4247  return count( $this->getVariants() ) > 1;
4248  }
4249 
4262  public function hasVariant( $variant ) {
4263  return $this->getConverter()->hasVariant( $variant );
4264  }
4265 
4275  public function convertHtml( $text ) {
4276  return htmlspecialchars( $this->convert( $text ) );
4277  }
4278 
4285  public function convertCategoryKey( $key ) {
4286  return $this->getConverter()->convertCategoryKey( $key );
4287  }
4288 
4297  public function getVariants() {
4298  return $this->getConverter()->getVariants();
4299  }
4300 
4305  public function getPreferredVariant() {
4306  return $this->getConverter()->getPreferredVariant();
4307  }
4308 
4313  public function getDefaultVariant() {
4314  return $this->getConverter()->getDefaultVariant();
4315  }
4316 
4321  public function getURLVariant() {
4322  return $this->getConverter()->getURLVariant();
4323  }
4324 
4333  public function getExtraHashOptions() {
4334  return $this->getConverter()->getExtraHashOptions();
4335  }
4336 
4343  public function linkTrail() {
4344  return $this->localisationCache->getItem( $this->mCode, 'linkTrail' );
4345  }
4346 
4353  public function linkPrefixCharset() {
4354  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixCharset' );
4355  }
4356 
4365  public function getParentLanguage() {
4366  return MediaWikiServices::getInstance()->getLanguageFactory()
4367  ->getParentLanguage( $this->getCode() );
4368  }
4369 
4377  public function equals( Language $lang ) {
4378  return $lang === $this || $lang->getCode() === $this->mCode;
4379  }
4380 
4389  public function getCode() {
4390  return $this->mCode;
4391  }
4392 
4403  public function getHtmlCode() {
4404  if ( $this->mHtmlCode === null ) {
4405  $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
4406  }
4407  return $this->mHtmlCode;
4408  }
4409 
4417  public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4418  $m = null;
4419  preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4420  preg_quote( $suffix, '/' ) . '/', $filename, $m );
4421  if ( !count( $m ) ) {
4422  return false;
4423  }
4424  return str_replace( '_', '-', strtolower( $m[1] ) );
4425  }
4426 
4437  public static function getFileName( $prefix, $code, $suffix = '.php' ) {
4438  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4439  ->getFileName( $prefix, $code, $suffix );
4440  }
4441 
4447  public static function getMessagesFileName( $code ) {
4448  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4449  ->getMessagesFileName( $code );
4450  }
4451 
4459  public static function getJsonMessagesFileName( $code ) {
4460  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4461  ->getJsonMessagesFileName( $code );
4462  }
4463 
4472  public static function getFallbackFor( $code ) {
4473  return MediaWikiServices::getInstance()->getLanguageFallback()->getFirst( $code )
4474  ?? false;
4475  }
4476 
4489  public static function getFallbacksFor( $code, $mode = LanguageFallback::MESSAGES ) {
4490  return MediaWikiServices::getInstance()->getLanguageFallback()->getAll( $code, $mode );
4491  }
4492 
4503  public static function getFallbacksIncludingSiteLanguage( $code ) {
4504  return MediaWikiServices::getInstance()->getLanguageFallback()
4505  ->getAllIncludingSiteLanguage( $code );
4506  }
4507 
4519  public static function getMessagesFor( $code ) {
4520  return self::getLocalisationCache()->getItem( $code, 'messages' );
4521  }
4522 
4533  public static function getMessageFor( $key, $code ) {
4534  return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4535  }
4536 
4547  public static function getMessageKeysFor( $code ) {
4548  return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
4549  }
4550 
4555  private function fixVariableInNamespace( $talk ) {
4556  if ( strpos( $talk, '$1' ) === false ) {
4557  return $talk;
4558  }
4559 
4560  global $wgMetaNamespace;
4561  $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4562 
4563  # Allow grammar transformations
4564  # Allowing full message-style parsing would make simple requests
4565  # such as action=raw much more expensive than they need to be.
4566  # This will hopefully cover most cases.
4567  $talk = preg_replace_callback(
4568  '/{{grammar:(.*?)\|(.*?)}}/i',
4569  function ( $m ) {
4570  return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4571  },
4572  $talk
4573  );
4574  return str_replace( ' ', '_', $talk );
4575  }
4576 
4589  public function formatExpiry( $expiry, $format = true, $infinity = 'infinity', $user = null ) {
4590  static $dbInfinity;
4591  if ( $dbInfinity === null ) {
4592  $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
4593  }
4594 
4595  if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4596  return $format === true
4597  ? $this->getMessageFromDB( 'infiniteblock' )
4598  : $infinity;
4599  } else {
4600  if ( $format === true ) {
4601  return $user
4602  ? $this->userTimeAndDate( $expiry, $user )
4603  : $this->timeanddate( $expiry, /* User preference timezone */ true );
4604  }
4605  return wfTimestamp( $format, $expiry );
4606  }
4607  }
4608 
4623  public function formatTimePeriod( $seconds, $format = [] ) {
4624  if ( !is_array( $format ) ) {
4625  $format = [ 'avoid' => $format ]; // For backwards compatibility
4626  }
4627  if ( !isset( $format['avoid'] ) ) {
4628  $format['avoid'] = false;
4629  }
4630  if ( !isset( $format['noabbrevs'] ) ) {
4631  $format['noabbrevs'] = false;
4632  }
4633  $secondsMsg = wfMessage(
4634  $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4635  $minutesMsg = wfMessage(
4636  $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4637  $hoursMsg = wfMessage(
4638  $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4639  $daysMsg = wfMessage(
4640  $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4641 
4642  if ( round( $seconds * 10 ) < 100 ) {
4643  $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4644  $s = $secondsMsg->params( $s )->text();
4645  } elseif ( round( $seconds ) < 60 ) {
4646  $s = $this->formatNum( round( $seconds ) );
4647  $s = $secondsMsg->params( $s )->text();
4648  } elseif ( round( $seconds ) < 3600 ) {
4649  $minutes = floor( $seconds / 60 );
4650  $secondsPart = round( fmod( $seconds, 60 ) );
4651  if ( $secondsPart == 60 ) {
4652  $secondsPart = 0;
4653  $minutes++;
4654  }
4655  $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4656  $s .= ' ';
4657  $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4658  } elseif ( round( $seconds ) <= 2 * 86400 ) {
4659  $hours = floor( $seconds / 3600 );
4660  $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4661  $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4662  if ( $secondsPart == 60 ) {
4663  $secondsPart = 0;
4664  $minutes++;
4665  }
4666  if ( $minutes == 60 ) {
4667  $minutes = 0;
4668  $hours++;
4669  }
4670  $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4671  $s .= ' ';
4672  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4673  if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes', 'avoidhours' ] ) ) {
4674  $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4675  }
4676  } else {
4677  $days = floor( $seconds / 86400 );
4678  if ( $format['avoid'] === 'avoidhours' ) {
4679  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4680  if ( $hours == 24 ) {
4681  $hours = 0;
4682  $days++;
4683  }
4684  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4685  } elseif ( $format['avoid'] === 'avoidminutes' ) {
4686  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4687  if ( $hours == 24 ) {
4688  $hours = 0;
4689  $days++;
4690  }
4691  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4692  $s .= ' ';
4693  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4694  } elseif ( $format['avoid'] === 'avoidseconds' ) {
4695  $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4696  $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4697  if ( $minutes == 60 ) {
4698  $minutes = 0;
4699  $hours++;
4700  }
4701  if ( $hours == 24 ) {
4702  $hours = 0;
4703  $days++;
4704  }
4705  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4706  $s .= ' ';
4707  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4708  $s .= ' ';
4709  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4710  } else {
4711  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4712  $s .= ' ';
4713  $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4714  }
4715  }
4716  return $s;
4717  }
4718 
4730  public function formatBitrate( $bps ) {
4731  return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4732  }
4733 
4740  public function formatComputingNumbers( $size, $boundary, $messageKey ) {
4741  if ( $size <= 0 ) {
4742  return str_replace( '$1', $this->formatNum( $size ),
4743  $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4744  );
4745  }
4746  $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'yotta' ];
4747  $index = 0;
4748 
4749  $maxIndex = count( $sizes ) - 1;
4750  while ( $size >= $boundary && $index < $maxIndex ) {
4751  $index++;
4752  $size /= $boundary;
4753  }
4754 
4755  // For small sizes no decimal places necessary
4756  $round = 0;
4757  if ( $index > 1 ) {
4758  // For MB and bigger two decimal places are smarter
4759  $round = 2;
4760  }
4761  $msg = str_replace( '$1', $sizes[$index], $messageKey );
4762 
4763  $size = round( $size, $round );
4764  $text = $this->getMessageFromDB( $msg );
4765  return str_replace( '$1', $this->formatNum( $size ), $text );
4766  }
4767 
4778  public function formatSize( $size ) {
4779  return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4780  }
4781 
4791  public function specialList( $page, $details, $oppositedm = true ) {
4792  if ( !$details ) {
4793  return $page;
4794  }
4795 
4796  $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4797  return $page .
4798  $dirmark .
4799  $this->msg( 'word-separator' )->escaped() .
4800  $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4801  }
4802 
4810  public function getConvRuleTitle() {
4811  return $this->getConverter()->getConvRuleTitle();
4812  }
4813 
4819  public function getCompiledPluralRules() {
4820  $pluralRules =
4821  $this->localisationCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4822  if ( !$pluralRules ) {
4823  $fallbacks = $this->getFallbackLanguages();
4824  foreach ( $fallbacks as $fallbackCode ) {
4825  $pluralRules = $this->localisationCache
4826  ->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4827  if ( $pluralRules ) {
4828  break;
4829  }
4830  }
4831  }
4832  return $pluralRules;
4833  }
4834 
4840  public function getPluralRules() {
4841  $pluralRules =
4842  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4843  if ( !$pluralRules ) {
4844  $fallbacks = $this->getFallbackLanguages();
4845  foreach ( $fallbacks as $fallbackCode ) {
4846  $pluralRules = $this->localisationCache
4847  ->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4848  if ( $pluralRules ) {
4849  break;
4850  }
4851  }
4852  }
4853  return $pluralRules;
4854  }
4855 
4861  public function getPluralRuleTypes() {
4862  $pluralRuleTypes =
4863  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4864  if ( !$pluralRuleTypes ) {
4865  $fallbacks = $this->getFallbackLanguages();
4866  foreach ( $fallbacks as $fallbackCode ) {
4867  $pluralRuleTypes = $this->localisationCache
4868  ->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4869  if ( $pluralRuleTypes ) {
4870  break;
4871  }
4872  }
4873  }
4874  return $pluralRuleTypes;
4875  }
4876 
4882  public function getPluralRuleIndexNumber( $number ) {
4883  $pluralRules = $this->getCompiledPluralRules();
4884  $form = Evaluator::evaluateCompiled( $number, $pluralRules );
4885  return $form;
4886  }
4887 
4896  public function getPluralRuleType( $number ) {
4897  $index = $this->getPluralRuleIndexNumber( $number );
4898  $pluralRuleTypes = $this->getPluralRuleTypes();
4899  return $pluralRuleTypes[$index] ?? 'other';
4900  }
4901 
4908  protected function getHookContainer() {
4909  return $this->hookContainer;
4910  }
4911 
4920  protected function getHookRunner() {
4921  return $this->hookRunner;
4922  }
4923 }
Language\$mCode
$mCode
Definition: Language.php:65
Language\$langFallback
LanguageFallback $langFallback
Definition: Language.php:104
Language\getCodeFromFileName
static getCodeFromFileName( $filename, $prefix='Language', $suffix='.php')
Get the language code from a file name.
Definition: Language.php:4417
Language\getExtraHashOptions
getExtraHashOptions()
returns language specific options used by User::getPageRenderHash() for example, the preferred langua...
Definition: Language.php:4333
Language\lc
lc( $str, $first=false)
Definition: Language.php:2722
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:38
Language\parseFormattedNumber
parseFormattedNumber( $number)
Definition: Language.php:3398
Language\getURLVariant
getURLVariant()
Definition: Language.php:4321
Language\getVariantname
getVariantname( $code, $usemsg=true)
short names for language variants used for language conversion links.
Definition: Language.php:800
Language\$hookContainer
HookContainer $hookContainer
Definition: Language.php:117
Language\getHookRunner
getHookRunner()
Get a HookRunner, for running core hooks.
Definition: Language.php:4920
Language\linkPrefixExtension
linkPrefixExtension()
To allow "foo[[bar]]" to extend the link over the whole word "foobar".
Definition: Language.php:3145
Language\$langNameUtils
LanguageNameUtils $langNameUtils
Definition: Language.php:101
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:3854
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:3510
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:3523
Language\$mIranianCalendarMonthMsgs
static $mIranianCalendarMonthMsgs
Definition: Language.php:217
Language\$mMonthAbbrevMsgs
static $mMonthAbbrevMsgs
Definition: Language.php:202
Language\formatSize
formatSize( $size)
Format a size in bytes for output, using an appropriate unit (B, KB, MB, GB, TB, PB,...
Definition: Language.php:4778
Language\separatorTransformTable
separatorTransformTable()
Definition: Language.php:3467
Language\WEEKDAY_ABBREVIATED_MESSAGES
const WEEKDAY_ABBREVIATED_MESSAGES
Definition: Language.php:154
Language\resetNamespaces
resetNamespaces()
Resets all of the namespace caches.
Definition: Language.php:590
Language\getConverter
getConverter()
Return the LanguageConverter used in the Language.
Definition: Language.php:4177
Language\hasVariants
hasVariants()
Check if this is a language with variants.
Definition: Language.php:4246
Language\$mWeekdayAbbrevMsgs
static $mWeekdayAbbrevMsgs
Definition: Language.php:161
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:186
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:4064
$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:4275
Language\minimumGroupingDigits
minimumGroupingDigits()
Definition: Language.php:3474
Language\segmentByWord
segmentByWord( $string)
Some languages such as Chinese require word segmentation, Specify such segmentation when overridden i...
Definition: Language.php:2858
Language\iconv
iconv( $in, $out, $string)
Definition: Language.php:2629
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:895
Language\convert
convert( $text)
convert text to different variants of a language.
Definition: Language.php:4221
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:3876
Language\mbUpperChar
mbUpperChar( $char)
Convert character to uppercase, allowing overrides of the default mb_upper behaviour,...
Definition: Language.php:2689
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=LanguageFallback::MESSAGES)
Get the ordered list of fallback languages.
Definition: Language.php:4489
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1692
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:3581
Language\$mMonthGenMsgs
static $mMonthGenMsgs
Definition: Language.php:189
Language\timeanddate
timeanddate( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2295
Language\$grammarTransformCache
array[] null $grammarTransformCache
Definition: Language.php:107
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1182
Language\MESSAGES_FALLBACKS
const MESSAGES_FALLBACKS
Return a fallback chain for messages in getFallbacksFor.
Definition: Language.php:129
Language\$mHijriCalendarMonthMsgs
static $mHijriCalendarMonthMsgs
Definition: Language.php:264
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:3241
Language\getPreferredVariant
getPreferredVariant()
Definition: Language.php:4305
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:2761
Language\getDefaultVariant
getDefaultVariant()
Definition: Language.php:4313
Language\fallback8bitEncoding
fallback8bitEncoding()
Definition: Language.php:2835
Language\embedBidi
embedBidi( $text='')
Wraps argument with unicode control characters for directionality safety.
Definition: Language.php:4084
Language\truncateInternal
truncateInternal( $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring)
Internal method used for truncation.
Definition: Language.php:3607
Language\formatTimePeriod
formatTimePeriod( $seconds, $format=[])
Formats a time given in seconds into a string representation of that time.
Definition: Language.php:4623
Language\formatBitrate
formatBitrate( $bps)
Format a bitrate for output, using an appropriate unit (bps, kbps, Mbps, Gbps, Tbps,...
Definition: Language.php:4730
Language\equals
equals(Language $lang)
Compare with an other language object.
Definition: Language.php:4377
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:3179
Language\__construct
__construct( $code=null, LocalisationCache $localisationCache=null, LanguageNameUtils $langNameUtils=null, LanguageFallback $langFallback=null, LanguageConverterFactory $converterFactory=null, HookContainer $hookContainer=null)
Definition: Language.php:461
Language\getMessagesFileName
static getMessagesFileName( $code)
Definition: Language.php:4447
Language\getPluralRuleTypes
getPluralRuleTypes()
Get the plural rule types for the language.
Definition: Language.php:4861
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:4791
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:249
$wgMetaNamespace
$wgMetaNamespace
Name of the project namespace.
Definition: DefaultSettings.php:4557
Language\checkTitleEncoding
checkTitleEncoding( $s)
TODO: $s is not always a string per T218883.
Definition: Language.php:2821
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:351
Language\getFormattedNamespaces
getFormattedNamespaces()
A convenience function that returns getNamespaces() with spaces instead of underscores in values.
Definition: Language.php:602
Language\lcfirst
lcfirst( $str)
Definition: Language.php:2699
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:438
Language\emphasize
emphasize( $text)
Italic is unsuitable for some languages.
Definition: Language.php:3196
Language\getFallbackLanguages
getFallbackLanguages()
Definition: Language.php:523
Language\getDurationIntervals
getDurationIntervals( $seconds, array $chosenIntervals=[])
Takes a number of seconds and returns an array with a set of corresponding intervals.
Definition: Language.php:2340
Language\caseFold
caseFold( $s)
Return a case-folded representation of $s.
Definition: Language.php:2812
Language\segmentForDiff
segmentForDiff( $text)
languages like Chinese need to be segmented in order for the diff to be of any use
Definition: Language.php:4154
Language\needsGenderDistinction
needsGenderDistinction()
Whether this language uses gender-dependent namespace aliases.
Definition: Language.php:667
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
Language\getLocalisationCache
static getLocalisationCache()
Definition: Language.php:447
MWException
MediaWiki exception.
Definition: MWException.php:29
Language\$transformData
$transformData
ReplacementArray object memoize.
Definition: Language.php:95
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:996
Language\tsToIranian
static tsToIranian( $ts)
Algorithm by Roozbeh Pournader and Mohammad Toossi to convert Gregorian dates to Iranian dates.
Definition: Language.php:1576
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:4164
Language\autoConvert
autoConvert( $text, $variant=false)
convert text to a variant
Definition: Language.php:4191
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:3712
Language\normalize
normalize( $s)
Convert a UTF-8 string to normal form C.
Definition: Language.php:2980
Language\getBookstoreList
getBookstoreList()
Exports $wgBookstoreListEn.
Definition: Language.php:531
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:2436
Language\$mHebrewCalendarMonthMsgs
static $mHebrewCalendarMonthMsgs
Definition: Language.php:233
Language\DURATION_INTERVALS
const DURATION_INTERVALS
Definition: Language.php:269
Language\pipeList
pipeList(array $list)
Same as commaList, but separate it with the pipe instead.
Definition: Language.php:3535
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2226
Language\convertForSearchResult
convertForSearchResult( $termsArray)
Definition: Language.php:2911
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4533
$matches
$matches
Definition: NoLocalSettings.php:24
Language\getGenderNsText
getGenderNsText( $index, $gender)
Returns gender-dependent namespace alias if available.
Definition: Language.php:652
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:2501
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:3486
Language\getHtmlCode
getHtmlCode()
Get the code in BCP 47 format which we can use inside of html lang="" tags.
Definition: Language.php:4403
Language\getNamespaceAliases
getNamespaceAliases()
Definition: Language.php:701
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:691
Language\$mMonthMsgs
static $mMonthMsgs
Definition: Language.php:175
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:3557
Language\getAllMessages
getAllMessages()
Definition: Language.php:2619
Language\getMagic
getMagic( $mw)
Fill a MagicWord object with data from here.
Definition: Language.php:3162
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:2459
$wgOverrideUcfirstCharacters
array $wgOverrideUcfirstCharacters
List of Unicode characters for which capitalization is overridden in Language::ucfirst.
Definition: DefaultSettings.php:3730
Language\isRTL
isRTL()
For right-to-left language support.
Definition: Language.php:3043
Language\getNsIndex
getNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:782
Language\MONTH_GENITIVE_MESSAGES
const MONTH_GENITIVE_MESSAGES
Definition: Language.php:180
Language\getNamespaceIds
getNamespaceIds()
Definition: Language.php:758
Language\getPluralRuleIndexNumber
getPluralRuleIndexNumber( $number)
Find the index number of the plural rule appropriate for the given number.
Definition: Language.php:4882
Language\HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
const HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
Definition: Language.php:238
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:2881
Language\getCompiledPluralRules
getCompiledPluralRules()
Get the compiled plural rules for the language.
Definition: Language.php:4819
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:2543
Language\convertCategoryKey
convertCategoryKey( $key)
Definition: Language.php:4285
Language\digitGroupingPattern
digitGroupingPattern()
Definition: Language.php:3453
Language\$hookRunner
HookRunner $hookRunner
Definition: Language.php:122
Language\ucwords
ucwords( $str)
Definition: Language.php:2742
Language\getPluralRules
getPluralRules()
Get the plural rules for the language.
Definition: Language.php:4840
Language\getArrow
getArrow( $direction='forwards')
An arrow, depending on the language direction.
Definition: Language.php:3123
Language\uc
uc( $str, $first=false)
Definition: Language.php:2668
Language\formatNumNoSeparators
formatNumNoSeparators( $number)
Front-end for non-commafied formatNum.
Definition: Language.php:3390
$wgTranslateNumerals
$wgTranslateNumerals
For Hindi and Arabic use local numerals instead of Western style (0-9) numerals in interface.
Definition: DefaultSettings.php:3572
Language\$mHtmlCode
$mHtmlCode
Definition: Language.php:72
Language\MONTH_ABBREVIATED_MESSAGES
const MONTH_ABBREVIATED_MESSAGES
Definition: Language.php:194
$digitGroupingPattern
$digitGroupingPattern
Definition: MessagesAr.php:473
$wgNamespaceAliases
$wgNamespaceAliases
Define extra namespace aliases.
Definition: DefaultSettings.php:4632
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:423
Language\$converterFactory
LanguageConverterFactory $converterFactory
Definition: Language.php:112
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:2314
Language\setNamespaces
setNamespaces(array $namespaces)
Arbitrarily set all of the namespace names at once.
Definition: Language.php:582
Language\linkPrefixCharset
linkPrefixCharset()
A regular expression character set to match legal word-prefixing characters which should be merged on...
Definition: Language.php:4353
ReplacementArray
Wrapper around strtr() that holds replacements.
Definition: ReplacementArray.php:24
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
Language\fixVariableInNamespace
fixVariableInNamespace( $talk)
Definition: Language.php:4555
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:29
Language\ucwordbreaks
ucwordbreaks( $str)
capitalize words at word breaks
Definition: Language.php:2768
Language\getNsText
getNsText( $index)
Get a namespace value by key.
Definition: Language.php:621
$wgLocalTZoffset
$wgLocalTZoffset
Set an offset from UTC in minutes to use for the default timezone setting for anonymous users and new...
Definition: DefaultSettings.php:3717
Language\getCode
getCode()
Get the internal language code for this language object.
Definition: Language.php:4389
Language\LRE
const LRE
Unicode directional formatting characters, for embedBidi()
Definition: Language.php:291
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:4896
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:2188
$wgMetaNamespaceTalk
$wgMetaNamespaceTalk
Name of the project talk namespace.
Definition: DefaultSettings.php:4566
Language\hebrewNumeral
static hebrewNumeral( $num)
Hebrew Gematria number formatting up to 9999.
Definition: Language.php:2018
Language\internalUserTimeAndDate
internalUserTimeAndDate( $type, $ts, UserIdentity $user, array $options)
Internal helper function for userDate(), userTime() and userTimeAndDate()
Definition: Language.php:2392
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2546
Language\getFormattedNsText
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with '_' changed to ' ',...
Definition: Language.php:639
Language\getMessagesFor
static getMessagesFor( $code)
Get all messages for a given language WARNING: this may take a long time.
Definition: Language.php:4519
Language\handleExplicitPluralForms
handleExplicitPluralForms( $count, array $forms)
Handles explicit plural forms for Language::convertPlural()
Definition: Language.php:4043
Language\RLE
const RLE
Definition: Language.php:292
Language\getFileName
static getFileName( $prefix, $code, $suffix='.php')
Get the name of a file for a certain language code.
Definition: Language.php:4437
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:166
Language\getHookContainer
getHookContainer()
Get a HookContainer, for hook metadata and running extension hooks.
Definition: Language.php:4908
Language\HEBREW_CALENDAR_MONTHS_MESSAGES
const HEBREW_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:222
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:3107
Language\normalizeForSearch
normalizeForSearch( $string)
Some languages have special punctuation need to be normalized.
Definition: Language.php:2869
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:408
Language\userAdjust
userAdjust( $ts, $tz=false)
Used by date() and time() to adjust the time output.
Definition: Language.php:2105
Language\formatComputingNumbers
formatComputingNumbers( $size, $boundary, $messageKey)
Definition: Language.php:4740
$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:2482
Language\getFallbackFor
static getFallbackFor( $code)
Get the first fallback for a given language.
Definition: Language.php:4472
Language\getParentLanguage
getParentLanguage()
Get the "parent" language which has a converter to convert a "compatible" language (in another varian...
Definition: Language.php:4365
Language\$dateFormatStrings
$dateFormatStrings
memoize
Definition: Language.php:78
Language\hasWordBreaks
hasWordBreaks()
Most writing systems use whitespace to break up words.
Definition: Language.php:2847
Language\getDir
getDir()
Return the correct HTML 'dir' attribute value for this language.
Definition: Language.php:3051
Language\date
date( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2256
Language\alignEnd
alignEnd()
Return 'right' or 'left' as appropriate alignment for line-end for this language's text direction.
Definition: Language.php:3075
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:3831
Language\getVariants
getVariants()
Get the list of variants supported by this language see sample implementation in LanguageZh....
Definition: Language.php:4297
Language\convertPlural
convertPlural( $count, $forms)
Plural form transformations, needed for some languages.
Definition: Language.php:4013
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:4503
$wgGrammarForms
$wgGrammarForms
Some languages need different word forms, usually for different cases.
Definition: DefaultSettings.php:3456
Language\transformUsingPairFile
transformUsingPairFile( $file, $string, $basePath=null)
Transform a string using serialized data stored in the given file (which must be in the serialized su...
Definition: Language.php:3007
Language\getGrammarForms
getGrammarForms()
Get the grammar forms for the content language.
Definition: Language.php:3927
Language\removeBadCharFirst
removeBadCharFirst( $string)
Remove bytes that represent an incomplete Unicode character at the start of string (e....
Definition: Language.php:3686
Language\$strongDirRegex
static $strongDirRegex
Directionality test regex for embedBidi().
Definition: Language.php:308
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:4609
Language\getMessage
getMessage( $key)
Definition: Language.php:2612
Language\getGrammarTransformations
getGrammarTransformations()
Get the grammar transformations data for the language.
Definition: Language.php:3947
Language\getMessageKeysFor
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4547
Language\getJsonMessagesFileName
static getJsonMessagesFileName( $code)
Definition: Language.php:4459
Language\IRANIAN_CALENDAR_MONTHS_MESSAGES
const IRANIAN_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:207
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:2923
Language\getNamespaces
getNamespaces()
Returns an array of localised namespaces indexed by their numbers.
Definition: Language.php:541
Language\$localisationCache
LocalisationCache $localisationCache
Definition: Language.php:98
SpecialBlock\getSuggestedDurations
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
Definition: SpecialBlock.php:941
Language\removeBadCharLast
removeBadCharLast( $string)
Remove bytes that represent an incomplete Unicode character at the end of string (e....
Definition: Language.php:3660
Language\romanNumeral
static romanNumeral( $num)
Roman number formatting up to 10000.
Definition: Language.php:1987
Language\getConvRuleTitle
getConvRuleTitle()
Get the conversion rule title, if any.
Definition: Language.php:4810
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:4589
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:318
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Language\translateBlockExpiry
translateBlockExpiry( $str, UserIdentity $user=null, $now=0)
Definition: Language.php:4111
Language\PDF
const PDF
Definition: Language.php:293
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:1636
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:555
$t
$t
Definition: testCompression.php:74
Language\time
time( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2275
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:3222
$minimumGroupingDigits
$minimumGroupingDigits
Definition: MessagesBg.php:223
Language\insertSpace
static insertSpace( $string, $pattern)
Definition: Language.php:2901
Language\isMultibyte
isMultibyte( $str)
Definition: Language.php:2734
Language\alignStart
alignStart()
Return 'left' or 'right' as appropriate alignment for line-start for this language's text direction.
Definition: Language.php:3063
Language\isSupportedLanguage
static isSupportedLanguage( $code)
Checks whether any localisation is available for that language tag in MediaWiki (MessagesXx....
Definition: Language.php:331
Language\$mWeekdayMsgs
static $mWeekdayMsgs
Definition: Language.php:149
NS_PROJECT_TALK
const NS_PROJECT_TALK
Definition: Defines.php:69
Language\digitTransformTable
digitTransformTable()
Definition: Language.php:3460
Language\tsToYear
static tsToYear( $ts, $cName)
Algorithm to convert Gregorian dates to Thai solar dates, Minguo dates or Minguo dates.
Definition: Language.php:1864
Language\getDirMarkEntity
getDirMarkEntity( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3090
Language\strongDirFromContent
static strongDirFromContent( $text='')
Gets directionality of the first strongly directional codepoint, for embedBidi()
Definition: Language.php:1970
Language\hebrewYearStart
static hebrewYearStart( $year)
This calculates the Hebrew year start, as days since 1 September.
Definition: Language.php:1826
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:2220
Language\getMagicWords
getMagicWords()
Get all magic words from cache.
Definition: Language.php:3153
Language\hasVariant
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: Language.php:4262
Language\__destruct
__destruct()
Reduce memory usage.
Definition: Language.php:513
Language\commafy
commafy( $number)
Adds commas to a given number.
Definition: Language.php:3441
Language\HIJRI_CALENDAR_MONTH_MESSAGES
const HIJRI_CALENDAR_MONTH_MESSAGES
Definition: Language.php:254
Language\STRICT_FALLBACKS
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:136
$wgExtraNamespaces
$wgExtraNamespaces
Additional namespaces.
Definition: DefaultSettings.php:4601
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:286
Language\tsToHebrew
static tsToHebrew( $ts)
Converting Gregorian dates to Hebrew dates.
Definition: Language.php:1688
Language\autoConvertToAllVariants
autoConvertToAllVariants( $text)
convert text to all supported variants
Definition: Language.php:4203
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:4343
$wgAllUnicodeFixes
$wgAllUnicodeFixes
Set this to always convert certain Unicode sequences to modern ones regardless of the content languag...
Definition: DefaultSettings.php:3534
Language\ucfirst
ucfirst( $str)
Definition: Language.php:2644
Language\$mMagicExtensions
$mMagicExtensions
Definition: Language.php:70
Language\gender
gender( $gender, $forms)
Provides an alternative text depending on specified gender.
Definition: Language.php:3984
Language\WEEKDAY_MESSAGES
const WEEKDAY_MESSAGES
Definition: Language.php:141
$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:4235