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 ALL = LanguageNameUtils::ALL;
49 
56  public const SUPPORTED = LanguageNameUtils::SUPPORTED;
57 
58  public $mCode;
59 
63  public $mMagicExtensions = [];
64 
65  private $mHtmlCode = null;
66 
71  public $dateFormatStrings = [];
72 
79 
81  protected $namespaceNames;
83 
87  private $transformData = [];
88 
91 
93  private $langNameUtils;
94 
96  private $langFallback;
97 
100 
105 
109  private $hookContainer;
110 
114  private $hookRunner;
115 
121  public const MESSAGES_FALLBACKS = LanguageFallback::MESSAGES;
122 
128  public const STRICT_FALLBACKS = LanguageFallback::STRICT;
129 
133  public const WEEKDAY_MESSAGES = [
134  'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
135  'friday', 'saturday'
136  ];
137 
142  'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
143  ];
144 
148  public const MONTH_MESSAGES = [
149  'january', 'february', 'march', 'april', 'may_long', 'june',
150  'july', 'august', 'september', 'october', 'november',
151  'december'
152  ];
153 
158 
162  public const MONTH_GENITIVE_MESSAGES = [
163  'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
164  'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
165  'december-gen'
166  ];
167 
171  public const MONTH_ABBREVIATED_MESSAGES = [
172  'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
173  'sep', 'oct', 'nov', 'dec'
174  ];
175 
180 
185  'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
186  'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
187  'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
188  'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
189  ];
190 
195  'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
196  'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
197  'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
198  'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
199  'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
200  ];
201 
206  'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
207  'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
208  'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
209  'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
210  'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
211  ];
212 
217  'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
218  'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
219  'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
220  'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
221  ];
222 
226  protected const DURATION_INTERVALS = [
227  'millennia' => 31556952000,
228  'centuries' => 3155695200,
229  'decades' => 315569520,
230  'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
231  'weeks' => 604800,
232  'days' => 86400,
233  'hours' => 3600,
234  'minutes' => 60,
235  'seconds' => 1,
236  ];
237 
244 
248  private const LRE = "\u{202A}"; // U+202A LEFT-TO-RIGHT EMBEDDING
249  private const RLE = "\u{202B}"; // U+202B RIGHT-TO-LEFT EMBEDDING
250  private const PDF = "\u{202C}"; // U+202C POP DIRECTIONAL FORMATTING
251 
263  // @codeCoverageIgnoreStart
264  // phpcs:ignore Generic.Files.LineLength
265  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';
266  // @codeCoverageIgnoreEnd
267 
275  public static function factory( $code ) {
276  return MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $code );
277  }
278 
288  public static function isSupportedLanguage( $code ) {
289  return MediaWikiServices::getInstance()->getLanguageNameUtils()
290  ->isSupportedLanguage( $code );
291  }
292 
308  public static function isWellFormedLanguageTag( $code, $lenient = false ) {
309  $alpha = '[a-z]';
310  $digit = '[0-9]';
311  $alphanum = '[a-z0-9]';
312  $x = 'x'; # private use singleton
313  $singleton = '[a-wy-z]'; # other singleton
314  $s = $lenient ? '[-_]' : '-';
315 
316  $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
317  $script = "$alpha{4}"; # ISO 15924
318  $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
319  $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
320  $extension = "$singleton(?:$s$alphanum{2,8})+";
321  $privateUse = "$x(?:$s$alphanum{1,8})+";
322 
323  # Define certain grandfathered codes, since otherwise the regex is pretty useless.
324  # Since these are limited, this is safe even later changes to the registry --
325  # the only oddity is that it might change the type of the tag, and thus
326  # the results from the capturing groups.
327  # https://www.iana.org/assignments/language-subtag-registry
328 
329  $grandfathered = "en{$s}GB{$s}oed"
330  . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
331  . "|no{$s}(?:bok|nyn)"
332  . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
333  . "|zh{$s}min{$s}nan";
334 
335  $variantList = "$variant(?:$s$variant)*";
336  $extensionList = "$extension(?:$s$extension)*";
337 
338  $langtag = "(?:($language)"
339  . "(?:$s$script)?"
340  . "(?:$s$region)?"
341  . "(?:$s$variantList)?"
342  . "(?:$s$extensionList)?"
343  . "(?:$s$privateUse)?)";
344 
345  # The final breakdown, with capturing groups for each of these components
346  # The variants, extensions, grandfathered, and private-use may have interior '-'
347 
348  $root = "^(?:$langtag|$privateUse|$grandfathered)$";
349 
350  return (bool)preg_match( "/$root/", strtolower( $code ) );
351  }
352 
365  public static function isValidCode( $code ) {
366  return MediaWikiServices::getInstance()->getLanguageNameUtils()->isValidCode( $code );
367  }
368 
380  public static function isValidBuiltInCode( $code ) {
381  return MediaWikiServices::getInstance()->getLanguageNameUtils()
382  ->isValidBuiltInCode( $code );
383  }
384 
395  public static function isKnownLanguageTag( $tag ) {
396  return MediaWikiServices::getInstance()->getLanguageNameUtils()
397  ->isKnownLanguageTag( $tag );
398  }
399 
404  public static function getLocalisationCache() {
405  return MediaWikiServices::getInstance()->getLocalisationCache();
406  }
407 
418  public function __construct(
419  $code = null,
425  ) {
426  if ( !func_num_args() ) {
427  // Old calling convention, deprecated
428  if ( static::class === 'Language' ) {
429  $this->mCode = 'en';
430  } else {
431  $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
432  }
433 
434  $services = MediaWikiServices::getInstance();
435  $this->localisationCache = $services->getLocalisationCache();
436  $this->langNameUtils = $services->getLanguageNameUtils();
437  $this->langFallback = $services->getLanguageFallback();
438  $this->converterFactory = $services->getLanguageConverterFactory();
439  $this->hookContainer = $services->getHookContainer();
440  $this->hookRunner = new HookRunner( $this->hookContainer );
441  return;
442  }
443 
444  Assert::parameter( $code !== null, '$code',
445  'Parameters cannot be null unless all are omitted' );
446  Assert::parameter( $localisationCache !== null, '$localisationCache',
447  'Parameters cannot be null unless all are omitted' );
448  Assert::parameter( $langNameUtils !== null, '$langNameUtils',
449  'Parameters cannot be null unless all are omitted' );
450  Assert::parameter( $langFallback !== null, '$langFallback',
451  'Parameters cannot be null unless all are omitted' );
452  Assert::parameter( $converterFactory !== null, '$converterFactory',
453  'Parameters cannot be null unless all are omitted' );
454  Assert::parameter( $hookContainer !== null, '$hookContainer',
455  'Parameters cannot be null unless all are omitted' );
456 
457  $this->mCode = $code;
458  $this->localisationCache = $localisationCache;
459  $this->langNameUtils = $langNameUtils;
460  $this->langFallback = $langFallback;
461  $this->converterFactory = $converterFactory;
462  $this->hookContainer = $hookContainer;
463  $this->hookRunner = new HookRunner( $hookContainer );
464  }
465 
470  public function __destruct() {
471  foreach ( $this as $name => $value ) {
472  unset( $this->$name );
473  }
474  }
475 
480  public function getFallbackLanguages() {
481  return $this->langFallback->getAll( $this->mCode );
482  }
483 
488  public function getBookstoreList() {
489  return $this->localisationCache->getItem( $this->mCode, 'bookstoreList' );
490  }
491 
498  public function getNamespaces() {
499  if ( $this->namespaceNames === null ) {
500  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
501  $metaNamespace = $mainConfig->get( 'MetaNamespace' );
502  $metaNamespaceTalk = $mainConfig->get( 'MetaNamespaceTalk' );
503  $extraNamespaces = $mainConfig->get( 'ExtraNamespaces' );
504  $validNamespaces = MediaWikiServices::getInstance()->getNamespaceInfo()->
505  getCanonicalNamespaces();
506 
507  $this->namespaceNames = $extraNamespaces +
508  $this->localisationCache->getItem( $this->mCode, 'namespaceNames' );
509  // @phan-suppress-next-line PhanTypeInvalidLeftOperand
510  $this->namespaceNames += $validNamespaces;
511 
512  $this->namespaceNames[NS_PROJECT] = $metaNamespace;
513  if ( $metaNamespaceTalk ) {
514  $this->namespaceNames[NS_PROJECT_TALK] = $metaNamespaceTalk;
515  } else {
516  $talk = $this->namespaceNames[NS_PROJECT_TALK];
517  $this->namespaceNames[NS_PROJECT_TALK] =
518  $this->fixVariableInNamespace( $talk );
519  }
520 
521  # Sometimes a language will be localised but not actually exist on this wiki.
522  foreach ( $this->namespaceNames as $key => $text ) {
523  if ( !isset( $validNamespaces[$key] ) ) {
524  unset( $this->namespaceNames[$key] );
525  }
526  }
527 
528  # The above mixing may leave namespaces out of canonical order.
529  # Re-order by namespace ID number...
530  ksort( $this->namespaceNames );
531 
532  $this->getHookRunner()->onLanguageGetNamespaces( $this->namespaceNames );
533  }
534 
535  return $this->namespaceNames;
536  }
537 
542  public function setNamespaces( array $namespaces ) {
543  $this->namespaceNames = $namespaces;
544  $this->mNamespaceIds = null;
545  }
546 
550  public function resetNamespaces() {
551  $this->namespaceNames = null;
552  $this->mNamespaceIds = null;
553  $this->namespaceAliases = null;
554  }
555 
562  public function getFormattedNamespaces() {
563  $ns = $this->getNamespaces();
564  foreach ( $ns as $k => $v ) {
565  $ns[$k] = strtr( $v, '_', ' ' );
566  }
567  return $ns;
568  }
569 
581  public function getNsText( $index ) {
582  $ns = $this->getNamespaces();
583  return $ns[$index] ?? false;
584  }
585 
599  public function getFormattedNsText( $index ) {
600  $ns = $this->getNsText( $index );
601  return strtr( $ns, '_', ' ' );
602  }
603 
612  public function getGenderNsText( $index, $gender ) {
613  $extraGenderNamespaces = MediaWikiServices::getInstance()->getMainConfig()->get( 'ExtraGenderNamespaces' );
614 
615  $ns = $extraGenderNamespaces +
616  (array)$this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
617 
618  return $ns[$index][$gender] ?? $this->getNsText( $index );
619  }
620 
627  public function needsGenderDistinction() {
628  $extraGenderNamespaces = MediaWikiServices::getInstance()->getMainConfig()->get( 'ExtraGenderNamespaces' );
629  $extraNamespaces = MediaWikiServices::getInstance()->getMainConfig()->get( 'ExtraNamespaces' );
630  if ( count( $extraGenderNamespaces ) > 0 ) {
631  // $wgExtraGenderNamespaces overrides everything
632  return true;
633  } elseif ( isset( $extraNamespaces[NS_USER] ) && isset( $extraNamespaces[NS_USER_TALK] ) ) {
634  // @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
635  // $wgExtraNamespaces overrides any gender aliases specified in i18n files
636  return false;
637  } else {
638  // Check what is in i18n files
639  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
640  return count( $aliases ) > 0;
641  }
642  }
643 
652  public function getLocalNsIndex( $text ) {
653  $lctext = $this->lc( $text );
654  $ids = $this->getNamespaceIds();
655  return $ids[$lctext] ?? false;
656  }
657 
662  public function getNamespaceAliases() {
663  if ( $this->namespaceAliases === null ) {
664  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceAliases' );
665  if ( !$aliases ) {
666  $aliases = [];
667  } else {
668  foreach ( $aliases as $name => $index ) {
669  if ( $index === NS_PROJECT_TALK ) {
670  unset( $aliases[$name] );
671  $name = $this->fixVariableInNamespace( $name );
672  $aliases[$name] = $index;
673  }
674  }
675  }
676 
677  $extraGenderNamespaces = MediaWikiServices::getInstance()->getMainConfig()->get( 'ExtraGenderNamespaces' );
678  $genders = $extraGenderNamespaces + (array)$this->localisationCache
679  ->getItem( $this->mCode, 'namespaceGenderAliases' );
680  foreach ( $genders as $index => $forms ) {
681  foreach ( $forms as $alias ) {
682  $aliases[$alias] = $index;
683  }
684  }
685 
686  # Also add converted namespace names as aliases, to avoid confusion.
687  $convertedNames = [];
688  foreach ( $this->getConverter()->getVariants() as $variant ) {
689  if ( $variant === $this->mCode ) {
690  continue;
691  }
692  foreach ( $this->getNamespaces() as $ns => $_ ) {
693  $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
694  }
695  }
696 
697  $this->namespaceAliases = $aliases + $convertedNames;
698 
699  // In the case of conflicts between $wgNamespaceAliases and other sources
700  // of aliasing, $wgNamespaceAliases wins.
701  $namespaceAliases = MediaWikiServices::getInstance()->getMainConfig()->get( 'NamespaceAliases' );
702  $this->namespaceAliases = $namespaceAliases + $this->namespaceAliases;
703 
704  # Filter out aliases to namespaces that don't exist, e.g. from extensions
705  # that aren't loaded here but are included in the l10n cache.
706  # (array_intersect preserves keys from its first argument)
707  $this->namespaceAliases = array_intersect(
708  $this->namespaceAliases,
709  array_keys( $this->getNamespaces() )
710  );
711  }
712 
714  }
715 
719  public function getNamespaceIds() {
720  if ( $this->mNamespaceIds === null ) {
721  # Put namespace names and aliases into a hashtable.
722  # If this is too slow, then we should arrange it so that it is done
723  # before caching. The catch is that at pre-cache time, the above
724  # class-specific fixup hasn't been done.
725  $this->mNamespaceIds = [];
726  foreach ( $this->getNamespaces() as $index => $name ) {
727  $this->mNamespaceIds[$this->lc( $name )] = $index;
728  }
729  foreach ( $this->getNamespaceAliases() as $name => $index ) {
730  $this->mNamespaceIds[$this->lc( $name )] = $index;
731  }
732  }
733  return $this->mNamespaceIds;
734  }
735 
743  public function getNsIndex( $text ) {
744  $lctext = $this->lc( $text );
745  $ns = MediaWikiServices::getInstance()->getNamespaceInfo()->
746  getCanonicalIndex( $lctext );
747  if ( $ns !== null ) {
748  return $ns;
749  }
750  $ids = $this->getNamespaceIds();
751  return $ids[$lctext] ?? false;
752  }
753 
761  public function getVariantname( $code, $usemsg = true ) {
762  $msg = "variantname-$code";
763  if ( $usemsg && wfMessage( $msg )->exists() ) {
764  return $this->getMessageFromDB( $msg );
765  }
766  $name = $this->langNameUtils->getLanguageName( $code );
767  if ( $name ) {
768  return $name; # if it's defined as a language name, show that
769  } else {
770  # otherwise, output the language code
771  return $code;
772  }
773  }
774 
778  public function getDatePreferences() {
779  return $this->localisationCache->getItem( $this->mCode, 'datePreferences' );
780  }
781 
785  public function getDateFormats() {
786  return $this->localisationCache->getItem( $this->mCode, 'dateFormats' );
787  }
788 
792  public function getDefaultDateFormat() {
793  $df = $this->localisationCache->getItem( $this->mCode, 'defaultDateFormat' );
794  if ( $df === 'dmy or mdy' ) {
795  $americanDates = MediaWikiServices::getInstance()->getMainConfig()->get( 'AmericanDates' );
796  return $americanDates ? 'mdy' : 'dmy';
797  } else {
798  return $df;
799  }
800  }
801 
805  public function getDatePreferenceMigrationMap() {
806  return $this->localisationCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
807  }
808 
824  public static function fetchLanguageNames(
825  $inLanguage = LanguageNameUtils::AUTONYMS,
826  $include = LanguageNameUtils::DEFINED
827  ) {
828  return MediaWikiServices::getInstance()->getLanguageNameUtils()
829  ->getLanguageNames( $inLanguage, $include );
830  }
831 
841  public static function fetchLanguageName(
842  $code,
843  $inLanguage = LanguageNameUtils::AUTONYMS,
844  $include = LanguageNameUtils::ALL
845  ) {
846  return MediaWikiServices::getInstance()->getLanguageNameUtils()
847  ->getLanguageName( $code, $inLanguage, $include );
848  }
849 
856  public function getMessageFromDB( $msg ) {
857  return $this->msg( $msg )->text();
858  }
859 
867  protected function msg( $msg, ...$params ) {
868  return wfMessage( $msg, ...$params )->inLanguage( $this );
869  }
870 
875  public function getMonthName( $key ) {
876  return $this->getMessageFromDB( self::MONTH_MESSAGES[$key - 1] );
877  }
878 
882  public function getMonthNamesArray() {
883  $monthNames = [ '' ];
884  for ( $i = 1; $i < 13; $i++ ) {
885  $monthNames[] = $this->getMonthName( $i );
886  }
887  return $monthNames;
888  }
889 
894  public function getMonthNameGen( $key ) {
895  return $this->getMessageFromDB( self::MONTH_GENITIVE_MESSAGES[$key - 1] );
896  }
897 
902  public function getMonthAbbreviation( $key ) {
903  return $this->getMessageFromDB( self::MONTH_ABBREVIATED_MESSAGES[$key - 1] );
904  }
905 
909  public function getMonthAbbreviationsArray() {
910  $monthNames = [ '' ];
911  for ( $i = 1; $i < 13; $i++ ) {
912  $monthNames[] = $this->getMonthAbbreviation( $i );
913  }
914  return $monthNames;
915  }
916 
921  public function getWeekdayName( $key ) {
922  return $this->getMessageFromDB( self::WEEKDAY_MESSAGES[$key - 1] );
923  }
924 
929  public function getWeekdayAbbreviation( $key ) {
930  return $this->getMessageFromDB( self::WEEKDAY_ABBREVIATED_MESSAGES[$key - 1] );
931  }
932 
937  private function getIranianCalendarMonthName( $key ) {
938  return $this->getMessageFromDB( self::IRANIAN_CALENDAR_MONTHS_MESSAGES[$key - 1] );
939  }
940 
945  private function getHebrewCalendarMonthName( $key ) {
946  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTHS_MESSAGES[$key - 1] );
947  }
948 
953  private function getHebrewCalendarMonthNameGen( $key ) {
954  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES[$key - 1] );
955  }
956 
961  private function getHijriCalendarMonthName( $key ) {
962  return $this->getMessageFromDB( self::HIJRI_CALENDAR_MONTH_MESSAGES[$key - 1] );
963  }
964 
973  private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
974  if ( !$dateTimeObj ) {
975  $dateTimeObj = DateTime::createFromFormat(
976  'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
977  );
978  }
979  return $dateTimeObj->format( $code );
980  }
981 
1052  public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
1053  $s = '';
1054  $raw = false;
1055  $roman = false;
1056  $hebrewNum = false;
1057  $dateTimeObj = false;
1058  $rawToggle = false;
1059  $iranian = false;
1060  $hebrew = false;
1061  $hijri = false;
1062  $thai = false;
1063  $minguo = false;
1064  $tenno = false;
1065 
1066  $usedSecond = false;
1067  $usedMinute = false;
1068  $usedHour = false;
1069  $usedAMPM = false;
1070  $usedDay = false;
1071  $usedWeek = false;
1072  $usedMonth = false;
1073  $usedYear = false;
1074  $usedISOYear = false;
1075  $usedIsLeapYear = false;
1076 
1077  $usedHebrewMonth = false;
1078  $usedIranianMonth = false;
1079  $usedHijriMonth = false;
1080  $usedHebrewYear = false;
1081  $usedIranianYear = false;
1082  $usedHijriYear = false;
1083  $usedTennoYear = false;
1084 
1085  if ( strlen( $ts ) !== 14 ) {
1086  throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1087  }
1088 
1089  if ( !ctype_digit( $ts ) ) {
1090  throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1091  }
1092 
1093  $formatLength = strlen( $format );
1094  for ( $p = 0; $p < $formatLength; $p++ ) {
1095  $num = false;
1096  $code = $format[$p];
1097  if ( $code == 'x' && $p < $formatLength - 1 ) {
1098  $code .= $format[++$p];
1099  }
1100 
1101  if ( ( $code === 'xi'
1102  || $code === 'xj'
1103  || $code === 'xk'
1104  || $code === 'xm'
1105  || $code === 'xo'
1106  || $code === 'xt' )
1107  && $p < $formatLength - 1 ) {
1108  $code .= $format[++$p];
1109  }
1110 
1111  switch ( $code ) {
1112  case 'xx':
1113  $s .= 'x';
1114  break;
1115  case 'xn':
1116  $raw = true;
1117  break;
1118  case 'xN':
1119  $rawToggle = !$rawToggle;
1120  break;
1121  case 'xr':
1122  $roman = true;
1123  break;
1124  case 'xh':
1125  $hebrewNum = true;
1126  break;
1127  case 'xg':
1128  $usedMonth = true;
1129  $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1130  break;
1131  case 'xjx':
1132  $usedHebrewMonth = true;
1133  if ( !$hebrew ) {
1134  $hebrew = self::tsToHebrew( $ts );
1135  }
1136  $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1137  break;
1138  case 'd':
1139  $usedDay = true;
1140  $num = substr( $ts, 6, 2 );
1141  break;
1142  case 'D':
1143  $usedDay = true;
1144  $s .= $this->getWeekdayAbbreviation(
1145  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1146  );
1147  break;
1148  case 'j':
1149  $usedDay = true;
1150  $num = intval( substr( $ts, 6, 2 ) );
1151  break;
1152  case 'xij':
1153  $usedDay = true;
1154  if ( !$iranian ) {
1155  $iranian = self::tsToIranian( $ts );
1156  }
1157  $num = $iranian[2];
1158  break;
1159  case 'xmj':
1160  $usedDay = true;
1161  if ( !$hijri ) {
1162  $hijri = self::tsToHijri( $ts );
1163  }
1164  $num = $hijri[2];
1165  break;
1166  case 'xjj':
1167  $usedDay = true;
1168  if ( !$hebrew ) {
1169  $hebrew = self::tsToHebrew( $ts );
1170  }
1171  $num = $hebrew[2];
1172  break;
1173  case 'l':
1174  $usedDay = true;
1175  $s .= $this->getWeekdayName(
1176  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1177  );
1178  break;
1179  case 'F':
1180  $usedMonth = true;
1181  $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1182  break;
1183  case 'xiF':
1184  $usedIranianMonth = true;
1185  if ( !$iranian ) {
1186  $iranian = self::tsToIranian( $ts );
1187  }
1188  $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1189  break;
1190  case 'xmF':
1191  $usedHijriMonth = true;
1192  if ( !$hijri ) {
1193  $hijri = self::tsToHijri( $ts );
1194  }
1195  $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1196  break;
1197  case 'xjF':
1198  $usedHebrewMonth = true;
1199  if ( !$hebrew ) {
1200  $hebrew = self::tsToHebrew( $ts );
1201  }
1202  $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1203  break;
1204  case 'm':
1205  $usedMonth = true;
1206  $num = substr( $ts, 4, 2 );
1207  break;
1208  case 'M':
1209  $usedMonth = true;
1210  $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1211  break;
1212  case 'n':
1213  $usedMonth = true;
1214  $num = intval( substr( $ts, 4, 2 ) );
1215  break;
1216  case 'xin':
1217  $usedIranianMonth = true;
1218  if ( !$iranian ) {
1219  $iranian = self::tsToIranian( $ts );
1220  }
1221  $num = $iranian[1];
1222  break;
1223  case 'xmn':
1224  $usedHijriMonth = true;
1225  if ( !$hijri ) {
1226  $hijri = self::tsToHijri( $ts );
1227  }
1228  $num = $hijri[1];
1229  break;
1230  case 'xjn':
1231  $usedHebrewMonth = true;
1232  if ( !$hebrew ) {
1233  $hebrew = self::tsToHebrew( $ts );
1234  }
1235  $num = $hebrew[1];
1236  break;
1237  case 'xjt':
1238  $usedHebrewMonth = true;
1239  if ( !$hebrew ) {
1240  $hebrew = self::tsToHebrew( $ts );
1241  }
1242  $num = $hebrew[3];
1243  break;
1244  case 'Y':
1245  $usedYear = true;
1246  $num = substr( $ts, 0, 4 );
1247  break;
1248  case 'xiY':
1249  $usedIranianYear = true;
1250  if ( !$iranian ) {
1251  $iranian = self::tsToIranian( $ts );
1252  }
1253  $num = $iranian[0];
1254  break;
1255  case 'xmY':
1256  $usedHijriYear = true;
1257  if ( !$hijri ) {
1258  $hijri = self::tsToHijri( $ts );
1259  }
1260  $num = $hijri[0];
1261  break;
1262  case 'xjY':
1263  $usedHebrewYear = true;
1264  if ( !$hebrew ) {
1265  $hebrew = self::tsToHebrew( $ts );
1266  }
1267  $num = $hebrew[0];
1268  break;
1269  case 'xkY':
1270  $usedYear = true;
1271  if ( !$thai ) {
1272  $thai = self::tsToYear( $ts, 'thai' );
1273  }
1274  $num = $thai[0];
1275  break;
1276  case 'xoY':
1277  $usedYear = true;
1278  if ( !$minguo ) {
1279  $minguo = self::tsToYear( $ts, 'minguo' );
1280  }
1281  $num = $minguo[0];
1282  break;
1283  case 'xtY':
1284  $usedTennoYear = true;
1285  if ( !$tenno ) {
1286  $tenno = self::tsToYear( $ts, 'tenno' );
1287  }
1288  $num = $tenno[0];
1289  break;
1290  case 'y':
1291  $usedYear = true;
1292  $num = substr( $ts, 2, 2 );
1293  break;
1294  case 'xiy':
1295  $usedIranianYear = true;
1296  if ( !$iranian ) {
1297  $iranian = self::tsToIranian( $ts );
1298  }
1299  $num = substr( $iranian[0], -2 );
1300  break;
1301  case 'xit':
1302  $usedIranianYear = true;
1303  if ( !$iranian ) {
1304  $iranian = self::tsToIranian( $ts );
1305  }
1306  $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
1307  break;
1308  case 'xiz':
1309  $usedIranianYear = true;
1310  if ( !$iranian ) {
1311  $iranian = self::tsToIranian( $ts );
1312  }
1313  $num = $iranian[3];
1314  break;
1315  case 'a':
1316  $usedAMPM = true;
1317  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1318  break;
1319  case 'A':
1320  $usedAMPM = true;
1321  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1322  break;
1323  case 'g':
1324  $usedHour = true;
1325  $h = substr( $ts, 8, 2 );
1326  $num = $h % 12 ?: 12;
1327  break;
1328  case 'G':
1329  $usedHour = true;
1330  $num = intval( substr( $ts, 8, 2 ) );
1331  break;
1332  case 'h':
1333  $usedHour = true;
1334  $h = substr( $ts, 8, 2 );
1335  $num = sprintf( '%02d', $h % 12 ?: 12 );
1336  break;
1337  case 'H':
1338  $usedHour = true;
1339  $num = substr( $ts, 8, 2 );
1340  break;
1341  case 'i':
1342  $usedMinute = true;
1343  $num = substr( $ts, 10, 2 );
1344  break;
1345  case 's':
1346  $usedSecond = true;
1347  $num = substr( $ts, 12, 2 );
1348  break;
1349  case 'c':
1350  case 'r':
1351  $usedSecond = true;
1352  // fall through
1353  case 'e':
1354  case 'O':
1355  case 'P':
1356  case 'T':
1357  $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1358  break;
1359  case 'w':
1360  case 'N':
1361  case 'z':
1362  $usedDay = true;
1363  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1364  break;
1365  case 'W':
1366  $usedWeek = true;
1367  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1368  break;
1369  case 't':
1370  $usedMonth = true;
1371  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1372  break;
1373  case 'L':
1374  $usedIsLeapYear = true;
1375  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1376  break;
1377  case 'o':
1378  $usedISOYear = true;
1379  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1380  break;
1381  case 'U':
1382  $usedSecond = true;
1383  // fall through
1384  case 'I':
1385  case 'Z':
1386  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1387  break;
1388  case '\\':
1389  # Backslash escaping
1390  if ( $p < $formatLength - 1 ) {
1391  $s .= $format[++$p];
1392  } else {
1393  $s .= '\\';
1394  }
1395  break;
1396  case '"':
1397  # Quoted literal
1398  if ( $p < $formatLength - 1 ) {
1399  $endQuote = strpos( $format, '"', $p + 1 );
1400  if ( $endQuote === false ) {
1401  # No terminating quote, assume literal "
1402  $s .= '"';
1403  } else {
1404  $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1405  $p = $endQuote;
1406  }
1407  } else {
1408  # Quote at end of string, assume literal "
1409  $s .= '"';
1410  }
1411  break;
1412  default:
1413  $s .= $format[$p];
1414  }
1415  if ( $num !== false ) {
1416  if ( $rawToggle || $raw ) {
1417  $s .= $num;
1418  $raw = false;
1419  } elseif ( $roman ) {
1420  $s .= self::romanNumeral( $num );
1421  $roman = false;
1422  } elseif ( $hebrewNum ) {
1423  $s .= self::hebrewNumeral( $num );
1424  $hebrewNum = false;
1425  } elseif ( preg_match( '/^[\d.]+$/', $num ) ) {
1426  $s .= $this->formatNumNoSeparators( $num );
1427  } else {
1428  $s .= $num;
1429  }
1430  }
1431  }
1432 
1433  if ( $ttl === 'unused' ) {
1434  // No need to calculate the TTL, the caller wont use it anyway.
1435  } elseif ( $usedSecond ) {
1436  $ttl = 1;
1437  } elseif ( $usedMinute ) {
1438  $ttl = 60 - substr( $ts, 12, 2 );
1439  } elseif ( $usedHour ) {
1440  $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1441  } elseif ( $usedAMPM ) {
1442  $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1443  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1444  } elseif (
1445  $usedDay ||
1446  $usedHebrewMonth ||
1447  $usedIranianMonth ||
1448  $usedHijriMonth ||
1449  $usedHebrewYear ||
1450  $usedIranianYear ||
1451  $usedHijriYear ||
1452  $usedTennoYear
1453  ) {
1454  // @todo Someone who understands the non-Gregorian calendars
1455  // should write proper logic for them so that they don't need purged every day.
1456  $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1457  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1458  } else {
1459  $possibleTtls = [];
1460  $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1461  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1462  if ( $usedWeek ) {
1463  $possibleTtls[] =
1464  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1465  $timeRemainingInDay;
1466  } elseif ( $usedISOYear ) {
1467  // December 28th falls on the last ISO week of the year, every year.
1468  // The last ISO week of a year can be 52 or 53.
1469  $lastWeekOfISOYear = DateTime::createFromFormat(
1470  'Ymd',
1471  substr( $ts, 0, 4 ) . '1228',
1472  $zone ?: new DateTimeZone( 'UTC' )
1473  )->format( 'W' );
1474  $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1475  $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1476  $timeRemainingInWeek =
1477  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1478  + $timeRemainingInDay;
1479  $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1480  }
1481 
1482  if ( $usedMonth ) {
1483  $possibleTtls[] =
1484  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1485  substr( $ts, 6, 2 ) ) * 86400
1486  + $timeRemainingInDay;
1487  } elseif ( $usedYear ) {
1488  $possibleTtls[] =
1489  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1490  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1491  + $timeRemainingInDay;
1492  } elseif ( $usedIsLeapYear ) {
1493  $year = substr( $ts, 0, 4 );
1494  $timeRemainingInYear =
1495  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1496  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1497  + $timeRemainingInDay;
1498  $mod = $year % 4;
1499  if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1500  // this isn't a leap year. see when the next one starts
1501  $nextCandidate = $year - $mod + 4;
1502  if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1503  $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1504  $timeRemainingInYear;
1505  } else {
1506  $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1507  $timeRemainingInYear;
1508  }
1509  } else {
1510  // this is a leap year, so the next year isn't
1511  $possibleTtls[] = $timeRemainingInYear;
1512  }
1513  }
1514 
1515  if ( $possibleTtls ) {
1516  $ttl = min( $possibleTtls );
1517  }
1518  }
1519 
1520  return $s;
1521  }
1522 
1523  private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1524  private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1525 
1538  private static function tsToIranian( $ts ) {
1539  $gy = substr( $ts, 0, 4 ) - 1600;
1540  $gm = substr( $ts, 4, 2 ) - 1;
1541  $gd = substr( $ts, 6, 2 ) - 1;
1542 
1543  # Days passed from the beginning (including leap years)
1544  $gDayNo = 365 * $gy
1545  + floor( ( $gy + 3 ) / 4 )
1546  - floor( ( $gy + 99 ) / 100 )
1547  + floor( ( $gy + 399 ) / 400 );
1548 
1549  // Add days of the past months of this year
1550  for ( $i = 0; $i < $gm; $i++ ) {
1551  $gDayNo += self::$GREG_DAYS[$i];
1552  }
1553 
1554  // Leap years
1555  if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 ) || $gy % 400 == 0 ) ) {
1556  $gDayNo++;
1557  }
1558 
1559  // Days passed in current month
1560  $gDayNo += (int)$gd;
1561 
1562  $jDayNo = $gDayNo - 79;
1563 
1564  $jNp = floor( $jDayNo / 12053 );
1565  $jDayNo %= 12053;
1566 
1567  $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1568  $jDayNo %= 1461;
1569 
1570  if ( $jDayNo >= 366 ) {
1571  $jy += floor( ( $jDayNo - 1 ) / 365 );
1572  $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1573  }
1574 
1575  $jz = $jDayNo;
1576 
1577  for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1578  $jDayNo -= self::$IRANIAN_DAYS[$i];
1579  }
1580 
1581  $jm = $i + 1;
1582  $jd = $jDayNo + 1;
1583 
1584  return [ $jy, $jm, $jd, $jz ];
1585  }
1586 
1598  private static function tsToHijri( $ts ) {
1599  $year = substr( $ts, 0, 4 );
1600  $month = substr( $ts, 4, 2 );
1601  $day = substr( $ts, 6, 2 );
1602 
1603  $zyr = $year;
1604  $zd = $day;
1605  $zm = $month;
1606  $zy = $zyr;
1607 
1608  if (
1609  ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1610  ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1611  ) {
1612  $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1613  (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1614  (int)( ( 3 * (int)( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) / 4 ) +
1615  $zd - 32075;
1616  } else {
1617  $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1618  (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1619  }
1620 
1621  $zl = $zjd - 1948440 + 10632;
1622  $zn = (int)( ( $zl - 1 ) / 10631 );
1623  $zl = $zl - 10631 * $zn + 354;
1624  $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1625  ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1626  $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1627  ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1628  $zm = (int)( ( 24 * $zl ) / 709 );
1629  $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1630  $zy = 30 * $zn + $zj - 30;
1631 
1632  return [ $zy, $zm, $zd ];
1633  }
1634 
1650  private static function tsToHebrew( $ts ) {
1651  # Parse date
1652  $year = substr( $ts, 0, 4 );
1653  $month = substr( $ts, 4, 2 );
1654  $day = substr( $ts, 6, 2 );
1655 
1656  # Calculate Hebrew year
1657  $hebrewYear = $year + 3760;
1658 
1659  # Month number when September = 1, August = 12
1660  $month += 4;
1661  if ( $month > 12 ) {
1662  # Next year
1663  $month -= 12;
1664  $year++;
1665  $hebrewYear++;
1666  }
1667 
1668  # Calculate day of year from 1 September
1669  $dayOfYear = $day;
1670  for ( $i = 1; $i < $month; $i++ ) {
1671  if ( $i == 6 ) {
1672  # February
1673  $dayOfYear += 28;
1674  # Check if the year is leap
1675  if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1676  $dayOfYear++;
1677  }
1678  } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1679  $dayOfYear += 30;
1680  } else {
1681  $dayOfYear += 31;
1682  }
1683  }
1684 
1685  # Calculate the start of the Hebrew year
1686  $start = self::hebrewYearStart( $hebrewYear );
1687 
1688  # Calculate next year's start
1689  if ( $dayOfYear <= $start ) {
1690  # Day is before the start of the year - it is the previous year
1691  # Next year's start
1692  $nextStart = $start;
1693  # Previous year
1694  $year--;
1695  $hebrewYear--;
1696  # Add days since previous year's 1 September
1697  $dayOfYear += 365;
1698  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1699  # Leap year
1700  $dayOfYear++;
1701  }
1702  # Start of the new (previous) year
1703  $start = self::hebrewYearStart( $hebrewYear );
1704  } else {
1705  # Next year's start
1706  $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1707  }
1708 
1709  # Calculate Hebrew day of year
1710  $hebrewDayOfYear = $dayOfYear - $start;
1711 
1712  # Difference between year's days
1713  $diff = $nextStart - $start;
1714  # Add 12 (or 13 for leap years) days to ignore the difference between
1715  # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1716  # difference is only about the year type
1717  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1718  $diff += 13;
1719  } else {
1720  $diff += 12;
1721  }
1722 
1723  # Check the year pattern, and is leap year
1724  # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1725  # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1726  # and non-leap years
1727  $yearPattern = $diff % 30;
1728  # Check if leap year
1729  $isLeap = $diff >= 30;
1730 
1731  # Calculate day in the month from number of day in the Hebrew year
1732  # Don't check Adar - if the day is not in Adar, we will stop before;
1733  # if it is in Adar, we will use it to check if it is Adar I or Adar II
1734  $hebrewDay = $hebrewDayOfYear;
1735  $hebrewMonth = 1;
1736  $days = 0;
1737  while ( $hebrewMonth <= 12 ) {
1738  # Calculate days in this month
1739  if ( $isLeap && $hebrewMonth == 6 ) {
1740  # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1741  $days = 30;
1742  if ( $hebrewDay <= $days ) {
1743  # Day in Adar I
1744  $hebrewMonth = 13;
1745  } else {
1746  # Subtract the days of Adar I
1747  $hebrewDay -= $days;
1748  # Try Adar II
1749  $days = 29;
1750  if ( $hebrewDay <= $days ) {
1751  # Day in Adar II
1752  $hebrewMonth = 14;
1753  }
1754  }
1755  } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1756  # Cheshvan in a complete year (otherwise as the rule below)
1757  $days = 30;
1758  } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1759  # Kislev in an incomplete year (otherwise as the rule below)
1760  $days = 29;
1761  } else {
1762  # Odd months have 30 days, even have 29
1763  $days = 30 - ( $hebrewMonth - 1 ) % 2;
1764  }
1765  if ( $hebrewDay <= $days ) {
1766  # In the current month
1767  break;
1768  } else {
1769  # Subtract the days of the current month
1770  $hebrewDay -= $days;
1771  # Try in the next month
1772  $hebrewMonth++;
1773  }
1774  }
1775 
1776  return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1777  }
1778 
1788  private static function hebrewYearStart( $year ) {
1789  $a = ( 12 * ( $year - 1 ) + 17 ) % 19;
1790  $b = ( $year - 1 ) % 4;
1791  $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1792  if ( $m < 0 ) {
1793  $m--;
1794  }
1795  $Mar = intval( $m );
1796  if ( $m < 0 ) {
1797  $m++;
1798  }
1799  $m -= $Mar;
1800 
1801  $c = ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7;
1802  if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1803  $Mar++;
1804  } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1805  $Mar += 2;
1806  } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1807  $Mar++;
1808  }
1809 
1810  $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1811  return $Mar;
1812  }
1813 
1826  private static function tsToYear( $ts, $cName ) {
1827  $gy = substr( $ts, 0, 4 );
1828  $gm = substr( $ts, 4, 2 );
1829  $gd = substr( $ts, 6, 2 );
1830 
1831  if ( !strcmp( $cName, 'thai' ) ) {
1832  # Thai solar dates
1833  # Add 543 years to the Gregorian calendar
1834  # Months and days are identical
1835  $gy_offset = $gy + 543;
1836  # fix for dates between 1912 and 1941
1837  # https://en.wikipedia.org/?oldid=836596673#New_year
1838  if ( $gy >= 1912 && $gy <= 1940 ) {
1839  if ( $gm <= 3 ) {
1840  $gy_offset--;
1841  }
1842  $gm = ( $gm - 3 ) % 12;
1843  }
1844  } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1845  # Minguo dates
1846  # Deduct 1911 years from the Gregorian calendar
1847  # Months and days are identical
1848  $gy_offset = $gy - 1911;
1849  } elseif ( !strcmp( $cName, 'tenno' ) ) {
1850  # Nengō dates up to Meiji period
1851  # Deduct years from the Gregorian calendar
1852  # depending on the nengo periods
1853  # Months and days are identical
1854  if ( ( $gy < 1912 )
1855  || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1856  || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1857  ) {
1858  # Meiji period
1859  $gy_gannen = $gy - 1868 + 1;
1860  $gy_offset = $gy_gannen;
1861  if ( $gy_gannen == 1 ) {
1862  $gy_offset = '元';
1863  }
1864  $gy_offset = '明治' . $gy_offset;
1865  } elseif (
1866  ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1867  ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1868  ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1869  ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1870  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1871  ) {
1872  # Taishō period
1873  $gy_gannen = $gy - 1912 + 1;
1874  $gy_offset = $gy_gannen;
1875  if ( $gy_gannen == 1 ) {
1876  $gy_offset = '元';
1877  }
1878  $gy_offset = '大正' . $gy_offset;
1879  } elseif (
1880  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1881  ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1882  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1883  ) {
1884  # Shōwa period
1885  $gy_gannen = $gy - 1926 + 1;
1886  $gy_offset = $gy_gannen;
1887  if ( $gy_gannen == 1 ) {
1888  $gy_offset = '元';
1889  }
1890  $gy_offset = '昭和' . $gy_offset;
1891  } elseif (
1892  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd >= 8 ) ) ||
1893  ( ( $gy > 1989 ) && ( $gy < 2019 ) ) ||
1894  ( ( $gy == 2019 ) && ( $gm < 5 ) )
1895  ) {
1896  # Heisei period
1897  $gy_gannen = $gy - 1989 + 1;
1898  $gy_offset = $gy_gannen;
1899  if ( $gy_gannen == 1 ) {
1900  $gy_offset = '元';
1901  }
1902  $gy_offset = '平成' . $gy_offset;
1903  } else {
1904  # Reiwa period
1905  $gy_gannen = $gy - 2019 + 1;
1906  $gy_offset = $gy_gannen;
1907  if ( $gy_gannen == 1 ) {
1908  $gy_offset = '元';
1909  }
1910  $gy_offset = '令和' . $gy_offset;
1911  }
1912  } else {
1913  $gy_offset = $gy;
1914  }
1915 
1916  return [ $gy_offset, $gm, $gd ];
1917  }
1918 
1932  private static function strongDirFromContent( $text = '' ) {
1933  if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
1934  return null;
1935  }
1936  if ( $matches[1] === '' ) {
1937  return 'rtl';
1938  }
1939  return 'ltr';
1940  }
1941 
1949  public static function romanNumeral( $num ) {
1950  static $table = [
1951  [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
1952  [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
1953  [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
1954  [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1955  'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
1956  ];
1957 
1958  $num = intval( $num );
1959  if ( $num > 10000 || $num <= 0 ) {
1960  return $num;
1961  }
1962 
1963  $s = '';
1964  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1965  if ( $num >= $pow10 ) {
1966  $s .= $table[$i][(int)floor( $num / $pow10 )];
1967  }
1968  $num %= $pow10;
1969  }
1970  return $s;
1971  }
1972 
1980  public static function hebrewNumeral( $num ) {
1981  static $table = [
1982  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
1983  [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
1984  [ '',
1985  [ 'ק' ],
1986  [ 'ר' ],
1987  [ 'ש' ],
1988  [ 'ת' ],
1989  [ 'ת', 'ק' ],
1990  [ 'ת', 'ר' ],
1991  [ 'ת', 'ש' ],
1992  [ 'ת', 'ת' ],
1993  [ 'ת', 'ת', 'ק' ],
1994  [ 'ת', 'ת', 'ר' ],
1995  ],
1996  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
1997  ];
1998 
1999  $num = intval( $num );
2000  if ( $num > 9999 || $num <= 0 ) {
2001  return $num;
2002  }
2003 
2004  // Round thousands have special notations
2005  if ( $num === 1000 ) {
2006  return "א' אלף";
2007  } elseif ( $num % 1000 === 0 ) {
2008  return $table[0][$num / 1000] . "' אלפים";
2009  }
2010 
2011  $letters = [];
2012 
2013  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2014  if ( $num >= $pow10 ) {
2015  if ( $num === 15 || $num === 16 ) {
2016  $letters[] = $table[0][9];
2017  $letters[] = $table[0][$num - 9];
2018  $num = 0;
2019  } else {
2020  $letters = array_merge(
2021  $letters,
2022  (array)$table[$i][intval( $num / $pow10 )]
2023  );
2024 
2025  if ( $pow10 === 1000 ) {
2026  $letters[] = "'";
2027  }
2028  }
2029  }
2030 
2031  $num %= $pow10;
2032  }
2033 
2034  $preTransformLength = count( $letters );
2035  if ( $preTransformLength === 1 ) {
2036  // Add geresh (single quote) to one-letter numbers
2037  $letters[] = "'";
2038  } else {
2039  $lastIndex = $preTransformLength - 1;
2040  $letters[$lastIndex] = str_replace(
2041  [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2042  [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2043  $letters[$lastIndex]
2044  );
2045 
2046  // Add gershayim (double quote) to multiple-letter numbers,
2047  // but exclude numbers with only one letter after the thousands
2048  // (1001-1009, 1020, 1030, 2001-2009, etc.)
2049  if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2050  $letters[] = "'";
2051  } else {
2052  array_splice( $letters, -1, 0, '"' );
2053  }
2054  }
2055 
2056  return implode( $letters );
2057  }
2058 
2067  public function userAdjust( $ts, $tz = false ) {
2068  $localTZoffset = MediaWikiServices::getInstance()->getMainConfig()->get( 'LocalTZoffset' );
2069 
2070  if ( $tz === false ) {
2071  $optionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
2072  $tz = $optionsLookup->getOption(
2074  'timecorrection'
2075  );
2076  }
2077 
2078  $data = explode( '|', $tz, 3 );
2079 
2080  if ( $data[0] == 'ZoneInfo' ) {
2081  try {
2082  $userTZ = new DateTimeZone( $data[2] );
2083  $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
2084  $date->setTimezone( $userTZ );
2085  return $date->format( 'YmdHis' );
2086  } catch ( Exception $e ) {
2087  // Unrecognized timezone, default to 'Offset' with the stored offset.
2088  $data[0] = 'Offset';
2089  }
2090  }
2091 
2092  if ( $data[0] == 'System' || $tz == '' ) {
2093  # Global offset in minutes.
2094  $minDiff = $localTZoffset;
2095  } elseif ( $data[0] == 'Offset' ) {
2096  $minDiff = intval( $data[1] );
2097  } else {
2098  $data = explode( ':', $tz );
2099  if ( count( $data ) == 2 ) {
2100  $data[0] = intval( $data[0] );
2101  $data[1] = intval( $data[1] );
2102  $minDiff = abs( $data[0] ) * 60 + $data[1];
2103  if ( $data[0] < 0 ) {
2104  $minDiff = -$minDiff;
2105  }
2106  } else {
2107  $minDiff = intval( $data[0] ) * 60;
2108  }
2109  }
2110 
2111  # No difference ? Return time unchanged
2112  if ( $minDiff == 0 ) {
2113  return $ts;
2114  }
2115 
2116  Wikimedia\suppressWarnings(); // E_STRICT system time bitching
2117  # Generate an adjusted date; take advantage of the fact that mktime
2118  # will normalize out-of-range values so we don't have to split $minDiff
2119  # into hours and minutes.
2120  $t = mktime( (
2121  (int)substr( $ts, 8, 2 ) ), # Hours
2122  (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2123  (int)substr( $ts, 12, 2 ), # Seconds
2124  (int)substr( $ts, 4, 2 ), # Month
2125  (int)substr( $ts, 6, 2 ), # Day
2126  (int)substr( $ts, 0, 4 ) ); # Year
2127 
2128  $date = date( 'YmdHis', $t );
2129  Wikimedia\restoreWarnings();
2130 
2131  return $date;
2132  }
2133 
2149  public function dateFormat( $usePrefs = true ) {
2150  if ( is_bool( $usePrefs ) ) {
2151  if ( $usePrefs ) {
2152  $datePreference = RequestContext::getMain()
2153  ->getUser()
2154  ->getDatePreference();
2155  } else {
2156  $userOptionsLookup = MediawikiServices::getInstance()->getUserOptionsLookup();
2157  $datePreference = (string)$userOptionsLookup->getDefaultOption( 'date' );
2158  }
2159  } else {
2160  $datePreference = (string)$usePrefs;
2161  }
2162 
2163  // return int
2164  if ( $datePreference == '' ) {
2165  return 'default';
2166  }
2167 
2168  return $datePreference;
2169  }
2170 
2181  public function getDateFormatString( $type, $pref ) {
2182  $wasDefault = false;
2183  if ( $pref == 'default' ) {
2184  $wasDefault = true;
2185  $pref = $this->getDefaultDateFormat();
2186  }
2187 
2188  if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2189  $df = $this->localisationCache
2190  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2191 
2192  if ( $type === 'pretty' && $df === null ) {
2193  $df = $this->getDateFormatString( 'date', $pref );
2194  }
2195 
2196  if ( !$wasDefault && $df === null ) {
2197  $pref = $this->getDefaultDateFormat();
2198  $df = $this->localisationCache
2199  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2200  }
2201 
2202  $this->dateFormatStrings[$type][$pref] = $df;
2203  }
2204  return $this->dateFormatStrings[$type][$pref];
2205  }
2206 
2217  public function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2218  $ts = wfTimestamp( TS_MW, $ts );
2219  if ( $adj ) {
2220  $ts = $this->userAdjust( $ts, $timecorrection );
2221  }
2222  $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2223  return $this->sprintfDate( $df, $ts );
2224  }
2225 
2236  public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2237  $ts = wfTimestamp( TS_MW, $ts );
2238  if ( $adj ) {
2239  $ts = $this->userAdjust( $ts, $timecorrection );
2240  }
2241  $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2242  return $this->sprintfDate( $df, $ts );
2243  }
2244 
2256  public function timeanddate( $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( 'both', $this->dateFormat( $format ) );
2262  return $this->sprintfDate( $df, $ts );
2263  }
2264 
2275  public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2276  $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2277 
2278  $segments = [];
2279 
2280  foreach ( $intervals as $intervalName => $intervalValue ) {
2281  // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2282  // duration-years, duration-decades, duration-centuries, duration-millennia
2283  $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2284  $segments[] = $message->inLanguage( $this )->escaped();
2285  }
2286 
2287  return $this->listToText( $segments );
2288  }
2289 
2301  public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2302  if ( empty( $chosenIntervals ) ) {
2303  $chosenIntervals = [
2304  'millennia',
2305  'centuries',
2306  'decades',
2307  'years',
2308  'days',
2309  'hours',
2310  'minutes',
2311  'seconds'
2312  ];
2313  }
2314 
2315  $intervals = array_intersect_key( self::DURATION_INTERVALS,
2316  array_fill_keys( $chosenIntervals, true ) );
2317  $sortedNames = array_keys( $intervals );
2318  $smallestInterval = array_pop( $sortedNames );
2319 
2320  $segments = [];
2321 
2322  foreach ( $intervals as $name => $length ) {
2323  $value = floor( $seconds / $length );
2324 
2325  if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2326  $seconds -= $value * $length;
2327  $segments[$name] = $value;
2328  }
2329  }
2330 
2331  return $segments;
2332  }
2333 
2353  private function internalUserTimeAndDate( $type, $ts, UserIdentity $user, array $options ) {
2354  $ts = wfTimestamp( TS_MW, $ts );
2355  $options += [ 'timecorrection' => true, 'format' => true ];
2356  if ( $options['timecorrection'] !== false ) {
2357  if ( $options['timecorrection'] === true ) {
2358  $offset = MediaWikiServices::getInstance()
2359  ->getUserOptionsLookup()
2360  ->getOption( $user, 'timecorrection' );
2361  } else {
2362  $offset = $options['timecorrection'];
2363  }
2364  $ts = $this->userAdjust( $ts, $offset );
2365  }
2366  if ( $options['format'] === true ) {
2367  $format = MediaWikiServices::getInstance()
2368  ->getUserFactory()
2369  ->newFromUserIdentity( $user )
2370  ->getDatePreference();
2371  } else {
2372  $format = $options['format'];
2373  }
2374  $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2375  return $this->sprintfDate( $df, $ts );
2376  }
2377 
2397  public function userDate( $ts, UserIdentity $user, array $options = [] ) {
2398  return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2399  }
2400 
2420  public function userTime( $ts, UserIdentity $user, array $options = [] ) {
2421  return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2422  }
2423 
2443  public function userTimeAndDate( $ts, UserIdentity $user, array $options = [] ) {
2444  return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2445  }
2446 
2462  public function getHumanTimestamp(
2463  MWTimestamp $time, MWTimestamp $relativeTo = null, UserIdentity $user = null
2464  ) {
2465  if ( $relativeTo === null ) {
2466  $relativeTo = new MWTimestamp();
2467  }
2468  if ( $user === null ) {
2469  $user = RequestContext::getMain()->getUser();
2470  } else {
2471  // For compatibility with the hook signature and self::getHumanTimestampInternal
2472  $user = MediaWikiServices::getInstance()
2473  ->getUserFactory()
2474  ->newFromUserIdentity( $user );
2475  }
2476 
2477  // Adjust for the user's timezone.
2478  $offsetThis = $time->offsetForUser( $user );
2479  $offsetRel = $relativeTo->offsetForUser( $user );
2480 
2481  $ts = '';
2482  if ( $this->getHookRunner()->onGetHumanTimestamp( $ts, $time, $relativeTo, $user, $this ) ) {
2483  $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2484  }
2485 
2486  // Reset the timezone on the objects.
2487  $time->timestamp->sub( $offsetThis );
2488  $relativeTo->timestamp->sub( $offsetRel );
2489 
2490  return $ts;
2491  }
2492 
2504  private function getHumanTimestampInternal(
2505  MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2506  ) {
2507  $diff = $ts->diff( $relativeTo );
2508  $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2509  (int)$relativeTo->timestamp->format( 'w' ) );
2510  $days = $diff->days ?: (int)$diffDay;
2511  if ( $diff->invert || $days > 5
2512  && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2513  ) {
2514  // Timestamps are in different years: use full timestamp
2515  // Also do full timestamp for future dates
2519  $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2520  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2521  } elseif ( $days > 5 ) {
2522  // Timestamps are in same year, but more than 5 days ago: show day and month only.
2523  $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2524  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2525  } elseif ( $days > 1 ) {
2526  // Timestamp within the past week: show the day of the week and time
2527  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2528  $weekday = self::WEEKDAY_MESSAGES[$ts->timestamp->format( 'w' )];
2529  // Messages:
2530  // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2531  $ts = wfMessage( "$weekday-at" )
2532  ->inLanguage( $this )
2533  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2534  ->text();
2535  } elseif ( $days == 1 ) {
2536  // Timestamp was yesterday: say 'yesterday' and the time.
2537  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2538  $ts = wfMessage( 'yesterday-at' )
2539  ->inLanguage( $this )
2540  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2541  ->text();
2542  } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2543  // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2544  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2545  $ts = wfMessage( 'today-at' )
2546  ->inLanguage( $this )
2547  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2548  ->text();
2549 
2550  // From here on in, the timestamp was soon enough ago so that we can simply say
2551  // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2552  } elseif ( $diff->h == 1 ) {
2553  // Less than 90 minutes, but more than an hour ago.
2554  $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2555  } elseif ( $diff->i >= 1 ) {
2556  // A few minutes ago.
2557  $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2558  } elseif ( $diff->s >= 30 ) {
2559  // Less than a minute, but more than 30 sec ago.
2560  $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2561  } else {
2562  // Less than 30 seconds ago.
2563  $ts = wfMessage( 'just-now' )->text();
2564  }
2565 
2566  return $ts;
2567  }
2568 
2576  public function getGroupName( $group ) {
2577  $msg = $this->msg( "group-$group" );
2578  return $msg->isBlank() ? $group : $msg->text();
2579  }
2580 
2589  public function getGroupMemberName( string $group, $member ) {
2590  if ( $member instanceof UserIdentity ) {
2591  $member = $member->getName();
2592  }
2593  $msg = $this->msg( "group-$group-member", $member );
2594  return $msg->isBlank() ? $group : $msg->text();
2595  }
2596 
2601  public function getMessage( $key ) {
2602  return $this->localisationCache->getSubitem( $this->mCode, 'messages', $key );
2603  }
2604 
2608  public function getAllMessages() {
2609  return $this->localisationCache->getItem( $this->mCode, 'messages' );
2610  }
2611 
2618  public function iconv( $in, $out, $string ) {
2619  # Even with //IGNORE iconv can whine about illegal characters in
2620  # *input* string. We just ignore those too.
2621  # REF: https://bugs.php.net/bug.php?id=37166
2622  # REF: https://phabricator.wikimedia.org/T18885
2623  Wikimedia\suppressWarnings();
2624  $text = iconv( $in, $out . '//IGNORE', $string );
2625  Wikimedia\restoreWarnings();
2626  return $text;
2627  }
2628 
2633  public function ucfirst( $str ) {
2634  $octetCode = ord( $str );
2635  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2636  if ( $octetCode < 96 ) {
2637  // Assume this is an uppercase/uncased ASCII character
2638  return (string)$str;
2639  } elseif ( $octetCode < 128 ) {
2640  // Assume this is a lowercase/uncased ASCII character
2641  return ucfirst( $str );
2642  }
2643 
2644  $first = mb_substr( $str, 0, 1 );
2645  return ( strlen( $first ) !== 1 )
2646  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2647  ? $this->mbUpperChar( $first ) . mb_substr( $str, 1 )
2648  // Assume this is a non-multibyte character and LC_CASE is appropriate
2649  : ucfirst( $str );
2650  }
2651 
2657  public function uc( $str, $first = false ) {
2658  if ( $first ) {
2659  return $this->ucfirst( $str );
2660  } else {
2661  return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2662  }
2663  }
2664 
2678  protected function mbUpperChar( $char ) {
2679  $overrideUcfirstCharacters = MediaWikiServices::getInstance()
2680  ->getMainConfig()->get( 'OverrideUcfirstCharacters' );
2681 
2682  return $overrideUcfirstCharacters[$char] ?? mb_strtoupper( $char );
2683  }
2684 
2689  public function lcfirst( $str ) {
2690  $octetCode = ord( $str );
2691  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2692  if ( $octetCode < 96 ) {
2693  // Assume this is an uppercase/uncased ASCII character
2694  return lcfirst( $str );
2695  } elseif ( $octetCode < 128 ) {
2696  // Assume this is a lowercase/uncased ASCII character
2697  return (string)$str;
2698  }
2699 
2700  return $this->isMultibyte( $str )
2701  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2702  ? mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 )
2703  // Assume this is a non-multibyte character and LC_CASE is appropriate
2704  : lcfirst( $str );
2705  }
2706 
2712  public function lc( $str, $first = false ) {
2713  if ( $first ) {
2714  return $this->lcfirst( $str );
2715  } else {
2716  return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2717  }
2718  }
2719 
2724  private function isMultibyte( $str ) {
2725  return strlen( $str ) !== mb_strlen( $str );
2726  }
2727 
2732  public function ucwords( $str ) {
2733  if ( $this->isMultibyte( $str ) ) {
2734  $str = $this->lc( $str );
2735 
2736  // regexp to find first letter in each word (i.e. after each space)
2737  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2738 
2739  // function to use to capitalize a single char
2740  return preg_replace_callback(
2741  $replaceRegexp,
2742  static function ( $matches ) {
2743  return mb_strtoupper( $matches[0] );
2744  },
2745  $str
2746  );
2747  } else {
2748  return ucwords( strtolower( $str ) );
2749  }
2750  }
2751 
2758  public function ucwordbreaks( $str ) {
2759  if ( $this->isMultibyte( $str ) ) {
2760  $str = $this->lc( $str );
2761 
2762  // since \b doesn't work for UTF-8, we explicitely define word break chars
2763  $breaks = "[ \-\‍(\‍)\}\{\.,\?!]";
2764 
2765  // find first letter after word break
2766  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2767  "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2768 
2769  return preg_replace_callback(
2770  $replaceRegexp,
2771  static function ( $matches ) {
2772  return mb_strtoupper( $matches[0] );
2773  },
2774  $str
2775  );
2776  } else {
2777  return preg_replace_callback(
2778  '/\b([\w\x80-\xff]+)\b/',
2779  function ( $matches ) {
2780  return $this->ucfirst( $matches[1] );
2781  },
2782  $str
2783  );
2784  }
2785  }
2786 
2802  public function caseFold( $s ) {
2803  return $this->uc( $s );
2804  }
2805 
2811  public function checkTitleEncoding( $s ) {
2812  if ( is_array( $s ) ) {
2813  throw new MWException( 'Given array to checkTitleEncoding.' );
2814  }
2815  if ( StringUtils::isUtf8( $s ) ) {
2816  return $s;
2817  }
2818 
2819  return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2820  }
2821 
2825  public function fallback8bitEncoding() {
2826  return $this->localisationCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2827  }
2828 
2837  public function hasWordBreaks() {
2838  return true;
2839  }
2840 
2848  public function segmentByWord( $string ) {
2849  return $string;
2850  }
2851 
2859  public function normalizeForSearch( $string ) {
2860  return self::convertDoubleWidth( $string );
2861  }
2862 
2871  protected static function convertDoubleWidth( $string ) {
2872  static $full = null;
2873  static $half = null;
2874 
2875  if ( $full === null ) {
2876  $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2877  $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2878  $full = str_split( $fullWidth, 3 );
2879  $half = str_split( $halfWidth );
2880  }
2881 
2882  $string = str_replace( $full, $half, $string );
2883  return $string;
2884  }
2885 
2891  protected static function insertSpace( $string, $pattern ) {
2892  $string = preg_replace( $pattern, " $1 ", $string );
2893  $string = preg_replace( '/ +/', ' ', $string );
2894  return $string;
2895  }
2896 
2901  public function convertForSearchResult( $termsArray ) {
2902  # some languages, e.g. Chinese, need to do a conversion
2903  # in order for search results to be displayed correctly
2904  return $termsArray;
2905  }
2906 
2913  public function firstChar( $s ) {
2914  $firstChar = mb_substr( $s, 0, 1 );
2915 
2916  if ( $firstChar === '' || strlen( $firstChar ) != 3 ) {
2917  return $firstChar;
2918  }
2919 
2920  // Break down Hangul syllables to grab the first jamo
2921  $code = mb_ord( $firstChar );
2922  if ( $code < 0xac00 || $code >= 0xd7a4 ) {
2923  return $firstChar;
2924  } elseif ( $code < 0xb098 ) {
2925  return "\u{3131}";
2926  } elseif ( $code < 0xb2e4 ) {
2927  return "\u{3134}";
2928  } elseif ( $code < 0xb77c ) {
2929  return "\u{3137}";
2930  } elseif ( $code < 0xb9c8 ) {
2931  return "\u{3139}";
2932  } elseif ( $code < 0xbc14 ) {
2933  return "\u{3141}";
2934  } elseif ( $code < 0xc0ac ) {
2935  return "\u{3142}";
2936  } elseif ( $code < 0xc544 ) {
2937  return "\u{3145}";
2938  } elseif ( $code < 0xc790 ) {
2939  return "\u{3147}";
2940  } elseif ( $code < 0xcc28 ) {
2941  return "\u{3148}";
2942  } elseif ( $code < 0xce74 ) {
2943  return "\u{314A}";
2944  } elseif ( $code < 0xd0c0 ) {
2945  return "\u{314B}";
2946  } elseif ( $code < 0xd30c ) {
2947  return "\u{314C}";
2948  } elseif ( $code < 0xd558 ) {
2949  return "\u{314D}";
2950  } else {
2951  return "\u{314E}";
2952  }
2953  }
2954 
2964  public function normalize( $s ) {
2965  $allUnicodeFixes = MediaWikiServices::getInstance()->getMainConfig()->get( 'AllUnicodeFixes' );
2966 
2967  $s = UtfNormal\Validator::cleanUp( $s );
2968  // Optimization: This is disabled by default to avoid negative performance impact.
2969  if ( $allUnicodeFixes ) {
2970  $s = $this->transformUsingPairFile( MediaWiki\Languages\Data\NormalizeAr::class, $s );
2971  $s = $this->transformUsingPairFile( MediaWiki\Languages\Data\NormalizeMl::class, $s );
2972  }
2973 
2974  return $s;
2975  }
2976 
2988  protected function transformUsingPairFile( string $dataClass, string $input ): string {
2989  if ( !isset( $this->transformData[$dataClass] ) ) {
2990  $this->transformData[$dataClass] = new ReplacementArray( $dataClass::PAIRS );
2991  }
2992 
2993  return $this->transformData[$dataClass]->replace( $input );
2994  }
2995 
3001  public function isRTL() {
3002  return $this->localisationCache->getItem( $this->mCode, 'rtl' );
3003  }
3004 
3009  public function getDir() {
3010  return $this->isRTL() ? 'rtl' : 'ltr';
3011  }
3012 
3021  public function alignStart() {
3022  return $this->isRTL() ? 'right' : 'left';
3023  }
3024 
3033  public function alignEnd() {
3034  return $this->isRTL() ? 'left' : 'right';
3035  }
3036 
3048  public function getDirMarkEntity( $opposite = false ) {
3049  if ( $opposite ) {
3050  return $this->isRTL() ? '&lrm;' : '&rlm;';
3051  }
3052  return $this->isRTL() ? '&rlm;' : '&lrm;';
3053  }
3054 
3065  public function getDirMark( $opposite = false ) {
3066  $lrm = "\u{200E}"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3067  $rlm = "\u{200F}"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3068  if ( $opposite ) {
3069  return $this->isRTL() ? $lrm : $rlm;
3070  }
3071  return $this->isRTL() ? $rlm : $lrm;
3072  }
3073 
3081  public function getArrow( $direction = 'forwards' ) {
3082  switch ( $direction ) {
3083  case 'forwards':
3084  return $this->isRTL() ? '←' : '→';
3085  case 'backwards':
3086  return $this->isRTL() ? '→' : '←';
3087  case 'left':
3088  return '←';
3089  case 'right':
3090  return '→';
3091  case 'up':
3092  return '↑';
3093  case 'down':
3094  return '↓';
3095  }
3096  }
3097 
3103  public function linkPrefixExtension() {
3104  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixExtension' );
3105  }
3106 
3111  public function getMagicWords() {
3112  return $this->localisationCache->getItem( $this->mCode, 'magicWords' );
3113  }
3114 
3120  public function getMagic( $mw ) {
3121  $rawEntry = $this->mMagicExtensions[$mw->mId] ??
3122  $this->localisationCache->getSubitem( $this->mCode, 'magicWords', $mw->mId );
3123 
3124  if ( !is_array( $rawEntry ) ) {
3125  wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3126  } else {
3127  $mw->mCaseSensitive = $rawEntry[0];
3128  $mw->mSynonyms = array_slice( $rawEntry, 1 );
3129  }
3130  }
3131 
3137  public function getSpecialPageAliases() {
3138  // Cache aliases because it may be slow to load them
3139  if ( $this->mExtendedSpecialPageAliases === null ) {
3140  // Initialise array
3141  $this->mExtendedSpecialPageAliases =
3142  $this->localisationCache->getItem( $this->mCode, 'specialPageAliases' );
3143  }
3144 
3145  return $this->mExtendedSpecialPageAliases;
3146  }
3147 
3154  public function emphasize( $text ) {
3155  return "<em>$text</em>";
3156  }
3157 
3180  public function formatNum( $number, $noSeparators = null ) {
3181  if ( $noSeparators !== null ) {
3182  wfDeprecated( __METHOD__ . ' with $noSeparators parameter', '1.36' );
3183  } else {
3184  // The legacy default value.
3185  $noSeparators = false;
3186  }
3187  return $this->formatNumInternal( (string)$number, false, $noSeparators );
3188  }
3189 
3199  private function formatNumInternal(
3200  string $number, bool $noTranslate, bool $noSeparators
3201  ): string {
3202  $translateNumerals = MediaWikiServices::getInstance()->getMainConfig()->get( 'TranslateNumerals' );
3203 
3204  if ( $number === '' ) {
3205  return $number;
3206  }
3207  if ( $number === (string)NAN ) {
3208  return $this->msg( 'formatnum-nan' )->text();
3209  }
3210  if ( $number === (string)INF ) {
3211  return "∞";
3212  }
3213  if ( $number === (string)-INF ) {
3214  return "\u{2212}∞";
3215  }
3216  if ( !is_numeric( $number ) ) {
3217  # T267587: downgrade this to level:warn while we chase down the long
3218  # trail of callers.
3219  # wfDeprecated( 'Language::formatNum with a non-numeric string', '1.36' );
3220  LoggerFactory::getInstance( 'formatnum' )->warning(
3221  'Language::formatNum with non-numeric string',
3222  [ 'number' => $number ]
3223  );
3224  $validNumberRe = '(-(?=[\d\.]))?(\d+|(?=\.\d))(\.\d*)?([Ee][-+]?\d+)?';
3225  // For backwards-compat, apply formatNum piecewise on the valid
3226  // numbers in the string. Don't split on NAN/INF in this legacy
3227  // case as they are likely to be found embedded inside non-numeric
3228  // text.
3229  return preg_replace_callback( "/{$validNumberRe}/", function ( $m ) use ( $noTranslate, $noSeparators ) {
3230  return $this->formatNumInternal( $m[0], $noTranslate, $noSeparators );
3231  }, $number );
3232  }
3233 
3234  if ( !$noSeparators ) {
3235  $separatorTransformTable = $this->separatorTransformTable();
3236  $digitGroupingPattern = $this->digitGroupingPattern();
3237  $code = $this->getCode();
3238  if ( !( $translateNumerals && $this->langNameUtils->isValidCode( $code ) ) ) {
3239  $code = 'C'; // POSIX system default locale
3240  }
3241 
3242  if ( $digitGroupingPattern ) {
3243  $fmt = new NumberFormatter(
3244  $code, NumberFormatter::PATTERN_DECIMAL, $digitGroupingPattern
3245  );
3246  } else {
3248  $fmt = new NumberFormatter( $code, NumberFormatter::DECIMAL );
3249  }
3250 
3251  // minimumGroupingDigits can be used to suppress groupings below a certain value.
3252  // This is used for languages such as Polish, where one would only write the grouping
3253  // separator for values above 9999 - numbers with more than 4 digits.
3254  // NumberFormatter is yet to support minimumGroupingDigits, ICU has it as experimental feature.
3255  // The attribute value is used by adding it to the grouping separator value. If
3256  // the input number has fewer integer digits, the grouping separator is suppressed.
3257  $minimumGroupingDigits = $this->minimumGroupingDigits() ?? 0;
3258  // Minimum length of a number to do digit grouping on.
3259  // http://unicode.org/reports/tr35/tr35-numbers.html#Examples_of_minimumGroupingDigits
3260  $minimumLength = $minimumGroupingDigits + $fmt->getAttribute( NumberFormatter::GROUPING_SIZE );
3261  if ( $minimumGroupingDigits && !preg_match( '/^\-?\d{' . $minimumLength . '}/', $number ) ) {
3262  // Even if number does not need commafy, do decimal
3263  // separator transformation. For example 1234.56 becomes
3264  // 1234,56 in pl with $minimumGroupingDigits = 2
3265  if ( !$noTranslate ) {
3266  $number = strtr( $number, $separatorTransformTable ?: [] );
3267  }
3268  } elseif ( $number === '-0' ) {
3269  // Special case to ensure we don't lose the minus sign by
3270  // converting to an int.
3271  if ( !$noTranslate ) {
3272  $number = strtr( $number, $separatorTransformTable ?: [] );
3273  }
3274  } else {
3275  // NumberFormatter supports separator transformation,
3276  // but it does not know all languages MW
3277  // supports. Example: arq. Also, languages like pl has
3278  // customisation. So manually set it.
3279  if ( $noTranslate ) {
3280  $fmt->setSymbol(
3281  NumberFormatter::DECIMAL_SEPARATOR_SYMBOL,
3282  '.'
3283  );
3284  $fmt->setSymbol(
3285  NumberFormatter::GROUPING_SEPARATOR_SYMBOL,
3286  ','
3287  );
3288  } elseif ( $separatorTransformTable ) {
3289  $fmt->setSymbol(
3290  NumberFormatter::DECIMAL_SEPARATOR_SYMBOL,
3291  $separatorTransformTable[ '.' ] ?? '.'
3292  );
3293  $fmt->setSymbol(
3294  NumberFormatter::GROUPING_SEPARATOR_SYMBOL,
3295  $separatorTransformTable[ ',' ] ?? ','
3296  );
3297  }
3298 
3299  // Maintain # of digits before and after the decimal point
3300  // (and presence of decimal point)
3301  if ( preg_match( '/^-?(\d*)(\.(\d*))?$/', $number, $m ) ) {
3302  $fmt->setAttribute( NumberFormatter::MIN_INTEGER_DIGITS, strlen( $m[1] ) );
3303  if ( isset( $m[2] ) ) {
3304  $fmt->setAttribute( NumberFormatter::DECIMAL_ALWAYS_SHOWN, true );
3305  }
3306  $fmt->setAttribute( NumberFormatter::FRACTION_DIGITS, strlen( $m[3] ?? '' ) );
3307  }
3308  $number = $fmt->format( $number );
3309  }
3310  }
3311 
3312  if ( !$noTranslate ) {
3313  if ( $translateNumerals ) {
3314  // This is often unnecessary: PHP's NumberFormatter will often
3315  // do the digit transform itself (T267614)
3316  $s = $this->digitTransformTable();
3317  if ( $s ) {
3318  $number = strtr( $number, $s );
3319  }
3320  }
3321  # T10327: Make our formatted numbers prettier by using a
3322  # proper Unicode 'minus' character.
3323  $number = strtr( $number, [ '-' => "\u{2212}" ] );
3324  }
3325 
3326  // Remove any LRM or RLM characters generated from NumberFormatter,
3327  // since directionality is handled outside of this context.
3328  // Similarly remove \u61C, the "Arabic Letter mark" (unicode 6.3.0)
3329  // https://en.wikipedia.org/wiki/Arabic_letter_mark
3330  // which is added starting PHP 7.3+
3331  $number = strtr( $number, [
3332  "\u{200E}" => '', // LRM
3333  "\u{200F}" => '', // RLM
3334  "\u{061C}" => '', // ALM
3335  ] );
3336 
3337  return $number;
3338  }
3339 
3348  public function formatNumNoSeparators( $number ) {
3349  return $this->formatNumInternal( (string)$number, false, true );
3350  }
3351 
3356  public function parseFormattedNumber( $number ) {
3357  if ( $number === $this->msg( 'formatnum-nan' )->text() ) {
3358  return (string)NAN;
3359  }
3360  if ( $number === "∞" ) {
3361  return (string)INF;
3362  }
3363  // Accept either ASCII hyphen-minus or the unicode minus emitted by
3364  // ::formatNum()
3365  $number = strtr( $number, [ "\u{2212}" => '-' ] );
3366  if ( $number === "-∞" ) {
3367  return (string)-INF;
3368  }
3369  $s = $this->digitTransformTable();
3370  if ( $s ) {
3371  // eliminate empty array values such as ''. (T66347)
3372  $s = array_filter( $s );
3373  $number = strtr( $number, array_flip( $s ) );
3374  }
3375 
3376  $s = $this->separatorTransformTable();
3377  if ( $s ) {
3378  // eliminate empty array values such as ''. (T66347)
3379  $s = array_filter( $s );
3380  $number = strtr( $number, array_flip( $s ) );
3381  }
3382 
3383  $number = strtr( $number, [ ',' => '' ] );
3384  return $number;
3385  }
3386 
3399  public function commafy( $number ) {
3400  wfDeprecated( __METHOD__, '1.36' );
3401  // Validate the input argument.
3402  if ( $number === null || $number === '' ) {
3403  return '';
3404  }
3405  return $this->formatNumInternal( $number, true, false );
3406  }
3407 
3411  public function digitGroupingPattern() {
3412  return $this->localisationCache->getItem( $this->mCode, 'digitGroupingPattern' );
3413  }
3414 
3418  public function digitTransformTable() {
3419  return $this->localisationCache->getItem( $this->mCode, 'digitTransformTable' );
3420  }
3421 
3425  public function separatorTransformTable() {
3426  return $this->localisationCache->getItem( $this->mCode, 'separatorTransformTable' );
3427  }
3428 
3432  public function minimumGroupingDigits() {
3433  return $this->localisationCache->getItem( $this->mCode, 'minimumGroupingDigits' );
3434  }
3435 
3444  public function listToText( array $list ) {
3445  $itemCount = count( $list );
3446  if ( $itemCount < 1 ) {
3447  return '';
3448  }
3449  $text = array_pop( $list );
3450  if ( $itemCount > 1 ) {
3451  $and = $this->msg( 'and' )->escaped();
3452  $space = $this->msg( 'word-separator' )->escaped();
3453  $comma = '';
3454  if ( $itemCount > 2 ) {
3455  $comma = $this->msg( 'comma-separator' )->escaped();
3456  }
3457  $text = implode( $comma, $list ) . $and . $space . $text;
3458  }
3459  return $text;
3460  }
3461 
3468  public function commaList( array $list ) {
3469  return implode(
3470  wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3471  $list
3472  );
3473  }
3474 
3481  public function semicolonList( array $list ) {
3482  return implode(
3483  wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3484  $list
3485  );
3486  }
3487 
3493  public function pipeList( array $list ) {
3494  return implode(
3495  wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3496  $list
3497  );
3498  }
3499 
3515  public function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3516  return $this->truncateInternal(
3517  $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
3518  );
3519  }
3520 
3539  public function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3540  // Passing encoding to mb_strlen and mb_substr is optional.
3541  // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
3542  // explicit specification of encoding is skipped.
3543  // Note: Both multibyte methods are callables invoked in truncateInternal.
3544  return $this->truncateInternal(
3545  $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
3546  );
3547  }
3548 
3565  private function truncateInternal(
3566  $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring
3567  ) {
3568  # Check if there is no need to truncate
3569  if ( $measureLength( $string ) <= abs( $length ) ) {
3570  return $string; // no need to truncate
3571  }
3572 
3573  # Use the localized ellipsis character
3574  if ( $ellipsis == '...' ) {
3575  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3576  }
3577  if ( $length == 0 ) {
3578  return $ellipsis; // convention
3579  }
3580 
3581  $stringOriginal = $string;
3582  # If ellipsis length is >= $length then we can't apply $adjustLength
3583  if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
3584  $string = $ellipsis; // this can be slightly unexpected
3585  # Otherwise, truncate and add ellipsis...
3586  } else {
3587  $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
3588  if ( $length > 0 ) {
3589  $length -= $ellipsisLength;
3590  $string = $getSubstring( $string, 0, $length ); // xyz...
3591  $string = $this->removeBadCharLast( $string );
3592  $string = rtrim( $string ) . $ellipsis;
3593  } else {
3594  $length += $ellipsisLength;
3595  $string = $getSubstring( $string, $length ); // ...xyz
3596  $string = $this->removeBadCharFirst( $string );
3597  $string = $ellipsis . ltrim( $string );
3598  }
3599  }
3600 
3601  # Do not truncate if the ellipsis makes the string longer/equal (T24181).
3602  # This check is *not* redundant if $adjustLength, due to the single case where
3603  # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3604  if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
3605  return $string;
3606  } else {
3607  return $stringOriginal;
3608  }
3609  }
3610 
3618  protected function removeBadCharLast( $string ) {
3619  if ( $string != '' ) {
3620  $char = ord( $string[strlen( $string ) - 1] );
3621  $m = [];
3622  if ( $char >= 0xc0 ) {
3623  # We got the first byte only of a multibyte char; remove it.
3624  $string = substr( $string, 0, -1 );
3625  } elseif ( $char >= 0x80 &&
3626  // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3627  preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3628  '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3629  ) {
3630  # We chopped in the middle of a character; remove it
3631  $string = $m[1];
3632  }
3633  }
3634  return $string;
3635  }
3636 
3644  protected function removeBadCharFirst( $string ) {
3645  if ( $string != '' ) {
3646  $char = ord( $string[0] );
3647  if ( $char >= 0x80 && $char < 0xc0 ) {
3648  # We chopped in the middle of a character; remove the whole thing
3649  $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3650  }
3651  }
3652  return $string;
3653  }
3654 
3670  public function truncateHtml( $text, $length, $ellipsis = '...' ) {
3671  # Use the localized ellipsis character
3672  if ( $ellipsis == '...' ) {
3673  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3674  }
3675  # Check if there is clearly no need to truncate
3676  if ( $length <= 0 ) {
3677  return $ellipsis; // no text shown, nothing to format (convention)
3678  } elseif ( strlen( $text ) <= $length ) {
3679  return $text; // string short enough even *with* HTML (short-circuit)
3680  }
3681 
3682  $dispLen = 0; // innerHTML legth so far
3683  $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3684  $tagType = 0; // 0-open, 1-close
3685  $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3686  $entityState = 0; // 0-not entity, 1-entity
3687  $tag = $ret = ''; // accumulated tag name, accumulated result string
3688  $openTags = []; // open tag stack
3689  $maybeState = null; // possible truncation state
3690 
3691  $textLen = strlen( $text );
3692  $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3693  for ( $pos = 0; true; ++$pos ) {
3694  # Consider truncation once the display length has reached the maximim.
3695  # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3696  # Check that we're not in the middle of a bracket/entity...
3697  if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3698  if ( !$testingEllipsis ) {
3699  $testingEllipsis = true;
3700  # Save where we are; we will truncate here unless there turn out to
3701  # be so few remaining characters that truncation is not necessary.
3702  if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3703  $maybeState = [ $ret, $openTags ]; // save state
3704  }
3705  } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3706  # String in fact does need truncation, the truncation point was OK.
3707  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
3708  list( $ret, $openTags ) = $maybeState; // reload state
3709  $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3710  $ret .= $ellipsis; // add ellipsis
3711  break;
3712  }
3713  }
3714  if ( $pos >= $textLen ) {
3715  break; // extra iteration just for above checks
3716  }
3717 
3718  # Read the next char...
3719  $ch = $text[$pos];
3720  $lastCh = $pos ? $text[$pos - 1] : '';
3721  $ret .= $ch; // add to result string
3722  if ( $ch == '<' ) {
3723  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3724  $entityState = 0; // for bad HTML
3725  $bracketState = 1; // tag started (checking for backslash)
3726  } elseif ( $ch == '>' ) {
3727  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3728  $entityState = 0; // for bad HTML
3729  $bracketState = 0; // out of brackets
3730  } elseif ( $bracketState == 1 ) {
3731  if ( $ch == '/' ) {
3732  $tagType = 1; // close tag (e.g. "</span>")
3733  } else {
3734  $tagType = 0; // open tag (e.g. "<span>")
3735  $tag .= $ch;
3736  }
3737  $bracketState = 2; // building tag name
3738  } elseif ( $bracketState == 2 ) {
3739  if ( $ch != ' ' ) {
3740  $tag .= $ch;
3741  } else {
3742  // Name found (e.g. "<a href=..."), add on tag attributes...
3743  $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3744  }
3745  } elseif ( $bracketState == 0 ) {
3746  if ( $entityState ) {
3747  if ( $ch == ';' ) {
3748  $entityState = 0;
3749  $dispLen++; // entity is one displayed char
3750  }
3751  } else {
3752  if ( $neLength == 0 && !$maybeState ) {
3753  // Save state without $ch. We want to *hit* the first
3754  // display char (to get tags) but not *use* it if truncating.
3755  $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3756  }
3757  if ( $ch == '&' ) {
3758  $entityState = 1; // entity found, (e.g. "&#160;")
3759  } else {
3760  $dispLen++; // this char is displayed
3761  // Add the next $max display text chars after this in one swoop...
3762  $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3763  $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3764  $dispLen += $skipped;
3765  $pos += $skipped;
3766  }
3767  }
3768  }
3769  }
3770  // Close the last tag if left unclosed by bad HTML
3771  $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3772  while ( count( $openTags ) > 0 ) {
3773  $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3774  }
3775  return $ret;
3776  }
3777 
3789  private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3790  if ( $len === null ) {
3791  // -1 means "no limit" for strcspn
3792  $len = -1;
3793  } elseif ( $len < 0 ) {
3794  $len = 0;
3795  }
3796  $skipCount = 0;
3797  if ( $start < strlen( $text ) ) {
3798  $skipCount = strcspn( $text, $search, $start, $len );
3799  $ret .= substr( $text, $start, $skipCount );
3800  }
3801  return $skipCount;
3802  }
3803 
3813  private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3814  $tag = ltrim( $tag );
3815  if ( $tag != '' ) {
3816  if ( $tagType == 0 && $lastCh != '/' ) {
3817  $openTags[] = $tag; // tag opened (didn't close itself)
3818  } elseif ( $tagType == 1 ) {
3819  if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3820  array_pop( $openTags ); // tag closed
3821  }
3822  }
3823  $tag = '';
3824  }
3825  }
3826 
3835  public function convertGrammar( $word, $case ) {
3836  $grammarForms = MediaWikiServices::getInstance()->getMainConfig()->get( 'GrammarForms' );
3837  if ( isset( $grammarForms[$this->getCode()][$case][$word] ) ) {
3838  return $grammarForms[$this->getCode()][$case][$word];
3839  }
3840 
3841  $grammarTransformations = $this->getGrammarTransformations();
3842 
3843  if ( isset( $grammarTransformations[$case] ) ) {
3844  $forms = $grammarTransformations[$case];
3845 
3846  // Some names of grammar rules are aliases for other rules.
3847  // In such cases the value is a string rather than object,
3848  // so load the actual rules.
3849  if ( is_string( $forms ) ) {
3850  $forms = $grammarTransformations[$forms];
3851  }
3852 
3853  foreach ( array_values( $forms ) as $rule ) {
3854  $form = $rule[0];
3855 
3856  if ( $form === '@metadata' ) {
3857  continue;
3858  }
3859 
3860  $replacement = $rule[1];
3861 
3862  $regex = '/' . addcslashes( $form, '/' ) . '/u';
3863  $patternMatches = preg_match( $regex, $word );
3864 
3865  if ( $patternMatches === false ) {
3866  wfLogWarning(
3867  'An error occurred while processing grammar. ' .
3868  "Word: '$word'. Regex: /$form/."
3869  );
3870  } elseif ( $patternMatches === 1 ) {
3871  $word = preg_replace( $regex, $replacement, $word );
3872 
3873  break;
3874  }
3875  }
3876  }
3877 
3878  return $word;
3879  }
3880 
3886  public function getGrammarForms() {
3887  $grammarForms = MediaWikiServices::getInstance()->getMainConfig()->get( 'GrammarForms' );
3888  if ( isset( $grammarForms[$this->getCode()] )
3889  && is_array( $grammarForms[$this->getCode()] )
3890  ) {
3891  return $grammarForms[$this->getCode()];
3892  }
3893 
3894  return [];
3895  }
3896 
3906  public function getGrammarTransformations() {
3907  global $IP;
3908  if ( $this->grammarTransformCache !== null ) {
3909  return $this->grammarTransformCache;
3910  }
3911 
3912  $grammarDataFile = $IP . "/languages/data/grammarTransformations/{$this->getCode()}.json";
3913  $this->grammarTransformCache = is_readable( $grammarDataFile )
3914  ? FormatJson::decode( file_get_contents( $grammarDataFile ), true )
3915  : [];
3916 
3917  if ( $this->grammarTransformCache === null ) {
3918  throw new MWException( "Invalid grammar data for \"{$this->getCode()}\"." );
3919  }
3920 
3921  return $this->grammarTransformCache;
3922  }
3923 
3943  public function gender( $gender, $forms ) {
3944  if ( !count( $forms ) ) {
3945  return '';
3946  }
3947  $forms = $this->preConvertPlural( $forms, 2 );
3948  if ( $gender === 'male' ) {
3949  return $forms[0];
3950  }
3951  if ( $gender === 'female' ) {
3952  return $forms[1];
3953  }
3954  return $forms[2] ?? $forms[0];
3955  }
3956 
3972  public function convertPlural( $count, $forms ) {
3973  // Handle explicit n=pluralform cases
3974  $forms = $this->handleExplicitPluralForms( $count, $forms );
3975  if ( is_string( $forms ) ) {
3976  return $forms;
3977  }
3978  if ( !count( $forms ) ) {
3979  return '';
3980  }
3981 
3982  $pluralForm = $this->getPluralRuleIndexNumber( $count );
3983  $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3984  return $forms[$pluralForm];
3985  }
3986 
4002  protected function handleExplicitPluralForms( $count, array $forms ) {
4003  foreach ( $forms as $index => $form ) {
4004  if ( preg_match( '/\d+=/i', $form ) ) {
4005  $pos = strpos( $form, '=' );
4006  if ( substr( $form, 0, $pos ) === (string)$count ) {
4007  return substr( $form, $pos + 1 );
4008  }
4009  unset( $forms[$index] );
4010  }
4011  }
4012  return array_values( $forms );
4013  }
4014 
4023  protected function preConvertPlural( /* Array */ $forms, $count ) {
4024  return array_pad( $forms, $count, end( $forms ) );
4025  }
4026 
4043  public function embedBidi( $text = '' ) {
4044  $dir = self::strongDirFromContent( $text );
4045  if ( $dir === 'ltr' ) {
4046  // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
4047  return self::LRE . $text . self::PDF;
4048  }
4049  if ( $dir === 'rtl' ) {
4050  // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
4051  return self::RLE . $text . self::PDF;
4052  }
4053  // No strong directionality: do not wrap
4054  return $text;
4055  }
4056 
4070  public function translateBlockExpiry( $str, UserIdentity $user = null, $now = 0 ) {
4071  $duration = SpecialBlock::getSuggestedDurations( $this );
4072  foreach ( $duration as $show => $value ) {
4073  if ( strcmp( $str, $value ) == 0 ) {
4074  return trim( $show );
4075  }
4076  }
4077 
4078  if ( wfIsInfinity( $str ) ) {
4079  foreach ( $duration as $show => $value ) {
4080  if ( wfIsInfinity( $value ) ) {
4081  return trim( $show );
4082  }
4083  }
4084  }
4085 
4086  // If all else fails, return a standard duration or timestamp description.
4087  $time = strtotime( $str, $now );
4088  if ( $time === false ) { // Unknown format. Return it as-is in case.
4089  return $str;
4090  } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
4091  // The result differs based on current time, so the difference
4092  // is a fixed duration length.
4093  return $this->formatDuration( $time - $now );
4094  } else { // It's an absolute timestamp.
4095  if ( $time === 0 ) {
4096  // wfTimestamp() handles 0 as current time instead of epoch.
4097  $time = '19700101000000';
4098  }
4099  if ( $user ) {
4100  return $this->userTimeAndDate( $time, $user );
4101  }
4102  return $this->timeanddate( $time );
4103  }
4104  }
4105 
4113  public function segmentForDiff( $text ) {
4114  return $text;
4115  }
4116 
4123  public function unsegmentForDiff( $text ) {
4124  return $text;
4125  }
4126 
4136  public function getConverter(): ILanguageConverter {
4137  return $this->converterFactory->getLanguageConverter( $this );
4138  }
4139 
4150  public function autoConvert( $text, $variant = false ) {
4151  return $this->getConverter()->autoConvert( $text, $variant );
4152  }
4153 
4162  public function autoConvertToAllVariants( $text ) {
4163  return $this->getConverter()->autoConvertToAllVariants( $text );
4164  }
4165 
4180  public function convert( $text ) {
4181  return $this->getConverter()->convert( $text );
4182  }
4183 
4194  public function convertNamespace( $ns, $variant = null ) {
4195  return $this->getConverter()->convertNamespace( $ns, $variant );
4196  }
4197 
4205  public function hasVariants() {
4206  return count( $this->getVariants() ) > 1;
4207  }
4208 
4221  public function hasVariant( $variant ) {
4222  return $this->getConverter()->hasVariant( $variant );
4223  }
4224 
4234  public function convertHtml( $text ) {
4235  return htmlspecialchars( $this->convert( $text ) );
4236  }
4237 
4244  public function convertCategoryKey( $key ) {
4245  return $this->getConverter()->convertCategoryKey( $key );
4246  }
4247 
4256  public function getVariants() {
4257  return $this->getConverter()->getVariants();
4258  }
4259 
4264  public function getPreferredVariant() {
4265  return $this->getConverter()->getPreferredVariant();
4266  }
4267 
4272  public function getDefaultVariant() {
4273  return $this->getConverter()->getDefaultVariant();
4274  }
4275 
4280  public function getURLVariant() {
4281  return $this->getConverter()->getURLVariant();
4282  }
4283 
4292  public function getExtraHashOptions() {
4293  return $this->getConverter()->getExtraHashOptions();
4294  }
4295 
4302  public function linkTrail() {
4303  return $this->localisationCache->getItem( $this->mCode, 'linkTrail' );
4304  }
4305 
4312  public function linkPrefixCharset() {
4313  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixCharset' );
4314  }
4315 
4324  public function getParentLanguage() {
4325  return MediaWikiServices::getInstance()->getLanguageFactory()
4326  ->getParentLanguage( $this->getCode() );
4327  }
4328 
4336  public function equals( Language $lang ) {
4337  return $lang === $this || $lang->getCode() === $this->mCode;
4338  }
4339 
4348  public function getCode() {
4349  return $this->mCode;
4350  }
4351 
4362  public function getHtmlCode() {
4363  if ( $this->mHtmlCode === null ) {
4364  $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
4365  }
4366  return $this->mHtmlCode;
4367  }
4368 
4376  public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4377  $m = null;
4378  preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4379  preg_quote( $suffix, '/' ) . '/', $filename, $m );
4380  if ( !count( $m ) ) {
4381  return false;
4382  }
4383  return str_replace( '_', '-', strtolower( $m[1] ) );
4384  }
4385 
4396  public static function getFileName( $prefix, $code, $suffix = '.php' ) {
4397  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4398  ->getFileName( $prefix, $code, $suffix );
4399  }
4400 
4406  public static function getMessagesFileName( $code ) {
4407  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4408  ->getMessagesFileName( $code );
4409  }
4410 
4418  public static function getJsonMessagesFileName( $code ) {
4419  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4420  ->getJsonMessagesFileName( $code );
4421  }
4422 
4431  public static function getFallbackFor( $code ) {
4432  return MediaWikiServices::getInstance()->getLanguageFallback()->getFirst( $code )
4433  ?? false;
4434  }
4435 
4448  public static function getFallbacksFor( $code, $mode = LanguageFallback::MESSAGES ) {
4449  return MediaWikiServices::getInstance()->getLanguageFallback()->getAll( $code, $mode );
4450  }
4451 
4462  public static function getFallbacksIncludingSiteLanguage( $code ) {
4463  return MediaWikiServices::getInstance()->getLanguageFallback()
4464  ->getAllIncludingSiteLanguage( $code );
4465  }
4466 
4478  public static function getMessagesFor( $code ) {
4479  return self::getLocalisationCache()->getItem( $code, 'messages' );
4480  }
4481 
4492  public static function getMessageFor( $key, $code ) {
4493  return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4494  }
4495 
4506  public static function getMessageKeysFor( $code ) {
4507  return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
4508  }
4509 
4514  private function fixVariableInNamespace( $talk ) {
4515  if ( strpos( $talk, '$1' ) === false ) {
4516  return $talk;
4517  }
4518 
4519  $metaNamespace = MediaWikiServices::getInstance()->getMainConfig()->get( 'MetaNamespace' );
4520  $talk = str_replace( '$1', $metaNamespace, $talk );
4521 
4522  # Allow grammar transformations
4523  # Allowing full message-style parsing would make simple requests
4524  # such as action=raw much more expensive than they need to be.
4525  # This will hopefully cover most cases.
4526  $talk = preg_replace_callback(
4527  '/{{grammar:(.*?)\|(.*?)}}/i',
4528  function ( $m ) {
4529  return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4530  },
4531  $talk
4532  );
4533  return str_replace( ' ', '_', $talk );
4534  }
4535 
4548  public function formatExpiry( $expiry, $format = true, $infinity = 'infinity', $user = null ) {
4549  static $dbInfinity;
4550  if ( $dbInfinity === null ) {
4551  $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
4552  }
4553 
4554  if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4555  return $format === true
4556  ? $this->getMessageFromDB( 'infiniteblock' )
4557  : $infinity;
4558  } else {
4559  if ( $format === true ) {
4560  return $user
4561  ? $this->userTimeAndDate( $expiry, $user )
4562  : $this->timeanddate( $expiry, /* User preference timezone */ true );
4563  }
4564  return wfTimestamp( $format, $expiry );
4565  }
4566  }
4567 
4582  public function formatTimePeriod( $seconds, $format = [] ) {
4583  if ( !is_array( $format ) ) {
4584  $format = [ 'avoid' => $format ]; // For backwards compatibility
4585  }
4586  if ( !isset( $format['avoid'] ) ) {
4587  $format['avoid'] = false;
4588  }
4589  if ( !isset( $format['noabbrevs'] ) ) {
4590  $format['noabbrevs'] = false;
4591  }
4592  $secondsMsg = wfMessage(
4593  $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4594  $minutesMsg = wfMessage(
4595  $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4596  $hoursMsg = wfMessage(
4597  $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4598  $daysMsg = wfMessage(
4599  $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4600 
4601  if ( round( $seconds * 10 ) < 100 ) {
4602  $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4603  $s = $secondsMsg->params( $s )->text();
4604  } elseif ( round( $seconds ) < 60 ) {
4605  $s = $this->formatNum( round( $seconds ) );
4606  $s = $secondsMsg->params( $s )->text();
4607  } elseif ( round( $seconds ) < 3600 ) {
4608  $minutes = floor( $seconds / 60 );
4609  $secondsPart = round( fmod( $seconds, 60 ) );
4610  if ( $secondsPart == 60 ) {
4611  $secondsPart = 0;
4612  $minutes++;
4613  }
4614  $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4615  $s .= ' ';
4616  $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4617  } elseif ( round( $seconds ) <= 2 * 86400 ) {
4618  $hours = floor( $seconds / 3600 );
4619  $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4620  $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4621  if ( $secondsPart == 60 ) {
4622  $secondsPart = 0;
4623  $minutes++;
4624  }
4625  if ( $minutes == 60 ) {
4626  $minutes = 0;
4627  $hours++;
4628  }
4629  $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4630  $s .= ' ';
4631  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4632  if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes', 'avoidhours' ] ) ) {
4633  $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4634  }
4635  } else {
4636  $days = floor( $seconds / 86400 );
4637  if ( $format['avoid'] === 'avoidhours' ) {
4638  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4639  if ( $hours == 24 ) {
4640  $hours = 0;
4641  $days++;
4642  }
4643  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4644  } elseif ( $format['avoid'] === 'avoidminutes' ) {
4645  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4646  if ( $hours == 24 ) {
4647  $hours = 0;
4648  $days++;
4649  }
4650  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4651  $s .= ' ';
4652  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4653  } elseif ( $format['avoid'] === 'avoidseconds' ) {
4654  $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4655  $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4656  if ( $minutes == 60 ) {
4657  $minutes = 0;
4658  $hours++;
4659  }
4660  if ( $hours == 24 ) {
4661  $hours = 0;
4662  $days++;
4663  }
4664  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4665  $s .= ' ';
4666  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4667  $s .= ' ';
4668  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4669  } else {
4670  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4671  $s .= ' ';
4672  $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4673  }
4674  }
4675  return $s;
4676  }
4677 
4689  public function formatBitrate( $bps ) {
4690  return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4691  }
4692 
4699  public function formatComputingNumbers( $size, $boundary, $messageKey ) {
4700  if ( $size <= 0 ) {
4701  return str_replace( '$1', $this->formatNum( $size ),
4702  $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4703  );
4704  }
4705  $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'yotta' ];
4706  $index = 0;
4707 
4708  $maxIndex = count( $sizes ) - 1;
4709  while ( $size >= $boundary && $index < $maxIndex ) {
4710  $index++;
4711  $size /= $boundary;
4712  }
4713 
4714  // For small sizes no decimal places necessary
4715  $round = 0;
4716  if ( $index > 1 ) {
4717  // For MB and bigger two decimal places are smarter
4718  $round = 2;
4719  }
4720  $msg = str_replace( '$1', $sizes[$index], $messageKey );
4721 
4722  $size = round( $size, $round );
4723  $text = $this->getMessageFromDB( $msg );
4724  return str_replace( '$1', $this->formatNum( $size ), $text );
4725  }
4726 
4737  public function formatSize( $size ) {
4738  return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4739  }
4740 
4750  public function specialList( $page, $details, $oppositedm = true ) {
4751  if ( !$details ) {
4752  return $page;
4753  }
4754 
4755  $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4756  return $page .
4757  $dirmark .
4758  $this->msg( 'word-separator' )->escaped() .
4759  $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4760  }
4761 
4769  public function getConvRuleTitle() {
4770  return $this->getConverter()->getConvRuleTitle();
4771  }
4772 
4778  public function getCompiledPluralRules() {
4779  $pluralRules =
4780  $this->localisationCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4781  if ( !$pluralRules ) {
4782  $fallbacks = $this->getFallbackLanguages();
4783  foreach ( $fallbacks as $fallbackCode ) {
4784  $pluralRules = $this->localisationCache
4785  ->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4786  if ( $pluralRules ) {
4787  break;
4788  }
4789  }
4790  }
4791  return $pluralRules;
4792  }
4793 
4799  public function getPluralRules() {
4800  $pluralRules =
4801  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4802  if ( !$pluralRules ) {
4803  $fallbacks = $this->getFallbackLanguages();
4804  foreach ( $fallbacks as $fallbackCode ) {
4805  $pluralRules = $this->localisationCache
4806  ->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4807  if ( $pluralRules ) {
4808  break;
4809  }
4810  }
4811  }
4812  return $pluralRules;
4813  }
4814 
4820  public function getPluralRuleTypes() {
4821  $pluralRuleTypes =
4822  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4823  if ( !$pluralRuleTypes ) {
4824  $fallbacks = $this->getFallbackLanguages();
4825  foreach ( $fallbacks as $fallbackCode ) {
4826  $pluralRuleTypes = $this->localisationCache
4827  ->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4828  if ( $pluralRuleTypes ) {
4829  break;
4830  }
4831  }
4832  }
4833  return $pluralRuleTypes;
4834  }
4835 
4841  public function getPluralRuleIndexNumber( $number ) {
4842  $pluralRules = $this->getCompiledPluralRules();
4843  $form = Evaluator::evaluateCompiled( $number, $pluralRules );
4844  return $form;
4845  }
4846 
4855  public function getPluralRuleType( $number ) {
4856  $index = $this->getPluralRuleIndexNumber( $number );
4857  $pluralRuleTypes = $this->getPluralRuleTypes();
4858  return $pluralRuleTypes[$index] ?? 'other';
4859  }
4860 
4867  protected function getHookContainer() {
4868  return $this->hookContainer;
4869  }
4870 
4879  protected function getHookRunner() {
4880  return $this->hookRunner;
4881  }
4882 }
Language\$mCode
$mCode
Definition: Language.php:58
Language\$langFallback
LanguageFallback $langFallback
Definition: Language.php:96
Language\getCodeFromFileName
static getCodeFromFileName( $filename, $prefix='Language', $suffix='.php')
Get the language code from a file name.
Definition: Language.php:4376
Language\getExtraHashOptions
getExtraHashOptions()
returns language specific options used by User::getPageRenderHash() for example, the preferred langua...
Definition: Language.php:4292
Language\lc
lc( $str, $first=false)
Definition: Language.php:2712
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:38
Language\parseFormattedNumber
parseFormattedNumber( $number)
Definition: Language.php:3356
Language\getURLVariant
getURLVariant()
Definition: Language.php:4280
Language\getVariantname
getVariantname( $code, $usemsg=true)
short names for language variants used for language conversion links.
Definition: Language.php:761
Language\$hookContainer
HookContainer $hookContainer
Definition: Language.php:109
Language\getHookRunner
getHookRunner()
Get a HookRunner, for running core hooks.
Definition: Language.php:4879
Language\linkPrefixExtension
linkPrefixExtension()
To allow "foo[[bar]]" to extend the link over the whole word "foobar".
Definition: Language.php:3103
Language\$langNameUtils
LanguageNameUtils $langNameUtils
Definition: Language.php:93
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:3813
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:3468
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:3481
Language\$mMonthAbbrevMsgs
static $mMonthAbbrevMsgs
Definition: Language.php:179
Language\formatSize
formatSize( $size)
Format a size in bytes for output, using an appropriate unit (B, KB, MB, GB, TB, PB,...
Definition: Language.php:4737
Language\separatorTransformTable
separatorTransformTable()
Definition: Language.php:3425
Language\WEEKDAY_ABBREVIATED_MESSAGES
const WEEKDAY_ABBREVIATED_MESSAGES
Definition: Language.php:141
Language\resetNamespaces
resetNamespaces()
Resets all of the namespace caches.
Definition: Language.php:550
Language\getConverter
getConverter()
Return the LanguageConverter used in the Language.
Definition: Language.php:4136
Language\hasVariants
hasVariants()
Check if this is a language with variants.
Definition: Language.php:4205
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:203
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:4023
$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:4234
Language\minimumGroupingDigits
minimumGroupingDigits()
Definition: Language.php:3432
Language\segmentByWord
segmentByWord( $string)
Some languages such as Chinese require word segmentation, Specify such segmentation when overridden i...
Definition: Language.php:2848
Language\$transformData
ReplacementArray[] $transformData
Definition: Language.php:87
Language\iconv
iconv( $in, $out, $string)
Definition: Language.php:2618
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:856
Language\convert
convert( $text)
convert text to different variants of a language.
Definition: Language.php:4180
Language\ALL
const ALL
Return all known languages in fetchLanguageName(s).
Definition: Language.php:48
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:3835
Language\mbUpperChar
mbUpperChar( $char)
Convert character to uppercase, allowing overrides of the default mb_upper behaviour,...
Definition: Language.php:2678
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=LanguageFallback::MESSAGES)
Get the ordered list of fallback languages.
Definition: Language.php:4448
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1649
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:3539
Language\timeanddate
timeanddate( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2256
Language\$grammarTransformCache
array[] null $grammarTransformCache
Definition: Language.php:99
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1167
Language\MESSAGES_FALLBACKS
const MESSAGES_FALLBACKS
Return a fallback chain for messages in getFallbacksFor.
Definition: Language.php:121
Language\$namespaceNames
array null $namespaceNames
Definition: Language.php:81
Language\formatNumInternal
formatNumInternal(string $number, bool $noTranslate, bool $noSeparators)
Internal implementation function, shared between commafy, formatNum, and formatNumNoSeparators.
Definition: Language.php:3199
Language\getPreferredVariant
getPreferredVariant()
Definition: Language.php:4264
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:2415
Language\getDefaultVariant
getDefaultVariant()
Definition: Language.php:4272
Language\fallback8bitEncoding
fallback8bitEncoding()
Definition: Language.php:2825
Language\embedBidi
embedBidi( $text='')
Wraps argument with unicode control characters for directionality safety.
Definition: Language.php:4043
Language\truncateInternal
truncateInternal( $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring)
Internal method used for truncation.
Definition: Language.php:3565
Language\formatTimePeriod
formatTimePeriod( $seconds, $format=[])
Formats a time given in seconds into a string representation of that time.
Definition: Language.php:4582
Language\formatBitrate
formatBitrate( $bps)
Format a bitrate for output, using an appropriate unit (bps, kbps, Mbps, Gbps, Tbps,...
Definition: Language.php:4689
Language\equals
equals(Language $lang)
Compare with an other language object.
Definition: Language.php:4336
Language\SUPPORTED
const SUPPORTED
Return in fetchLanguageName(s) only the languages for which we have at least some localisation.
Definition: Language.php:56
Language\getSpecialPageAliases
getSpecialPageAliases()
Get special page names, as an associative array canonical name => array of valid names,...
Definition: Language.php:3137
Language\getGroupName
getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
Definition: Language.php:2576
Language\__construct
__construct( $code=null, LocalisationCache $localisationCache=null, LanguageNameUtils $langNameUtils=null, LanguageFallback $langFallback=null, LanguageConverterFactory $converterFactory=null, HookContainer $hookContainer=null)
Definition: Language.php:418
Language\getMessagesFileName
static getMessagesFileName( $code)
Definition: Language.php:4406
Language\getPluralRuleTypes
getPluralRuleTypes()
Get the plural rule types for the language.
Definition: Language.php:4820
Language\specialList
specialList( $page, $details, $oppositedm=true)
Make a list item, used by various special pages.
Definition: Language.php:4750
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\checkTitleEncoding
checkTitleEncoding( $s)
TODO: $s is not always a string per T218883.
Definition: Language.php:2811
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:308
Language\getFormattedNamespaces
getFormattedNamespaces()
A convenience function that returns getNamespaces() with spaces instead of underscores in values.
Definition: Language.php:562
Language\lcfirst
lcfirst( $str)
Definition: Language.php:2689
MediaWiki\Languages\LanguageNameUtils
A service that provides utilities to do with language names and codes.
Definition: LanguageNameUtils.php:43
Language\isKnownLanguageTag
static isKnownLanguageTag( $tag)
Returns true if a language code is an IETF tag known to MediaWiki.
Definition: Language.php:395
Language\emphasize
emphasize( $text)
Italic is unsuitable for some languages.
Definition: Language.php:3154
Language\getFallbackLanguages
getFallbackLanguages()
Definition: Language.php:480
Language\getDurationIntervals
getDurationIntervals( $seconds, array $chosenIntervals=[])
Takes a number of seconds and returns an array with a set of corresponding intervals.
Definition: Language.php:2301
Language\caseFold
caseFold( $s)
Return a case-folded representation of $s.
Definition: Language.php:2802
Language\segmentForDiff
segmentForDiff( $text)
languages like Chinese need to be segmented in order for the diff to be of any use
Definition: Language.php:4113
Language\needsGenderDistinction
needsGenderDistinction()
Whether this language uses gender-dependent namespace aliases.
Definition: Language.php:627
getUser
getUser()
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:146
Language\getLocalisationCache
static getLocalisationCache()
Definition: Language.php:404
MWException
MediaWiki exception.
Definition: MWException.php:29
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:997
Language\tsToIranian
static tsToIranian( $ts)
Algorithm by Roozbeh Pournader and Mohammad Toossi to convert Gregorian dates to Iranian dates.
Definition: Language.php:1538
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:4123
Language\autoConvert
autoConvert( $text, $variant=false)
convert text to a variant
Definition: Language.php:4150
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:3670
Language\normalize
normalize( $s)
Convert a UTF-8 string to normal form C.
Definition: Language.php:2964
Language\getBookstoreList
getBookstoreList()
Exports $wgBookstoreListEn.
Definition: Language.php:488
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:2397
Language\DURATION_INTERVALS
const DURATION_INTERVALS
Definition: Language.php:226
Language\pipeList
pipeList(array $list)
Same as commaList, but separate it with the pipe instead.
Definition: Language.php:3493
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2186
Language\convertForSearchResult
convertForSearchResult( $termsArray)
Definition: Language.php:2901
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4492
$matches
$matches
Definition: NoLocalSettings.php:24
Language\getGenderNsText
getGenderNsText( $index, $gender)
Returns gender-dependent namespace alias if available.
Definition: Language.php:612
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:2462
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:3444
Language\getHtmlCode
getHtmlCode()
Get the code in BCP 47 format which we can use inside of html lang="" tags.
Definition: Language.php:4362
Language\getNamespaceAliases
getNamespaceAliases()
Definition: Language.php:662
NS_PROJECT
const NS_PROJECT
Definition: Defines.php:68
Language\$mExtendedSpecialPageAliases
array[] $mExtendedSpecialPageAliases
memoize
Definition: Language.php:78
Language\getLocalNsIndex
getLocalNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:652
MediaWiki
A helper class for throttling authentication attempts.
Language\$mMonthMsgs
static $mMonthMsgs
Definition: Language.php:157
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:3515
Language\getAllMessages
getAllMessages()
Definition: Language.php:2608
Language\getMagic
getMagic( $mw)
Fill a MagicWord object with data from here.
Definition: Language.php:3120
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:2420
Language\isRTL
isRTL()
For right-to-left language support.
Definition: Language.php:3001
Language\getNsIndex
getNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:743
Language\MONTH_GENITIVE_MESSAGES
const MONTH_GENITIVE_MESSAGES
Definition: Language.php:162
Language\getNamespaceIds
getNamespaceIds()
Definition: Language.php:719
Language\getPluralRuleIndexNumber
getPluralRuleIndexNumber( $number)
Find the index number of the plural rule appropriate for the given number.
Definition: Language.php:4841
Language\HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
const HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
Definition: Language.php:205
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:2871
Language\getCompiledPluralRules
getCompiledPluralRules()
Get the compiled plural rules for the language.
Definition: Language.php:4778
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:2504
Language\convertCategoryKey
convertCategoryKey( $key)
Definition: Language.php:4244
Language\digitGroupingPattern
digitGroupingPattern()
Definition: Language.php:3411
Language\$hookRunner
HookRunner $hookRunner
Definition: Language.php:114
Language\ucwords
ucwords( $str)
Definition: Language.php:2732
Language\getPluralRules
getPluralRules()
Get the plural rules for the language.
Definition: Language.php:4799
Language\getArrow
getArrow( $direction='forwards')
An arrow, depending on the language direction.
Definition: Language.php:3081
Language\uc
uc( $str, $first=false)
Definition: Language.php:2657
Language\formatNumNoSeparators
formatNumNoSeparators( $number)
Front-end for non-commafied formatNum.
Definition: Language.php:3348
Language\$mHtmlCode
$mHtmlCode
Definition: Language.php:65
Language\MONTH_ABBREVIATED_MESSAGES
const MONTH_ABBREVIATED_MESSAGES
Definition: Language.php:171
$digitGroupingPattern
$digitGroupingPattern
Definition: MessagesAr.php:473
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:380
Language\$converterFactory
LanguageConverterFactory $converterFactory
Definition: Language.php:104
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:2275
Language\setNamespaces
setNamespaces(array $namespaces)
Arbitrarily set all of the namespace names at once.
Definition: Language.php:542
Language\linkPrefixCharset
linkPrefixCharset()
A regular expression character set to match legal word-prefixing characters which should be merged on...
Definition: Language.php:4312
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
ReplacementArray
Wrapper around strtr() that holds replacements.
Definition: ReplacementArray.php:24
Language\fixVariableInNamespace
fixVariableInNamespace( $talk)
Definition: Language.php:4514
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:29
Language\ucwordbreaks
ucwordbreaks( $str)
capitalize words at word breaks
Definition: Language.php:2758
Language\getNsText
getNsText( $index)
Get a namespace value by key.
Definition: Language.php:581
Language\getCode
getCode()
Get the internal language code for this language object.
Definition: Language.php:4348
Language\LRE
const LRE
Unicode directional formatting characters, for embedBidi()
Definition: Language.php:248
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:4855
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:2149
Language\transformUsingPairFile
transformUsingPairFile(string $dataClass, string $input)
Transform a string using serialized data stored in the given file (which must be in the serialized su...
Definition: Language.php:2988
Language\getGroupMemberName
getGroupMemberName(string $group, $member)
Gets the localized name for a member of a group, if it exists.
Definition: Language.php:2589
Language\hebrewNumeral
static hebrewNumeral( $num)
Hebrew Gematria number formatting up to 9999.
Definition: Language.php:1980
Language\internalUserTimeAndDate
internalUserTimeAndDate( $type, $ts, UserIdentity $user, array $options)
Internal helper function for userDate(), userTime() and userTimeAndDate()
Definition: Language.php:2353
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2514
Language\getFormattedNsText
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with '_' changed to ' ',...
Definition: Language.php:599
Language\getMessagesFor
static getMessagesFor( $code)
Get all messages for a given language WARNING: this may take a long time.
Definition: Language.php:4478
Language\handleExplicitPluralForms
handleExplicitPluralForms( $count, array $forms)
Handles explicit plural forms for Language::convertPlural()
Definition: Language.php:4002
Language\RLE
const RLE
Definition: Language.php:249
Language\getFileName
static getFileName( $prefix, $code, $suffix='.php')
Get the name of a file for a certain language code.
Definition: Language.php:4396
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:148
Language\getHookContainer
getHookContainer()
Get a HookContainer, for hook metadata and running extension hooks.
Definition: Language.php:4867
Language\HEBREW_CALENDAR_MONTHS_MESSAGES
const HEBREW_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:194
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:3065
Language\normalizeForSearch
normalizeForSearch( $string)
Some languages have special punctuation need to be normalized.
Definition: Language.php:2859
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:365
Language\userAdjust
userAdjust( $ts, $tz=false)
Used by date() and time() to adjust the time output.
Definition: Language.php:2067
Language\formatComputingNumbers
formatComputingNumbers( $size, $boundary, $messageKey)
Definition: Language.php:4699
$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:2443
Language\getFallbackFor
static getFallbackFor( $code)
Get the first fallback for a given language.
Definition: Language.php:4431
Language\getParentLanguage
getParentLanguage()
Get the "parent" language which has a converter to convert a "compatible" language (in another varian...
Definition: Language.php:4324
Language\$dateFormatStrings
$dateFormatStrings
memoize
Definition: Language.php:71
Language\hasWordBreaks
hasWordBreaks()
Most writing systems use whitespace to break up words.
Definition: Language.php:2837
Language\getDir
getDir()
Return the correct HTML 'dir' attribute value for this language.
Definition: Language.php:3009
Language\date
date( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2217
Language\alignEnd
alignEnd()
Return 'right' or 'left' as appropriate alignment for line-end for this language's text direction.
Definition: Language.php:3033
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:3789
Language\getVariants
getVariants()
Get the list of variants supported by this language see sample implementation in LanguageZh....
Definition: Language.php:4256
Language\convertPlural
convertPlural( $count, $forms)
Plural form transformations, needed for some languages.
Definition: Language.php:3972
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:4462
Language\getGrammarForms
getGrammarForms()
Get the grammar forms for the content language.
Definition: Language.php:3886
Language\removeBadCharFirst
removeBadCharFirst( $string)
Remove bytes that represent an incomplete Unicode character at the start of string (e....
Definition: Language.php:3644
Language\$strongDirRegex
static $strongDirRegex
Directionality test regex for embedBidi().
Definition: Language.php:265
LanguageCode\bcp47
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: LanguageCode.php:175
Language\getMessage
getMessage( $key)
Definition: Language.php:2601
Language\getGrammarTransformations
getGrammarTransformations()
Get the grammar transformations data for the language.
Definition: Language.php:3906
Language\getMessageKeysFor
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4506
Language\getJsonMessagesFileName
static getJsonMessagesFileName( $code)
Definition: Language.php:4418
Language\IRANIAN_CALENDAR_MONTHS_MESSAGES
const IRANIAN_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:184
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:2913
Language\getNamespaces
getNamespaces()
Returns an array of localised namespaces indexed by their numbers.
Definition: Language.php:498
Language\$localisationCache
LocalisationCache $localisationCache
Definition: Language.php:90
SpecialBlock\getSuggestedDurations
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
Definition: SpecialBlock.php:946
Language\removeBadCharLast
removeBadCharLast( $string)
Remove bytes that represent an incomplete Unicode character at the end of string (e....
Definition: Language.php:3618
Language\romanNumeral
static romanNumeral( $num)
Roman number formatting up to 10000.
Definition: Language.php:1949
Language\getConvRuleTitle
getConvRuleTitle()
Get the conversion rule title, if any.
Definition: Language.php:4769
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:4548
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:275
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Language\translateBlockExpiry
translateBlockExpiry( $str, UserIdentity $user=null, $now=0)
Definition: Language.php:4070
Language\PDF
const PDF
Definition: Language.php:250
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:82
Language\tsToHijri
static tsToHijri( $ts)
Converting Gregorian dates to Hijri dates.
Definition: Language.php:1598
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:557
$t
$t
Definition: testCompression.php:74
Language\time
time( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2236
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:3180
$minimumGroupingDigits
$minimumGroupingDigits
Definition: MessagesBg.php:223
Language\insertSpace
static insertSpace( $string, $pattern)
Definition: Language.php:2891
Language\isMultibyte
isMultibyte( $str)
Definition: Language.php:2724
Language\alignStart
alignStart()
Return 'left' or 'right' as appropriate alignment for line-start for this language's text direction.
Definition: Language.php:3021
Language\isSupportedLanguage
static isSupportedLanguage( $code)
Checks whether any localisation is available for that language tag in MediaWiki (MessagesXx....
Definition: Language.php:288
NS_PROJECT_TALK
const NS_PROJECT_TALK
Definition: Defines.php:69
Language\digitTransformTable
digitTransformTable()
Definition: Language.php:3418
Language\tsToYear
static tsToYear( $ts, $cName)
Algorithm to convert Gregorian dates to Thai solar dates, Minguo dates or Minguo dates.
Definition: Language.php:1826
Language\getDirMarkEntity
getDirMarkEntity( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3048
Language\strongDirFromContent
static strongDirFromContent( $text='')
Gets directionality of the first strongly directional codepoint, for embedBidi()
Definition: Language.php:1932
Language\hebrewYearStart
static hebrewYearStart( $year)
This calculates the Hebrew year start, as days since 1 September.
Definition: Language.php:1788
Language\$mNamespaceIds
$mNamespaceIds
Definition: Language.php:82
$IP
$IP
Definition: WebStart.php:49
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:67
Language\getDateFormatString
getDateFormatString( $type, $pref)
Get a format string for a given type and preference.
Definition: Language.php:2181
Language\getMagicWords
getMagicWords()
Get all magic words from cache.
Definition: Language.php:3111
Language\hasVariant
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: Language.php:4221
Language\__destruct
__destruct()
Reduce memory usage.
Definition: Language.php:470
Language\commafy
commafy( $number)
Adds commas to a given number.
Definition: Language.php:3399
Language\HIJRI_CALENDAR_MONTH_MESSAGES
const HIJRI_CALENDAR_MONTH_MESSAGES
Definition: Language.php:216
Language\STRICT_FALLBACKS
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:128
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:243
Language\tsToHebrew
static tsToHebrew( $ts)
Converting Gregorian dates to Hebrew dates.
Definition: Language.php:1650
Language\autoConvertToAllVariants
autoConvertToAllVariants( $text)
convert text to all supported variants
Definition: Language.php:4162
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:4302
Language\ucfirst
ucfirst( $str)
Definition: Language.php:2633
Language\$mMagicExtensions
$mMagicExtensions
Definition: Language.php:63
Language\gender
gender( $gender, $forms)
Provides an alternative text depending on specified gender.
Definition: Language.php:3943
Language\WEEKDAY_MESSAGES
const WEEKDAY_MESSAGES
Definition: Language.php:133
$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:4194