MediaWiki  master
Language.php
Go to the documentation of this file.
1 <?php
34 
39 class Language {
45  const AS_AUTONYMS = LanguageNameUtils::AUTONYMS;
46 
52  const ALL = LanguageNameUtils::ALL;
53 
60  const SUPPORTED = LanguageNameUtils::SUPPORTED;
61 
65  public $mConverter;
66 
67  public $mVariants, $mCode, $mLoaded = false;
68  public $mMagicExtensions = [];
69  private $mHtmlCode = null;
71  private $mParentLanguage = false;
72 
73  public $dateFormatStrings = [];
75 
77  protected $namespaceNames;
79 
83  public $transformData = [];
84 
87 
89  private $langNameUtils;
90 
92  private $langFallback;
93 
96 
101  public static $mLangObjCache = [];
102 
108  const MESSAGES_FALLBACKS = LanguageFallback::MESSAGES;
109 
115  const STRICT_FALLBACKS = LanguageFallback::STRICT;
116 
120  public const WEEKDAY_MESSAGES = [
121  'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
122  'friday', 'saturday'
123  ];
124 
128  public static $mWeekdayMsgs = self::WEEKDAY_MESSAGES;
129 
134  'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
135  ];
136 
140  public static $mWeekdayAbbrevMsgs = self::WEEKDAY_ABBREVIATED_MESSAGES;
141 
145  public const MONTH_MESSAGES = [
146  'january', 'february', 'march', 'april', 'may_long', 'june',
147  'july', 'august', 'september', 'october', 'november',
148  'december'
149  ];
150 
154  public static $mMonthMsgs = self::MONTH_MESSAGES;
155 
159  public const MONTH_GENITIVE_MESSAGES = [
160  'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
161  'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
162  'december-gen'
163  ];
164 
168  public static $mMonthGenMsgs = self::MONTH_GENITIVE_MESSAGES;
169 
173  public const MONTH_ABBREVIATED_MESSAGES = [
174  'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
175  'sep', 'oct', 'nov', 'dec'
176  ];
177 
181  public static $mMonthAbbrevMsgs = self::MONTH_ABBREVIATED_MESSAGES;
182 
187  'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
188  'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
189  'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
190  'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
191  ];
192 
196  public static $mIranianCalendarMonthMsgs = self::IRANIAN_CALENDAR_MONTHS_MESSAGES;
197 
202  'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
203  'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
204  'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
205  'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
206  'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
207  ];
208 
212  public static $mHebrewCalendarMonthMsgs = self::HEBREW_CALENDAR_MONTHS_MESSAGES;
213 
218  'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
219  'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
220  'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
221  'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
222  'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
223  ];
224 
228  public static $mHebrewCalendarMonthGenMsgs = self::HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES;
229 
234  'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
235  'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
236  'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
237  'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
238  ];
239 
243  public static $mHijriCalendarMonthMsgs = self::HIJRI_CALENDAR_MONTH_MESSAGES;
244 
248  protected const DURATION_INTERVALS = [
249  'millennia' => 31556952000,
250  'centuries' => 3155695200,
251  'decades' => 315569520,
252  'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
253  'weeks' => 604800,
254  'days' => 86400,
255  'hours' => 3600,
256  'minutes' => 60,
257  'seconds' => 1,
258  ];
259 
265  public static $durationIntervals = self::DURATION_INTERVALS;
266 
270  private const LRE = "\u{202A}"; // U+202A LEFT-TO-RIGHT EMBEDDING
271  private const RLE = "\u{202B}"; // U+202B RIGHT-TO-LEFT EMBEDDING
272  private const PDF = "\u{202C}"; // U+202C POP DIRECTIONAL FORMATTING
273 
285  // @codeCoverageIgnoreStart
286  // phpcs:ignore Generic.Files.LineLength
287  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';
288  // @codeCoverageIgnoreEnd
289 
297  static function factory( $code ) {
298  return MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $code );
299  }
300 
307  public static function clearCaches() {
308  wfDeprecated( __METHOD__, '1.35' );
309 
310  $services = MediaWikiServices::getInstance();
311 
312  $services->resetServiceForTesting( 'LanguageFallback' );
313  $services->resetServiceForTesting( 'LanguageNameUtils' );
314  $services->resetServiceForTesting( 'LocalisationCache' );
315  $services->resetServiceForTesting( 'LanguageFactory' );
316 
317  self::$mLangObjCache = [];
318  }
319 
329  public static function isSupportedLanguage( $code ) {
330  return MediaWikiServices::getInstance()->getLanguageNameUtils()
331  ->isSupportedLanguage( $code );
332  }
333 
349  public static function isWellFormedLanguageTag( $code, $lenient = false ) {
350  $alpha = '[a-z]';
351  $digit = '[0-9]';
352  $alphanum = '[a-z0-9]';
353  $x = 'x'; # private use singleton
354  $singleton = '[a-wy-z]'; # other singleton
355  $s = $lenient ? '[-_]' : '-';
356 
357  $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
358  $script = "$alpha{4}"; # ISO 15924
359  $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
360  $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
361  $extension = "$singleton(?:$s$alphanum{2,8})+";
362  $privateUse = "$x(?:$s$alphanum{1,8})+";
363 
364  # Define certain grandfathered codes, since otherwise the regex is pretty useless.
365  # Since these are limited, this is safe even later changes to the registry --
366  # the only oddity is that it might change the type of the tag, and thus
367  # the results from the capturing groups.
368  # https://www.iana.org/assignments/language-subtag-registry
369 
370  $grandfathered = "en{$s}GB{$s}oed"
371  . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
372  . "|no{$s}(?:bok|nyn)"
373  . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
374  . "|zh{$s}min{$s}nan";
375 
376  $variantList = "$variant(?:$s$variant)*";
377  $extensionList = "$extension(?:$s$extension)*";
378 
379  $langtag = "(?:($language)"
380  . "(?:$s$script)?"
381  . "(?:$s$region)?"
382  . "(?:$s$variantList)?"
383  . "(?:$s$extensionList)?"
384  . "(?:$s$privateUse)?)";
385 
386  # The final breakdown, with capturing groups for each of these components
387  # The variants, extensions, grandfathered, and private-use may have interior '-'
388 
389  $root = "^(?:$langtag|$privateUse|$grandfathered)$";
390 
391  return (bool)preg_match( "/$root/", strtolower( $code ) );
392  }
393 
405  public static function isValidCode( $code ) {
406  return MediaWikiServices::getInstance()->getLanguageNameUtils()->isValidCode( $code );
407  }
408 
420  public static function isValidBuiltInCode( $code ) {
421  return MediaWikiServices::getInstance()->getLanguageNameUtils()
422  ->isValidBuiltInCode( $code );
423  }
424 
435  public static function isKnownLanguageTag( $tag ) {
436  return MediaWikiServices::getInstance()->getLanguageNameUtils()
437  ->isKnownLanguageTag( $tag );
438  }
439 
446  public static function getLocalisationCache() {
447  return MediaWikiServices::getInstance()->getLocalisationCache();
448  }
449 
458  public function __construct(
459  $code = null,
463  ) {
464  $this->mConverter = $this->newConverter();
465  if ( !func_num_args() ) {
466  // Old calling convention, deprecated
467  if ( static::class === 'Language' ) {
468  $this->mCode = 'en';
469  } else {
470  $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
471  }
472  $services = MediaWikiServices::getInstance();
473  $this->localisationCache = $services->getLocalisationCache();
474  $this->langNameUtils = $services->getLanguageNameUtils();
475  $this->langFallback = $services->getLanguageFallback();
476  return;
477  }
478 
479  Assert::parameter( $code !== null, '$code',
480  'Parameters cannot be null unless all are omitted' );
481  Assert::parameter( $localisationCache !== null, '$localisationCache',
482  'Parameters cannot be null unless all are omitted' );
483  Assert::parameter( $langNameUtils !== null, '$langNameUtils',
484  'Parameters cannot be null unless all are omitted' );
485  Assert::parameter( $langFallback !== null, '$langFallback',
486  'Parameters cannot be null unless all are omitted' );
487 
488  $this->mCode = $code;
489  $this->localisationCache = $localisationCache;
490  $this->langNameUtils = $langNameUtils;
491  $this->langFallback = $langFallback;
492  }
493 
498  function __destruct() {
499  foreach ( $this as $name => $value ) {
500  unset( $this->$name );
501  }
502  }
503 
508  public function getFallbackLanguages() {
509  return $this->langFallback->getAll( $this->mCode );
510  }
511 
516  public function getBookstoreList() {
517  return $this->localisationCache->getItem( $this->mCode, 'bookstoreList' );
518  }
519 
526  public function getNamespaces() {
527  if ( is_null( $this->namespaceNames ) ) {
529 
530  $validNamespaces = MediaWikiServices::getInstance()->getNamespaceInfo()->
531  getCanonicalNamespaces();
532 
533  $this->namespaceNames = $wgExtraNamespaces +
534  $this->localisationCache->getItem( $this->mCode, 'namespaceNames' );
535  $this->namespaceNames += $validNamespaces;
536 
537  $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
538  if ( $wgMetaNamespaceTalk ) {
539  $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
540  } else {
541  $talk = $this->namespaceNames[NS_PROJECT_TALK];
542  $this->namespaceNames[NS_PROJECT_TALK] =
543  $this->fixVariableInNamespace( $talk );
544  }
545 
546  # Sometimes a language will be localised but not actually exist on this wiki.
547  foreach ( $this->namespaceNames as $key => $text ) {
548  if ( !isset( $validNamespaces[$key] ) ) {
549  unset( $this->namespaceNames[$key] );
550  }
551  }
552 
553  # The above mixing may leave namespaces out of canonical order.
554  # Re-order by namespace ID number...
555  ksort( $this->namespaceNames );
556 
557  Hooks::run( 'LanguageGetNamespaces', [ &$this->namespaceNames ] );
558  }
559 
560  return $this->namespaceNames;
561  }
562 
567  public function setNamespaces( array $namespaces ) {
568  $this->namespaceNames = $namespaces;
569  $this->mNamespaceIds = null;
570  }
571 
575  public function resetNamespaces() {
576  $this->namespaceNames = null;
577  $this->mNamespaceIds = null;
578  $this->namespaceAliases = null;
579  }
580 
587  public function getFormattedNamespaces() {
588  $ns = $this->getNamespaces();
589  foreach ( $ns as $k => $v ) {
590  $ns[$k] = strtr( $v, '_', ' ' );
591  }
592  return $ns;
593  }
594 
606  public function getNsText( $index ) {
607  $ns = $this->getNamespaces();
608  return $ns[$index] ?? false;
609  }
610 
624  public function getFormattedNsText( $index ) {
625  $ns = $this->getNsText( $index );
626  return strtr( $ns, '_', ' ' );
627  }
628 
637  public function getGenderNsText( $index, $gender ) {
639 
640  $ns = $wgExtraGenderNamespaces +
641  (array)$this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
642 
643  return $ns[$index][$gender] ?? $this->getNsText( $index );
644  }
645 
652  public function needsGenderDistinction() {
654  if ( count( $wgExtraGenderNamespaces ) > 0 ) {
655  // $wgExtraGenderNamespaces overrides everything
656  return true;
657  } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
659  // $wgExtraNamespaces overrides any gender aliases specified in i18n files
660  return false;
661  } else {
662  // Check what is in i18n files
663  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
664  return count( $aliases ) > 0;
665  }
666  }
667 
676  function getLocalNsIndex( $text ) {
677  $lctext = $this->lc( $text );
678  $ids = $this->getNamespaceIds();
679  return $ids[$lctext] ?? false;
680  }
681 
685  public function getNamespaceAliases() {
686  if ( is_null( $this->namespaceAliases ) ) {
687  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceAliases' );
688  if ( !$aliases ) {
689  $aliases = [];
690  } else {
691  foreach ( $aliases as $name => $index ) {
692  if ( $index === NS_PROJECT_TALK ) {
693  unset( $aliases[$name] );
694  $name = $this->fixVariableInNamespace( $name );
695  $aliases[$name] = $index;
696  }
697  }
698  }
699 
701  $genders = $wgExtraGenderNamespaces + (array)$this->localisationCache
702  ->getItem( $this->mCode, 'namespaceGenderAliases' );
703  foreach ( $genders as $index => $forms ) {
704  foreach ( $forms as $alias ) {
705  $aliases[$alias] = $index;
706  }
707  }
708 
709  # Also add converted namespace names as aliases, to avoid confusion.
710  $convertedNames = [];
711  foreach ( $this->getVariants() as $variant ) {
712  if ( $variant === $this->mCode ) {
713  continue;
714  }
715  foreach ( $this->getNamespaces() as $ns => $_ ) {
716  $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
717  }
718  }
719 
720  $this->namespaceAliases = $aliases + $convertedNames;
721 
722  # Filter out aliases to namespaces that don't exist, e.g. from extensions
723  # that aren't loaded here but are included in the l10n cache.
724  # (array_intersect preserves keys from its first argument)
725  $this->namespaceAliases = array_intersect(
726  $this->namespaceAliases,
727  array_keys( $this->getNamespaces() )
728  );
729  }
730 
732  }
733 
737  public function getNamespaceIds() {
738  if ( is_null( $this->mNamespaceIds ) ) {
739  global $wgNamespaceAliases;
740  # Put namespace names and aliases into a hashtable.
741  # If this is too slow, then we should arrange it so that it is done
742  # before caching. The catch is that at pre-cache time, the above
743  # class-specific fixup hasn't been done.
744  $this->mNamespaceIds = [];
745  foreach ( $this->getNamespaces() as $index => $name ) {
746  $this->mNamespaceIds[$this->lc( $name )] = $index;
747  }
748  foreach ( $this->getNamespaceAliases() as $name => $index ) {
749  $this->mNamespaceIds[$this->lc( $name )] = $index;
750  }
751  if ( $wgNamespaceAliases ) {
752  foreach ( $wgNamespaceAliases as $name => $index ) {
753  $this->mNamespaceIds[$this->lc( $name )] = $index;
754  }
755  }
756  }
757  return $this->mNamespaceIds;
758  }
759 
767  public function getNsIndex( $text ) {
768  $lctext = $this->lc( $text );
769  $ns = MediaWikiServices::getInstance()->getNamespaceInfo()->
770  getCanonicalIndex( $lctext );
771  if ( $ns !== null ) {
772  return $ns;
773  }
774  $ids = $this->getNamespaceIds();
775  return $ids[$lctext] ?? false;
776  }
777 
785  public function getVariantname( $code, $usemsg = true ) {
786  $msg = "variantname-$code";
787  if ( $usemsg && wfMessage( $msg )->exists() ) {
788  return $this->getMessageFromDB( $msg );
789  }
790  $name = $this->langNameUtils->getLanguageName( $code );
791  if ( $name ) {
792  return $name; # if it's defined as a language name, show that
793  } else {
794  # otherwise, output the language code
795  return $code;
796  }
797  }
798 
802  public function getDatePreferences() {
803  return $this->localisationCache->getItem( $this->mCode, 'datePreferences' );
804  }
805 
809  function getDateFormats() {
810  return $this->localisationCache->getItem( $this->mCode, 'dateFormats' );
811  }
812 
816  public function getDefaultDateFormat() {
817  $df = $this->localisationCache->getItem( $this->mCode, 'defaultDateFormat' );
818  if ( $df === 'dmy or mdy' ) {
819  global $wgAmericanDates;
820  return $wgAmericanDates ? 'mdy' : 'dmy';
821  } else {
822  return $df;
823  }
824  }
825 
829  public function getDatePreferenceMigrationMap() {
830  return $this->localisationCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
831  }
832 
836  public function getExtraUserToggles() {
837  wfDeprecated( __METHOD__, '1.34' );
838  return [];
839  }
840 
854  public static function fetchLanguageNames( $inLanguage = self::AS_AUTONYMS, $include = 'mw' ) {
855  return MediaWikiServices::getInstance()->getLanguageNameUtils()
856  ->getLanguageNames( $inLanguage, $include );
857  }
858 
868  public static function fetchLanguageName(
869  $code,
870  $inLanguage = self::AS_AUTONYMS,
871  $include = self::ALL
872  ) {
873  return MediaWikiServices::getInstance()->getLanguageNameUtils()
874  ->getLanguageName( $code, $inLanguage, $include );
875  }
876 
883  public function getMessageFromDB( $msg ) {
884  return $this->msg( $msg )->text();
885  }
886 
893  protected function msg( $msg ) {
894  return wfMessage( $msg )->inLanguage( $this );
895  }
896 
901  public function getMonthName( $key ) {
902  return $this->getMessageFromDB( self::MONTH_MESSAGES[$key - 1] );
903  }
904 
908  public function getMonthNamesArray() {
909  $monthNames = [ '' ];
910  for ( $i = 1; $i < 13; $i++ ) {
911  $monthNames[] = $this->getMonthName( $i );
912  }
913  return $monthNames;
914  }
915 
920  public function getMonthNameGen( $key ) {
921  return $this->getMessageFromDB( self::MONTH_GENITIVE_MESSAGES[$key - 1] );
922  }
923 
928  public function getMonthAbbreviation( $key ) {
929  return $this->getMessageFromDB( self::MONTH_ABBREVIATED_MESSAGES[$key - 1] );
930  }
931 
935  public function getMonthAbbreviationsArray() {
936  $monthNames = [ '' ];
937  for ( $i = 1; $i < 13; $i++ ) {
938  $monthNames[] = $this->getMonthAbbreviation( $i );
939  }
940  return $monthNames;
941  }
942 
947  public function getWeekdayName( $key ) {
948  return $this->getMessageFromDB( self::WEEKDAY_MESSAGES[$key - 1] );
949  }
950 
955  public function getWeekdayAbbreviation( $key ) {
956  return $this->getMessageFromDB( self::WEEKDAY_ABBREVIATED_MESSAGES[$key - 1] );
957  }
958 
963  private function getIranianCalendarMonthName( $key ) {
964  return $this->getMessageFromDB( self::IRANIAN_CALENDAR_MONTHS_MESSAGES[$key - 1] );
965  }
966 
971  private function getHebrewCalendarMonthName( $key ) {
972  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTHS_MESSAGES[$key - 1] );
973  }
974 
979  private function getHebrewCalendarMonthNameGen( $key ) {
980  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES[$key - 1] );
981  }
982 
987  private function getHijriCalendarMonthName( $key ) {
988  return $this->getMessageFromDB( self::HIJRI_CALENDAR_MONTH_MESSAGES[$key - 1] );
989  }
990 
999  private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1000  if ( !$dateTimeObj ) {
1001  $dateTimeObj = DateTime::createFromFormat(
1002  'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1003  );
1004  }
1005  return $dateTimeObj->format( $code );
1006  }
1007 
1078  public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
1079  $s = '';
1080  $raw = false;
1081  $roman = false;
1082  $hebrewNum = false;
1083  $dateTimeObj = false;
1084  $rawToggle = false;
1085  $iranian = false;
1086  $hebrew = false;
1087  $hijri = false;
1088  $thai = false;
1089  $minguo = false;
1090  $tenno = false;
1091 
1092  $usedSecond = false;
1093  $usedMinute = false;
1094  $usedHour = false;
1095  $usedAMPM = false;
1096  $usedDay = false;
1097  $usedWeek = false;
1098  $usedMonth = false;
1099  $usedYear = false;
1100  $usedISOYear = false;
1101  $usedIsLeapYear = false;
1102 
1103  $usedHebrewMonth = false;
1104  $usedIranianMonth = false;
1105  $usedHijriMonth = false;
1106  $usedHebrewYear = false;
1107  $usedIranianYear = false;
1108  $usedHijriYear = false;
1109  $usedTennoYear = false;
1110 
1111  if ( strlen( $ts ) !== 14 ) {
1112  throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1113  }
1114 
1115  if ( !ctype_digit( $ts ) ) {
1116  throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1117  }
1118 
1119  $formatLength = strlen( $format );
1120  for ( $p = 0; $p < $formatLength; $p++ ) {
1121  $num = false;
1122  $code = $format[$p];
1123  if ( $code == 'x' && $p < $formatLength - 1 ) {
1124  $code .= $format[++$p];
1125  }
1126 
1127  if ( ( $code === 'xi'
1128  || $code === 'xj'
1129  || $code === 'xk'
1130  || $code === 'xm'
1131  || $code === 'xo'
1132  || $code === 'xt' )
1133  && $p < $formatLength - 1 ) {
1134  $code .= $format[++$p];
1135  }
1136 
1137  switch ( $code ) {
1138  case 'xx':
1139  $s .= 'x';
1140  break;
1141  case 'xn':
1142  $raw = true;
1143  break;
1144  case 'xN':
1145  $rawToggle = !$rawToggle;
1146  break;
1147  case 'xr':
1148  $roman = true;
1149  break;
1150  case 'xh':
1151  $hebrewNum = true;
1152  break;
1153  case 'xg':
1154  $usedMonth = true;
1155  $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1156  break;
1157  case 'xjx':
1158  $usedHebrewMonth = true;
1159  if ( !$hebrew ) {
1160  $hebrew = self::tsToHebrew( $ts );
1161  }
1162  $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1163  break;
1164  case 'd':
1165  $usedDay = true;
1166  $num = substr( $ts, 6, 2 );
1167  break;
1168  case 'D':
1169  $usedDay = true;
1170  $s .= $this->getWeekdayAbbreviation(
1171  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1172  );
1173  break;
1174  case 'j':
1175  $usedDay = true;
1176  $num = intval( substr( $ts, 6, 2 ) );
1177  break;
1178  case 'xij':
1179  $usedDay = true;
1180  if ( !$iranian ) {
1181  $iranian = self::tsToIranian( $ts );
1182  }
1183  $num = $iranian[2];
1184  break;
1185  case 'xmj':
1186  $usedDay = true;
1187  if ( !$hijri ) {
1188  $hijri = self::tsToHijri( $ts );
1189  }
1190  $num = $hijri[2];
1191  break;
1192  case 'xjj':
1193  $usedDay = true;
1194  if ( !$hebrew ) {
1195  $hebrew = self::tsToHebrew( $ts );
1196  }
1197  $num = $hebrew[2];
1198  break;
1199  case 'l':
1200  $usedDay = true;
1201  $s .= $this->getWeekdayName(
1202  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1203  );
1204  break;
1205  case 'F':
1206  $usedMonth = true;
1207  $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1208  break;
1209  case 'xiF':
1210  $usedIranianMonth = true;
1211  if ( !$iranian ) {
1212  $iranian = self::tsToIranian( $ts );
1213  }
1214  $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1215  break;
1216  case 'xmF':
1217  $usedHijriMonth = true;
1218  if ( !$hijri ) {
1219  $hijri = self::tsToHijri( $ts );
1220  }
1221  $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1222  break;
1223  case 'xjF':
1224  $usedHebrewMonth = true;
1225  if ( !$hebrew ) {
1226  $hebrew = self::tsToHebrew( $ts );
1227  }
1228  $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1229  break;
1230  case 'm':
1231  $usedMonth = true;
1232  $num = substr( $ts, 4, 2 );
1233  break;
1234  case 'M':
1235  $usedMonth = true;
1236  $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1237  break;
1238  case 'n':
1239  $usedMonth = true;
1240  $num = intval( substr( $ts, 4, 2 ) );
1241  break;
1242  case 'xin':
1243  $usedIranianMonth = true;
1244  if ( !$iranian ) {
1245  $iranian = self::tsToIranian( $ts );
1246  }
1247  $num = $iranian[1];
1248  break;
1249  case 'xmn':
1250  $usedHijriMonth = true;
1251  if ( !$hijri ) {
1252  $hijri = self::tsToHijri( $ts );
1253  }
1254  $num = $hijri[1];
1255  break;
1256  case 'xjn':
1257  $usedHebrewMonth = true;
1258  if ( !$hebrew ) {
1259  $hebrew = self::tsToHebrew( $ts );
1260  }
1261  $num = $hebrew[1];
1262  break;
1263  case 'xjt':
1264  $usedHebrewMonth = true;
1265  if ( !$hebrew ) {
1266  $hebrew = self::tsToHebrew( $ts );
1267  }
1268  $num = $hebrew[3];
1269  break;
1270  case 'Y':
1271  $usedYear = true;
1272  $num = substr( $ts, 0, 4 );
1273  break;
1274  case 'xiY':
1275  $usedIranianYear = true;
1276  if ( !$iranian ) {
1277  $iranian = self::tsToIranian( $ts );
1278  }
1279  $num = $iranian[0];
1280  break;
1281  case 'xmY':
1282  $usedHijriYear = true;
1283  if ( !$hijri ) {
1284  $hijri = self::tsToHijri( $ts );
1285  }
1286  $num = $hijri[0];
1287  break;
1288  case 'xjY':
1289  $usedHebrewYear = true;
1290  if ( !$hebrew ) {
1291  $hebrew = self::tsToHebrew( $ts );
1292  }
1293  $num = $hebrew[0];
1294  break;
1295  case 'xkY':
1296  $usedYear = true;
1297  if ( !$thai ) {
1298  $thai = self::tsToYear( $ts, 'thai' );
1299  }
1300  $num = $thai[0];
1301  break;
1302  case 'xoY':
1303  $usedYear = true;
1304  if ( !$minguo ) {
1305  $minguo = self::tsToYear( $ts, 'minguo' );
1306  }
1307  $num = $minguo[0];
1308  break;
1309  case 'xtY':
1310  $usedTennoYear = true;
1311  if ( !$tenno ) {
1312  $tenno = self::tsToYear( $ts, 'tenno' );
1313  }
1314  $num = $tenno[0];
1315  break;
1316  case 'y':
1317  $usedYear = true;
1318  $num = substr( $ts, 2, 2 );
1319  break;
1320  case 'xiy':
1321  $usedIranianYear = true;
1322  if ( !$iranian ) {
1323  $iranian = self::tsToIranian( $ts );
1324  }
1325  $num = substr( $iranian[0], -2 );
1326  break;
1327  case 'xit':
1328  $usedIranianYear = true;
1329  if ( !$iranian ) {
1330  $iranian = self::tsToIranian( $ts );
1331  }
1332  $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
1333  break;
1334  case 'xiz':
1335  $usedIranianYear = true;
1336  if ( !$iranian ) {
1337  $iranian = self::tsToIranian( $ts );
1338  }
1339  $num = $iranian[3];
1340  break;
1341  case 'a':
1342  $usedAMPM = true;
1343  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1344  break;
1345  case 'A':
1346  $usedAMPM = true;
1347  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1348  break;
1349  case 'g':
1350  $usedHour = true;
1351  $h = substr( $ts, 8, 2 );
1352  $num = $h % 12 ?: 12;
1353  break;
1354  case 'G':
1355  $usedHour = true;
1356  $num = intval( substr( $ts, 8, 2 ) );
1357  break;
1358  case 'h':
1359  $usedHour = true;
1360  $h = substr( $ts, 8, 2 );
1361  $num = sprintf( '%02d', $h % 12 ?: 12 );
1362  break;
1363  case 'H':
1364  $usedHour = true;
1365  $num = substr( $ts, 8, 2 );
1366  break;
1367  case 'i':
1368  $usedMinute = true;
1369  $num = substr( $ts, 10, 2 );
1370  break;
1371  case 's':
1372  $usedSecond = true;
1373  $num = substr( $ts, 12, 2 );
1374  break;
1375  case 'c':
1376  case 'r':
1377  $usedSecond = true;
1378  // fall through
1379  case 'e':
1380  case 'O':
1381  case 'P':
1382  case 'T':
1383  $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1384  break;
1385  case 'w':
1386  case 'N':
1387  case 'z':
1388  $usedDay = true;
1389  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1390  break;
1391  case 'W':
1392  $usedWeek = true;
1393  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1394  break;
1395  case 't':
1396  $usedMonth = true;
1397  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1398  break;
1399  case 'L':
1400  $usedIsLeapYear = true;
1401  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1402  break;
1403  case 'o':
1404  $usedISOYear = true;
1405  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1406  break;
1407  case 'U':
1408  $usedSecond = true;
1409  // fall through
1410  case 'I':
1411  case 'Z':
1412  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1413  break;
1414  case '\\':
1415  # Backslash escaping
1416  if ( $p < $formatLength - 1 ) {
1417  $s .= $format[++$p];
1418  } else {
1419  $s .= '\\';
1420  }
1421  break;
1422  case '"':
1423  # Quoted literal
1424  if ( $p < $formatLength - 1 ) {
1425  $endQuote = strpos( $format, '"', $p + 1 );
1426  if ( $endQuote === false ) {
1427  # No terminating quote, assume literal "
1428  $s .= '"';
1429  } else {
1430  $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1431  $p = $endQuote;
1432  }
1433  } else {
1434  # Quote at end of string, assume literal "
1435  $s .= '"';
1436  }
1437  break;
1438  default:
1439  $s .= $format[$p];
1440  }
1441  if ( $num !== false ) {
1442  if ( $rawToggle || $raw ) {
1443  $s .= $num;
1444  $raw = false;
1445  } elseif ( $roman ) {
1446  $s .= self::romanNumeral( $num );
1447  $roman = false;
1448  } elseif ( $hebrewNum ) {
1449  $s .= self::hebrewNumeral( $num );
1450  $hebrewNum = false;
1451  } else {
1452  $s .= $this->formatNum( $num, true );
1453  }
1454  }
1455  }
1456 
1457  if ( $ttl === 'unused' ) {
1458  // No need to calculate the TTL, the caller wont use it anyway.
1459  } elseif ( $usedSecond ) {
1460  $ttl = 1;
1461  } elseif ( $usedMinute ) {
1462  $ttl = 60 - substr( $ts, 12, 2 );
1463  } elseif ( $usedHour ) {
1464  $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1465  } elseif ( $usedAMPM ) {
1466  $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1467  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1468  } elseif (
1469  $usedDay ||
1470  $usedHebrewMonth ||
1471  $usedIranianMonth ||
1472  $usedHijriMonth ||
1473  $usedHebrewYear ||
1474  $usedIranianYear ||
1475  $usedHijriYear ||
1476  $usedTennoYear
1477  ) {
1478  // @todo Someone who understands the non-Gregorian calendars
1479  // should write proper logic for them so that they don't need purged every day.
1480  $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1481  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1482  } else {
1483  $possibleTtls = [];
1484  $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1485  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1486  if ( $usedWeek ) {
1487  $possibleTtls[] =
1488  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1489  $timeRemainingInDay;
1490  } elseif ( $usedISOYear ) {
1491  // December 28th falls on the last ISO week of the year, every year.
1492  // The last ISO week of a year can be 52 or 53.
1493  $lastWeekOfISOYear = DateTime::createFromFormat(
1494  'Ymd',
1495  substr( $ts, 0, 4 ) . '1228',
1496  $zone ?: new DateTimeZone( 'UTC' )
1497  )->format( 'W' );
1498  $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1499  $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1500  $timeRemainingInWeek =
1501  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1502  + $timeRemainingInDay;
1503  $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1504  }
1505 
1506  if ( $usedMonth ) {
1507  $possibleTtls[] =
1508  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1509  substr( $ts, 6, 2 ) ) * 86400
1510  + $timeRemainingInDay;
1511  } elseif ( $usedYear ) {
1512  $possibleTtls[] =
1513  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1514  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1515  + $timeRemainingInDay;
1516  } elseif ( $usedIsLeapYear ) {
1517  $year = substr( $ts, 0, 4 );
1518  $timeRemainingInYear =
1519  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1520  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1521  + $timeRemainingInDay;
1522  $mod = $year % 4;
1523  if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1524  // this isn't a leap year. see when the next one starts
1525  $nextCandidate = $year - $mod + 4;
1526  if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1527  $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1528  $timeRemainingInYear;
1529  } else {
1530  $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1531  $timeRemainingInYear;
1532  }
1533  } else {
1534  // this is a leap year, so the next year isn't
1535  $possibleTtls[] = $timeRemainingInYear;
1536  }
1537  }
1538 
1539  if ( $possibleTtls ) {
1540  $ttl = min( $possibleTtls );
1541  }
1542  }
1543 
1544  return $s;
1545  }
1546 
1547  private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1548  private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1549 
1562  private static function tsToIranian( $ts ) {
1563  $gy = substr( $ts, 0, 4 ) - 1600;
1564  $gm = substr( $ts, 4, 2 ) - 1;
1565  $gd = substr( $ts, 6, 2 ) - 1;
1566 
1567  # Days passed from the beginning (including leap years)
1568  $gDayNo = 365 * $gy
1569  + floor( ( $gy + 3 ) / 4 )
1570  - floor( ( $gy + 99 ) / 100 )
1571  + floor( ( $gy + 399 ) / 400 );
1572 
1573  // Add days of the past months of this year
1574  for ( $i = 0; $i < $gm; $i++ ) {
1575  $gDayNo += self::$GREG_DAYS[$i];
1576  }
1577 
1578  // Leap years
1579  if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1580  $gDayNo++;
1581  }
1582 
1583  // Days passed in current month
1584  $gDayNo += (int)$gd;
1585 
1586  $jDayNo = $gDayNo - 79;
1587 
1588  $jNp = floor( $jDayNo / 12053 );
1589  $jDayNo %= 12053;
1590 
1591  $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1592  $jDayNo %= 1461;
1593 
1594  if ( $jDayNo >= 366 ) {
1595  $jy += floor( ( $jDayNo - 1 ) / 365 );
1596  $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1597  }
1598 
1599  $jz = $jDayNo;
1600 
1601  for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1602  $jDayNo -= self::$IRANIAN_DAYS[$i];
1603  }
1604 
1605  $jm = $i + 1;
1606  $jd = $jDayNo + 1;
1607 
1608  return [ $jy, $jm, $jd, $jz ];
1609  }
1610 
1622  private static function tsToHijri( $ts ) {
1623  $year = substr( $ts, 0, 4 );
1624  $month = substr( $ts, 4, 2 );
1625  $day = substr( $ts, 6, 2 );
1626 
1627  $zyr = $year;
1628  $zd = $day;
1629  $zm = $month;
1630  $zy = $zyr;
1631 
1632  if (
1633  ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1634  ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1635  ) {
1636  $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1637  (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1638  (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1639  $zd - 32075;
1640  } else {
1641  $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1642  (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1643  }
1644 
1645  $zl = $zjd - 1948440 + 10632;
1646  $zn = (int)( ( $zl - 1 ) / 10631 );
1647  $zl = $zl - 10631 * $zn + 354;
1648  $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1649  ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1650  $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1651  ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1652  $zm = (int)( ( 24 * $zl ) / 709 );
1653  $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1654  $zy = 30 * $zn + $zj - 30;
1655 
1656  return [ $zy, $zm, $zd ];
1657  }
1658 
1674  private static function tsToHebrew( $ts ) {
1675  # Parse date
1676  $year = substr( $ts, 0, 4 );
1677  $month = substr( $ts, 4, 2 );
1678  $day = substr( $ts, 6, 2 );
1679 
1680  # Calculate Hebrew year
1681  $hebrewYear = $year + 3760;
1682 
1683  # Month number when September = 1, August = 12
1684  $month += 4;
1685  if ( $month > 12 ) {
1686  # Next year
1687  $month -= 12;
1688  $year++;
1689  $hebrewYear++;
1690  }
1691 
1692  # Calculate day of year from 1 September
1693  $dayOfYear = $day;
1694  for ( $i = 1; $i < $month; $i++ ) {
1695  if ( $i == 6 ) {
1696  # February
1697  $dayOfYear += 28;
1698  # Check if the year is leap
1699  if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1700  $dayOfYear++;
1701  }
1702  } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1703  $dayOfYear += 30;
1704  } else {
1705  $dayOfYear += 31;
1706  }
1707  }
1708 
1709  # Calculate the start of the Hebrew year
1710  $start = self::hebrewYearStart( $hebrewYear );
1711 
1712  # Calculate next year's start
1713  if ( $dayOfYear <= $start ) {
1714  # Day is before the start of the year - it is the previous year
1715  # Next year's start
1716  $nextStart = $start;
1717  # Previous year
1718  $year--;
1719  $hebrewYear--;
1720  # Add days since previous year's 1 September
1721  $dayOfYear += 365;
1722  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1723  # Leap year
1724  $dayOfYear++;
1725  }
1726  # Start of the new (previous) year
1727  $start = self::hebrewYearStart( $hebrewYear );
1728  } else {
1729  # Next year's start
1730  $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1731  }
1732 
1733  # Calculate Hebrew day of year
1734  $hebrewDayOfYear = $dayOfYear - $start;
1735 
1736  # Difference between year's days
1737  $diff = $nextStart - $start;
1738  # Add 12 (or 13 for leap years) days to ignore the difference between
1739  # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1740  # difference is only about the year type
1741  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1742  $diff += 13;
1743  } else {
1744  $diff += 12;
1745  }
1746 
1747  # Check the year pattern, and is leap year
1748  # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1749  # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1750  # and non-leap years
1751  $yearPattern = $diff % 30;
1752  # Check if leap year
1753  $isLeap = $diff >= 30;
1754 
1755  # Calculate day in the month from number of day in the Hebrew year
1756  # Don't check Adar - if the day is not in Adar, we will stop before;
1757  # if it is in Adar, we will use it to check if it is Adar I or Adar II
1758  $hebrewDay = $hebrewDayOfYear;
1759  $hebrewMonth = 1;
1760  $days = 0;
1761  while ( $hebrewMonth <= 12 ) {
1762  # Calculate days in this month
1763  if ( $isLeap && $hebrewMonth == 6 ) {
1764  # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1765  $days = 30;
1766  if ( $hebrewDay <= $days ) {
1767  # Day in Adar I
1768  $hebrewMonth = 13;
1769  } else {
1770  # Subtract the days of Adar I
1771  $hebrewDay -= $days;
1772  # Try Adar II
1773  $days = 29;
1774  if ( $hebrewDay <= $days ) {
1775  # Day in Adar II
1776  $hebrewMonth = 14;
1777  }
1778  }
1779  } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1780  # Cheshvan in a complete year (otherwise as the rule below)
1781  $days = 30;
1782  } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1783  # Kislev in an incomplete year (otherwise as the rule below)
1784  $days = 29;
1785  } else {
1786  # Odd months have 30 days, even have 29
1787  $days = 30 - ( $hebrewMonth - 1 ) % 2;
1788  }
1789  if ( $hebrewDay <= $days ) {
1790  # In the current month
1791  break;
1792  } else {
1793  # Subtract the days of the current month
1794  $hebrewDay -= $days;
1795  # Try in the next month
1796  $hebrewMonth++;
1797  }
1798  }
1799 
1800  return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1801  }
1802 
1812  private static function hebrewYearStart( $year ) {
1813  $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1814  $b = intval( ( $year - 1 ) % 4 );
1815  $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1816  if ( $m < 0 ) {
1817  $m--;
1818  }
1819  $Mar = intval( $m );
1820  if ( $m < 0 ) {
1821  $m++;
1822  }
1823  $m -= $Mar;
1824 
1825  $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1826  if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1827  $Mar++;
1828  } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1829  $Mar += 2;
1830  } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1831  $Mar++;
1832  }
1833 
1834  $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1835  return $Mar;
1836  }
1837 
1850  private static function tsToYear( $ts, $cName ) {
1851  $gy = substr( $ts, 0, 4 );
1852  $gm = substr( $ts, 4, 2 );
1853  $gd = substr( $ts, 6, 2 );
1854 
1855  if ( !strcmp( $cName, 'thai' ) ) {
1856  # Thai solar dates
1857  # Add 543 years to the Gregorian calendar
1858  # Months and days are identical
1859  $gy_offset = $gy + 543;
1860  # fix for dates between 1912 and 1941
1861  # https://en.wikipedia.org/?oldid=836596673#New_year
1862  if ( $gy >= 1912 && $gy <= 1940 ) {
1863  if ( $gm <= 3 ) {
1864  $gy_offset--;
1865  }
1866  $gm = ( $gm - 3 ) % 12;
1867  }
1868  } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1869  # Minguo dates
1870  # Deduct 1911 years from the Gregorian calendar
1871  # Months and days are identical
1872  $gy_offset = $gy - 1911;
1873  } elseif ( !strcmp( $cName, 'tenno' ) ) {
1874  # Nengō dates up to Meiji period
1875  # Deduct years from the Gregorian calendar
1876  # depending on the nengo periods
1877  # Months and days are identical
1878  if ( ( $gy < 1912 )
1879  || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1880  || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1881  ) {
1882  # Meiji period
1883  $gy_gannen = $gy - 1868 + 1;
1884  $gy_offset = $gy_gannen;
1885  if ( $gy_gannen == 1 ) {
1886  $gy_offset = '元';
1887  }
1888  $gy_offset = '明治' . $gy_offset;
1889  } elseif (
1890  ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1891  ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1892  ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1893  ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1894  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1895  ) {
1896  # Taishō period
1897  $gy_gannen = $gy - 1912 + 1;
1898  $gy_offset = $gy_gannen;
1899  if ( $gy_gannen == 1 ) {
1900  $gy_offset = '元';
1901  }
1902  $gy_offset = '大正' . $gy_offset;
1903  } elseif (
1904  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1905  ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1906  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1907  ) {
1908  # Shōwa period
1909  $gy_gannen = $gy - 1926 + 1;
1910  $gy_offset = $gy_gannen;
1911  if ( $gy_gannen == 1 ) {
1912  $gy_offset = '元';
1913  }
1914  $gy_offset = '昭和' . $gy_offset;
1915  } elseif (
1916  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd >= 8 ) ) ||
1917  ( ( $gy > 1989 ) && ( $gy < 2019 ) ) ||
1918  ( ( $gy == 2019 ) && ( $gm < 5 ) )
1919  ) {
1920  # Heisei period
1921  $gy_gannen = $gy - 1989 + 1;
1922  $gy_offset = $gy_gannen;
1923  if ( $gy_gannen == 1 ) {
1924  $gy_offset = '元';
1925  }
1926  $gy_offset = '平成' . $gy_offset;
1927  } else {
1928  # Reiwa period
1929  $gy_gannen = $gy - 2019 + 1;
1930  $gy_offset = $gy_gannen;
1931  if ( $gy_gannen == 1 ) {
1932  $gy_offset = '元';
1933  }
1934  $gy_offset = '令和' . $gy_offset;
1935  }
1936  } else {
1937  $gy_offset = $gy;
1938  }
1939 
1940  return [ $gy_offset, $gm, $gd ];
1941  }
1942 
1956  private static function strongDirFromContent( $text = '' ) {
1957  if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
1958  return null;
1959  }
1960  if ( $matches[1] === '' ) {
1961  return 'rtl';
1962  }
1963  return 'ltr';
1964  }
1965 
1973  static function romanNumeral( $num ) {
1974  static $table = [
1975  [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
1976  [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
1977  [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
1978  [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
1979  'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
1980  ];
1981 
1982  $num = intval( $num );
1983  if ( $num > 10000 || $num <= 0 ) {
1984  return $num;
1985  }
1986 
1987  $s = '';
1988  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1989  if ( $num >= $pow10 ) {
1990  $s .= $table[$i][(int)floor( $num / $pow10 )];
1991  }
1992  $num = $num % $pow10;
1993  }
1994  return $s;
1995  }
1996 
2004  static function hebrewNumeral( $num ) {
2005  static $table = [
2006  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
2007  [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
2008  [ '',
2009  [ 'ק' ],
2010  [ 'ר' ],
2011  [ 'ש' ],
2012  [ 'ת' ],
2013  [ 'ת', 'ק' ],
2014  [ 'ת', 'ר' ],
2015  [ 'ת', 'ש' ],
2016  [ 'ת', 'ת' ],
2017  [ 'ת', 'ת', 'ק' ],
2018  [ 'ת', 'ת', 'ר' ],
2019  ],
2020  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
2021  ];
2022 
2023  $num = intval( $num );
2024  if ( $num > 9999 || $num <= 0 ) {
2025  return $num;
2026  }
2027 
2028  // Round thousands have special notations
2029  if ( $num === 1000 ) {
2030  return "א' אלף";
2031  } elseif ( $num % 1000 === 0 ) {
2032  return $table[0][$num / 1000] . "' אלפים";
2033  }
2034 
2035  $letters = [];
2036 
2037  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2038  if ( $num >= $pow10 ) {
2039  if ( $num === 15 || $num === 16 ) {
2040  $letters[] = $table[0][9];
2041  $letters[] = $table[0][$num - 9];
2042  $num = 0;
2043  } else {
2044  $letters = array_merge(
2045  $letters,
2046  (array)$table[$i][intval( $num / $pow10 )]
2047  );
2048 
2049  if ( $pow10 === 1000 ) {
2050  $letters[] = "'";
2051  }
2052  }
2053  }
2054 
2055  $num = $num % $pow10;
2056  }
2057 
2058  $preTransformLength = count( $letters );
2059  if ( $preTransformLength === 1 ) {
2060  // Add geresh (single quote) to one-letter numbers
2061  $letters[] = "'";
2062  } else {
2063  $lastIndex = $preTransformLength - 1;
2064  $letters[$lastIndex] = str_replace(
2065  [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2066  [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2067  $letters[$lastIndex]
2068  );
2069 
2070  // Add gershayim (double quote) to multiple-letter numbers,
2071  // but exclude numbers with only one letter after the thousands
2072  // (1001-1009, 1020, 1030, 2001-2009, etc.)
2073  if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2074  $letters[] = "'";
2075  } else {
2076  array_splice( $letters, -1, 0, '"' );
2077  }
2078  }
2079 
2080  return implode( $letters );
2081  }
2082 
2091  public function userAdjust( $ts, $tz = false ) {
2092  global $wgUser, $wgLocalTZoffset;
2093 
2094  if ( $tz === false ) {
2095  $tz = $wgUser->getOption( 'timecorrection' );
2096  }
2097 
2098  $data = explode( '|', $tz, 3 );
2099 
2100  if ( $data[0] == 'ZoneInfo' ) {
2101  try {
2102  $userTZ = new DateTimeZone( $data[2] );
2103  $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
2104  $date->setTimezone( $userTZ );
2105  return $date->format( 'YmdHis' );
2106  } catch ( Exception $e ) {
2107  // Unrecognized timezone, default to 'Offset' with the stored offset.
2108  $data[0] = 'Offset';
2109  }
2110  }
2111 
2112  if ( $data[0] == 'System' || $tz == '' ) {
2113  # Global offset in minutes.
2114  $minDiff = $wgLocalTZoffset;
2115  } elseif ( $data[0] == 'Offset' ) {
2116  $minDiff = intval( $data[1] );
2117  } else {
2118  $data = explode( ':', $tz );
2119  if ( count( $data ) == 2 ) {
2120  $data[0] = intval( $data[0] );
2121  $data[1] = intval( $data[1] );
2122  $minDiff = abs( $data[0] ) * 60 + $data[1];
2123  if ( $data[0] < 0 ) {
2124  $minDiff = -$minDiff;
2125  }
2126  } else {
2127  $minDiff = intval( $data[0] ) * 60;
2128  }
2129  }
2130 
2131  # No difference ? Return time unchanged
2132  if ( $minDiff == 0 ) {
2133  return $ts;
2134  }
2135 
2136  Wikimedia\suppressWarnings(); // E_STRICT system time bitching
2137  # Generate an adjusted date; take advantage of the fact that mktime
2138  # will normalize out-of-range values so we don't have to split $minDiff
2139  # into hours and minutes.
2140  $t = mktime( (
2141  (int)substr( $ts, 8, 2 ) ), # Hours
2142  (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2143  (int)substr( $ts, 12, 2 ), # Seconds
2144  (int)substr( $ts, 4, 2 ), # Month
2145  (int)substr( $ts, 6, 2 ), # Day
2146  (int)substr( $ts, 0, 4 ) ); # Year
2147 
2148  $date = date( 'YmdHis', $t );
2149  Wikimedia\restoreWarnings();
2150 
2151  return $date;
2152  }
2153 
2169  function dateFormat( $usePrefs = true ) {
2170  global $wgUser;
2171 
2172  if ( is_bool( $usePrefs ) ) {
2173  if ( $usePrefs ) {
2174  $datePreference = $wgUser->getDatePreference();
2175  } else {
2176  $datePreference = (string)User::getDefaultOption( 'date' );
2177  }
2178  } else {
2179  $datePreference = (string)$usePrefs;
2180  }
2181 
2182  // return int
2183  if ( $datePreference == '' ) {
2184  return 'default';
2185  }
2186 
2187  return $datePreference;
2188  }
2189 
2200  function getDateFormatString( $type, $pref ) {
2201  $wasDefault = false;
2202  if ( $pref == 'default' ) {
2203  $wasDefault = true;
2204  $pref = $this->getDefaultDateFormat();
2205  }
2206 
2207  if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2208  $df = $this->localisationCache
2209  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2210 
2211  if ( $type === 'pretty' && $df === null ) {
2212  $df = $this->getDateFormatString( 'date', $pref );
2213  }
2214 
2215  if ( !$wasDefault && $df === null ) {
2216  $pref = $this->getDefaultDateFormat();
2217  $df = $this->localisationCache
2218  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2219  }
2220 
2221  $this->dateFormatStrings[$type][$pref] = $df;
2222  }
2223  return $this->dateFormatStrings[$type][$pref];
2224  }
2225 
2236  public function date( $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( 'date', $this->dateFormat( $format ) );
2242  return $this->sprintfDate( $df, $ts );
2243  }
2244 
2255  public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2256  $ts = wfTimestamp( TS_MW, $ts );
2257  if ( $adj ) {
2258  $ts = $this->userAdjust( $ts, $timecorrection );
2259  }
2260  $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2261  return $this->sprintfDate( $df, $ts );
2262  }
2263 
2275  public function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2276  $ts = wfTimestamp( TS_MW, $ts );
2277  if ( $adj ) {
2278  $ts = $this->userAdjust( $ts, $timecorrection );
2279  }
2280  $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2281  return $this->sprintfDate( $df, $ts );
2282  }
2283 
2294  public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2295  $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2296 
2297  $segments = [];
2298 
2299  foreach ( $intervals as $intervalName => $intervalValue ) {
2300  // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2301  // duration-years, duration-decades, duration-centuries, duration-millennia
2302  $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2303  $segments[] = $message->inLanguage( $this )->escaped();
2304  }
2305 
2306  return $this->listToText( $segments );
2307  }
2308 
2320  public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2321  if ( empty( $chosenIntervals ) ) {
2322  $chosenIntervals = [
2323  'millennia',
2324  'centuries',
2325  'decades',
2326  'years',
2327  'days',
2328  'hours',
2329  'minutes',
2330  'seconds'
2331  ];
2332  }
2333 
2334  $intervals = array_intersect_key( self::DURATION_INTERVALS, array_flip( $chosenIntervals ) );
2335  $sortedNames = array_keys( $intervals );
2336  $smallestInterval = array_pop( $sortedNames );
2337 
2338  $segments = [];
2339 
2340  foreach ( $intervals as $name => $length ) {
2341  $value = floor( $seconds / $length );
2342 
2343  if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2344  $seconds -= $value * $length;
2345  $segments[$name] = $value;
2346  }
2347  }
2348 
2349  return $segments;
2350  }
2351 
2371  private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2372  $ts = wfTimestamp( TS_MW, $ts );
2373  $options += [ 'timecorrection' => true, 'format' => true ];
2374  if ( $options['timecorrection'] !== false ) {
2375  if ( $options['timecorrection'] === true ) {
2376  $offset = $user->getOption( 'timecorrection' );
2377  } else {
2378  $offset = $options['timecorrection'];
2379  }
2380  $ts = $this->userAdjust( $ts, $offset );
2381  }
2382  if ( $options['format'] === true ) {
2383  $format = $user->getDatePreference();
2384  } else {
2385  $format = $options['format'];
2386  }
2387  $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2388  return $this->sprintfDate( $df, $ts );
2389  }
2390 
2410  public function userDate( $ts, User $user, array $options = [] ) {
2411  return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2412  }
2413 
2433  public function userTime( $ts, User $user, array $options = [] ) {
2434  return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2435  }
2436 
2456  public function userTimeAndDate( $ts, User $user, array $options = [] ) {
2457  return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2458  }
2459 
2475  public function getHumanTimestamp(
2476  MWTimestamp $time, MWTimestamp $relativeTo = null, User $user = null
2477  ) {
2478  if ( $relativeTo === null ) {
2479  $relativeTo = new MWTimestamp();
2480  }
2481  if ( $user === null ) {
2482  $user = RequestContext::getMain()->getUser();
2483  }
2484 
2485  // Adjust for the user's timezone.
2486  $offsetThis = $time->offsetForUser( $user );
2487  $offsetRel = $relativeTo->offsetForUser( $user );
2488 
2489  $ts = '';
2490  if ( Hooks::run( 'GetHumanTimestamp', [ &$ts, $time, $relativeTo, $user, $this ] ) ) {
2491  $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2492  }
2493 
2494  // Reset the timezone on the objects.
2495  $time->timestamp->sub( $offsetThis );
2496  $relativeTo->timestamp->sub( $offsetRel );
2497 
2498  return $ts;
2499  }
2500 
2512  private function getHumanTimestampInternal(
2513  MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2514  ) {
2515  $diff = $ts->diff( $relativeTo );
2516  $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2517  (int)$relativeTo->timestamp->format( 'w' ) );
2518  $days = $diff->days ?: (int)$diffDay;
2519  if ( $diff->invert || $days > 5
2520  && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2521  ) {
2522  // Timestamps are in different years: use full timestamp
2523  // Also do full timestamp for future dates
2527  $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2528  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2529  } elseif ( $days > 5 ) {
2530  // Timestamps are in same year, but more than 5 days ago: show day and month only.
2531  $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2532  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2533  } elseif ( $days > 1 ) {
2534  // Timestamp within the past week: show the day of the week and time
2535  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2536  $weekday = self::WEEKDAY_MESSAGES[$ts->timestamp->format( 'w' )];
2537  // Messages:
2538  // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2539  $ts = wfMessage( "$weekday-at" )
2540  ->inLanguage( $this )
2541  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2542  ->text();
2543  } elseif ( $days == 1 ) {
2544  // Timestamp was yesterday: say 'yesterday' and the time.
2545  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2546  $ts = wfMessage( 'yesterday-at' )
2547  ->inLanguage( $this )
2548  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2549  ->text();
2550  } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2551  // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2552  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2553  $ts = wfMessage( 'today-at' )
2554  ->inLanguage( $this )
2555  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2556  ->text();
2557 
2558  // From here on in, the timestamp was soon enough ago so that we can simply say
2559  // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2560  } elseif ( $diff->h == 1 ) {
2561  // Less than 90 minutes, but more than an hour ago.
2562  $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2563  } elseif ( $diff->i >= 1 ) {
2564  // A few minutes ago.
2565  $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2566  } elseif ( $diff->s >= 30 ) {
2567  // Less than a minute, but more than 30 sec ago.
2568  $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2569  } else {
2570  // Less than 30 seconds ago.
2571  $ts = wfMessage( 'just-now' )->text();
2572  }
2573 
2574  return $ts;
2575  }
2576 
2581  public function getMessage( $key ) {
2582  return $this->localisationCache->getSubitem( $this->mCode, 'messages', $key );
2583  }
2584 
2588  function getAllMessages() {
2589  return $this->localisationCache->getItem( $this->mCode, 'messages' );
2590  }
2591 
2598  public function iconv( $in, $out, $string ) {
2599  # Even with //IGNORE iconv can whine about illegal characters in
2600  # *input* string. We just ignore those too.
2601  # REF: https://bugs.php.net/bug.php?id=37166
2602  # REF: https://phabricator.wikimedia.org/T18885
2603  Wikimedia\suppressWarnings();
2604  $text = iconv( $in, $out . '//IGNORE', $string );
2605  Wikimedia\restoreWarnings();
2606  return $text;
2607  }
2608 
2613  public function ucfirst( $str ) {
2614  $octetCode = ord( $str );
2615  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2616  if ( $octetCode < 96 ) {
2617  // Assume this is an uppercase/uncased ASCII character
2618  return (string)$str;
2619  } elseif ( $octetCode < 128 ) {
2620  // Assume this is a lowercase/uncased ASCII character
2621  return ucfirst( $str );
2622  }
2623 
2624  return $this->isMultibyte( $str )
2625  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2626  ? $this->mbUpperChar( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 )
2627  // Assume this is a non-multibyte character and LC_CASE is appropriate
2628  : ucfirst( $str );
2629  }
2630 
2636  public function uc( $str, $first = false ) {
2637  if ( $first ) {
2638  return $this->ucfirst( $str );
2639  } else {
2640  return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2641  }
2642  }
2643 
2657  protected function mbUpperChar( $char ) {
2659 
2660  return $wgOverrideUcfirstCharacters[$char] ?? mb_strtoupper( $char );
2661  }
2662 
2667  public function lcfirst( $str ) {
2668  $octetCode = ord( $str );
2669  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2670  if ( $octetCode < 96 ) {
2671  // Assume this is an uppercase/uncased ASCII character
2672  return lcfirst( $str );
2673  } elseif ( $octetCode < 128 ) {
2674  // Assume this is a lowercase/uncased ASCII character
2675  return (string)$str;
2676  }
2677 
2678  return $this->isMultibyte( $str )
2679  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2680  ? mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 )
2681  // Assume this is a non-multibyte character and LC_CASE is appropriate
2682  : lcfirst( $str );
2683  }
2684 
2690  public function lc( $str, $first = false ) {
2691  if ( $first ) {
2692  return $this->lcfirst( $str );
2693  } else {
2694  return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2695  }
2696  }
2697 
2702  function isMultibyte( $str ) {
2703  return strlen( $str ) !== mb_strlen( $str );
2704  }
2705 
2710  function ucwords( $str ) {
2711  if ( $this->isMultibyte( $str ) ) {
2712  $str = $this->lc( $str );
2713 
2714  // regexp to find first letter in each word (i.e. after each space)
2715  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2716 
2717  // function to use to capitalize a single char
2718  return preg_replace_callback(
2719  $replaceRegexp,
2720  function ( $matches ) {
2721  return mb_strtoupper( $matches[0] );
2722  },
2723  $str
2724  );
2725  } else {
2726  return ucwords( strtolower( $str ) );
2727  }
2728  }
2729 
2736  function ucwordbreaks( $str ) {
2737  if ( $this->isMultibyte( $str ) ) {
2738  $str = $this->lc( $str );
2739 
2740  // since \b doesn't work for UTF-8, we explicitely define word break chars
2741  $breaks = "[ \-\(\)\}\{\.,\?!]";
2742 
2743  // find first letter after word break
2744  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2745  "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2746 
2747  return preg_replace_callback(
2748  $replaceRegexp,
2749  function ( $matches ) {
2750  return mb_strtoupper( $matches[0] );
2751  },
2752  $str
2753  );
2754  } else {
2755  return preg_replace_callback(
2756  '/\b([\w\x80-\xff]+)\b/',
2757  function ( $matches ) {
2758  return $this->ucfirst( $matches[1] );
2759  },
2760  $str
2761  );
2762  }
2763  }
2764 
2780  public function caseFold( $s ) {
2781  return $this->uc( $s );
2782  }
2783 
2789  function checkTitleEncoding( $s ) {
2790  if ( is_array( $s ) ) {
2791  throw new MWException( 'Given array to checkTitleEncoding.' );
2792  }
2793  if ( StringUtils::isUtf8( $s ) ) {
2794  return $s;
2795  }
2796 
2797  return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2798  }
2799 
2803  public function fallback8bitEncoding() {
2804  return $this->localisationCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2805  }
2806 
2815  public function hasWordBreaks() {
2816  return true;
2817  }
2818 
2826  public function segmentByWord( $string ) {
2827  return $string;
2828  }
2829 
2837  public function normalizeForSearch( $string ) {
2838  return self::convertDoubleWidth( $string );
2839  }
2840 
2849  protected static function convertDoubleWidth( $string ) {
2850  static $full = null;
2851  static $half = null;
2852 
2853  if ( $full === null ) {
2854  $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2855  $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2856  $full = str_split( $fullWidth, 3 );
2857  $half = str_split( $halfWidth );
2858  }
2859 
2860  $string = str_replace( $full, $half, $string );
2861  return $string;
2862  }
2863 
2869  protected static function insertSpace( $string, $pattern ) {
2870  $string = preg_replace( $pattern, " $1 ", $string );
2871  $string = preg_replace( '/ +/', ' ', $string );
2872  return $string;
2873  }
2874 
2879  public function convertForSearchResult( $termsArray ) {
2880  # some languages, e.g. Chinese, need to do a conversion
2881  # in order for search results to be displayed correctly
2882  return $termsArray;
2883  }
2884 
2891  function firstChar( $s ) {
2892  $matches = [];
2893  preg_match(
2894  '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2895  '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2896  $s,
2897  $matches
2898  );
2899 
2900  if ( isset( $matches[1] ) ) {
2901  if ( strlen( $matches[1] ) != 3 ) {
2902  return $matches[1];
2903  }
2904 
2905  // Break down Hangul syllables to grab the first jamo
2906  $code = UtfNormal\Utils::utf8ToCodepoint( $matches[1] );
2907  if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2908  return $matches[1];
2909  } elseif ( $code < 0xb098 ) {
2910  return "\u{3131}";
2911  } elseif ( $code < 0xb2e4 ) {
2912  return "\u{3134}";
2913  } elseif ( $code < 0xb77c ) {
2914  return "\u{3137}";
2915  } elseif ( $code < 0xb9c8 ) {
2916  return "\u{3139}";
2917  } elseif ( $code < 0xbc14 ) {
2918  return "\u{3141}";
2919  } elseif ( $code < 0xc0ac ) {
2920  return "\u{3142}";
2921  } elseif ( $code < 0xc544 ) {
2922  return "\u{3145}";
2923  } elseif ( $code < 0xc790 ) {
2924  return "\u{3147}";
2925  } elseif ( $code < 0xcc28 ) {
2926  return "\u{3148}";
2927  } elseif ( $code < 0xce74 ) {
2928  return "\u{314A}";
2929  } elseif ( $code < 0xd0c0 ) {
2930  return "\u{314B}";
2931  } elseif ( $code < 0xd30c ) {
2932  return "\u{314C}";
2933  } elseif ( $code < 0xd558 ) {
2934  return "\u{314D}";
2935  } else {
2936  return "\u{314E}";
2937  }
2938  } else {
2939  return '';
2940  }
2941  }
2942 
2954  public function normalize( $s ) {
2955  global $wgAllUnicodeFixes;
2956  $s = UtfNormal\Validator::cleanUp( $s );
2957  if ( $wgAllUnicodeFixes ) {
2958  $s = $this->transformUsingPairFile( 'normalize-ar.php', $s );
2959  $s = $this->transformUsingPairFile( 'normalize-ml.php', $s );
2960  }
2961 
2962  return $s;
2963  }
2964 
2979  protected function transformUsingPairFile( $file, $string ) {
2980  if ( !isset( $this->transformData[$file] ) ) {
2981  global $IP;
2982  $data = require "$IP/languages/data/{$file}";
2983  $this->transformData[$file] = new ReplacementArray( $data );
2984  }
2985  return $this->transformData[$file]->replace( $string );
2986  }
2987 
2993  public function isRTL() {
2994  return $this->localisationCache->getItem( $this->mCode, 'rtl' );
2995  }
2996 
3001  public function getDir() {
3002  return $this->isRTL() ? 'rtl' : 'ltr';
3003  }
3004 
3013  public function alignStart() {
3014  return $this->isRTL() ? 'right' : 'left';
3015  }
3016 
3025  public function alignEnd() {
3026  return $this->isRTL() ? 'left' : 'right';
3027  }
3028 
3040  public function getDirMarkEntity( $opposite = false ) {
3041  if ( $opposite ) {
3042  return $this->isRTL() ? '&lrm;' : '&rlm;';
3043  }
3044  return $this->isRTL() ? '&rlm;' : '&lrm;';
3045  }
3046 
3057  public function getDirMark( $opposite = false ) {
3058  $lrm = "\u{200E}"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3059  $rlm = "\u{200F}"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3060  if ( $opposite ) {
3061  return $this->isRTL() ? $lrm : $rlm;
3062  }
3063  return $this->isRTL() ? $rlm : $lrm;
3064  }
3065 
3069  public function capitalizeAllNouns() {
3070  return $this->localisationCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3071  }
3072 
3080  public function getArrow( $direction = 'forwards' ) {
3081  switch ( $direction ) {
3082  case 'forwards':
3083  return $this->isRTL() ? '←' : '→';
3084  case 'backwards':
3085  return $this->isRTL() ? '→' : '←';
3086  case 'left':
3087  return '←';
3088  case 'right':
3089  return '→';
3090  case 'up':
3091  return '↑';
3092  case 'down':
3093  return '↓';
3094  }
3095  }
3096 
3102  public function linkPrefixExtension() {
3103  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixExtension' );
3104  }
3105 
3110  public function getMagicWords() {
3111  return $this->localisationCache->getItem( $this->mCode, 'magicWords' );
3112  }
3113 
3119  public function getMagic( $mw ) {
3120  $rawEntry = $this->mMagicExtensions[$mw->mId] ??
3121  $this->localisationCache->getSubitem( $this->mCode, 'magicWords', $mw->mId );
3122 
3123  if ( !is_array( $rawEntry ) ) {
3124  wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3125  } else {
3126  $mw->mCaseSensitive = $rawEntry[0];
3127  $mw->mSynonyms = array_slice( $rawEntry, 1 );
3128  }
3129  }
3130 
3136  public function getSpecialPageAliases() {
3137  // Cache aliases because it may be slow to load them
3138  if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3139  // Initialise array
3140  $this->mExtendedSpecialPageAliases =
3141  $this->localisationCache->getItem( $this->mCode, 'specialPageAliases' );
3142  }
3143 
3145  }
3146 
3153  function emphasize( $text ) {
3154  return "<em>$text</em>";
3155  }
3156 
3179  public function formatNum( $number, $nocommafy = false ) {
3180  global $wgTranslateNumerals;
3181  if ( !$nocommafy ) {
3182  $number = $this->commafy( $number );
3183  $s = $this->separatorTransformTable();
3184  if ( $s ) {
3185  $number = strtr( $number, $s );
3186  }
3187  }
3188 
3189  if ( $wgTranslateNumerals ) {
3190  $s = $this->digitTransformTable();
3191  if ( $s ) {
3192  $number = strtr( $number, $s );
3193  }
3194  }
3195 
3196  return (string)$number;
3197  }
3198 
3207  public function formatNumNoSeparators( $number ) {
3208  return $this->formatNum( $number, true );
3209  }
3210 
3215  public function parseFormattedNumber( $number ) {
3216  $s = $this->digitTransformTable();
3217  if ( $s ) {
3218  // eliminate empty array values such as ''. (T66347)
3219  $s = array_filter( $s );
3220  $number = strtr( $number, array_flip( $s ) );
3221  }
3222 
3223  $s = $this->separatorTransformTable();
3224  if ( $s ) {
3225  // eliminate empty array values such as ''. (T66347)
3226  $s = array_filter( $s );
3227  $number = strtr( $number, array_flip( $s ) );
3228  }
3229 
3230  $number = strtr( $number, [ ',' => '' ] );
3231  return $number;
3232  }
3233 
3242  function commafy( $number ) {
3245  if ( $number === null ) {
3246  return '';
3247  }
3248 
3249  if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3250  // Default grouping is at thousands, use the same for ###,###,### pattern too.
3251  // In some languages it's conventional not to insert a thousands separator
3252  // in numbers that are four digits long (1000-9999).
3253  if ( $minimumGroupingDigits ) {
3254  // Number of '#' characters after last comma in the grouping pattern.
3255  // The pattern is hardcoded here, but this would vary for different patterns.
3256  $primaryGroupingSize = 3;
3257  // Maximum length of a number to suppress digit grouping for.
3258  $maximumLength = $minimumGroupingDigits + $primaryGroupingSize - 1;
3259  if ( preg_match( '/^\-?\d{1,' . $maximumLength . '}(\.\d+)?$/', $number ) ) {
3260  return $number;
3261  }
3262  }
3263  return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3264  } else {
3265  // Ref: http://cldr.unicode.org/translation/number-patterns
3266  $sign = "";
3267  if ( intval( $number ) < 0 ) {
3268  // For negative numbers apply the algorithm like positive number and add sign.
3269  $sign = "-";
3270  $number = substr( $number, 1 );
3271  }
3272  $integerPart = [];
3273  $decimalPart = [];
3274  $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3275  preg_match( "/\d+/", $number, $integerPart );
3276  preg_match( "/\.\d*/", $number, $decimalPart );
3277  $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3278  if ( $groupedNumber === $number ) {
3279  // the string does not have any number part. Eg: .12345
3280  return $sign . $groupedNumber;
3281  }
3282  $start = $end = ( $integerPart ) ? strlen( $integerPart[0] ) : 0;
3283  while ( $start > 0 ) {
3284  $match = $matches[0][$numMatches - 1];
3285  $matchLen = strlen( $match );
3286  $start = $end - $matchLen;
3287  if ( $start < 0 ) {
3288  $start = 0;
3289  }
3290  $groupedNumber = substr( $number, $start, $end - $start ) . $groupedNumber;
3291  $end = $start;
3292  if ( $numMatches > 1 ) {
3293  // use the last pattern for the rest of the number
3294  $numMatches--;
3295  }
3296  if ( $start > 0 ) {
3297  $groupedNumber = "," . $groupedNumber;
3298  }
3299  }
3300  return $sign . $groupedNumber;
3301  }
3302  }
3303 
3307  public function digitGroupingPattern() {
3308  return $this->localisationCache->getItem( $this->mCode, 'digitGroupingPattern' );
3309  }
3310 
3314  public function digitTransformTable() {
3315  return $this->localisationCache->getItem( $this->mCode, 'digitTransformTable' );
3316  }
3317 
3321  public function separatorTransformTable() {
3322  return $this->localisationCache->getItem( $this->mCode, 'separatorTransformTable' );
3323  }
3324 
3328  public function minimumGroupingDigits() {
3329  return $this->localisationCache->getItem( $this->mCode, 'minimumGroupingDigits' );
3330  }
3331 
3340  public function listToText( array $list ) {
3341  $itemCount = count( $list );
3342  if ( $itemCount < 1 ) {
3343  return '';
3344  }
3345  $text = array_pop( $list );
3346  if ( $itemCount > 1 ) {
3347  $and = $this->msg( 'and' )->escaped();
3348  $space = $this->msg( 'word-separator' )->escaped();
3349  $comma = '';
3350  if ( $itemCount > 2 ) {
3351  $comma = $this->msg( 'comma-separator' )->escaped();
3352  }
3353  $text = implode( $comma, $list ) . $and . $space . $text;
3354  }
3355  return $text;
3356  }
3357 
3364  public function commaList( array $list ) {
3365  return implode(
3366  wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3367  $list
3368  );
3369  }
3370 
3377  public function semicolonList( array $list ) {
3378  return implode(
3379  wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3380  $list
3381  );
3382  }
3383 
3389  public function pipeList( array $list ) {
3390  return implode(
3391  wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3392  $list
3393  );
3394  }
3395 
3411  public function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3412  return $this->truncateInternal(
3413  $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
3414  );
3415  }
3416 
3435  public function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3436  // Passing encoding to mb_strlen and mb_substr is optional.
3437  // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
3438  // explicit specification of encoding is skipped.
3439  // Note: Both multibyte methods are callables invoked in truncateInternal.
3440  return $this->truncateInternal(
3441  $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
3442  );
3443  }
3444 
3461  private function truncateInternal(
3462  $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring
3463  ) {
3464  # Check if there is no need to truncate
3465  if ( $measureLength( $string ) <= abs( $length ) ) {
3466  return $string; // no need to truncate
3467  }
3468 
3469  # Use the localized ellipsis character
3470  if ( $ellipsis == '...' ) {
3471  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3472  }
3473  if ( $length == 0 ) {
3474  return $ellipsis; // convention
3475  }
3476 
3477  $stringOriginal = $string;
3478  # If ellipsis length is >= $length then we can't apply $adjustLength
3479  if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
3480  $string = $ellipsis; // this can be slightly unexpected
3481  # Otherwise, truncate and add ellipsis...
3482  } else {
3483  $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
3484  if ( $length > 0 ) {
3485  $length -= $ellipsisLength;
3486  $string = $getSubstring( $string, 0, $length ); // xyz...
3487  $string = $this->removeBadCharLast( $string );
3488  $string = rtrim( $string ) . $ellipsis;
3489  } else {
3490  $length += $ellipsisLength;
3491  $string = $getSubstring( $string, $length ); // ...xyz
3492  $string = $this->removeBadCharFirst( $string );
3493  $string = $ellipsis . ltrim( $string );
3494  }
3495  }
3496 
3497  # Do not truncate if the ellipsis makes the string longer/equal (T24181).
3498  # This check is *not* redundant if $adjustLength, due to the single case where
3499  # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3500  if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
3501  return $string;
3502  } else {
3503  return $stringOriginal;
3504  }
3505  }
3506 
3514  protected function removeBadCharLast( $string ) {
3515  if ( $string != '' ) {
3516  $char = ord( $string[strlen( $string ) - 1] );
3517  $m = [];
3518  if ( $char >= 0xc0 ) {
3519  # We got the first byte only of a multibyte char; remove it.
3520  $string = substr( $string, 0, -1 );
3521  } elseif ( $char >= 0x80 &&
3522  // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3523  preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3524  '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3525  ) {
3526  # We chopped in the middle of a character; remove it
3527  $string = $m[1];
3528  }
3529  }
3530  return $string;
3531  }
3532 
3540  protected function removeBadCharFirst( $string ) {
3541  if ( $string != '' ) {
3542  $char = ord( $string[0] );
3543  if ( $char >= 0x80 && $char < 0xc0 ) {
3544  # We chopped in the middle of a character; remove the whole thing
3545  $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3546  }
3547  }
3548  return $string;
3549  }
3550 
3566  public function truncateHtml( $text, $length, $ellipsis = '...' ) {
3567  # Use the localized ellipsis character
3568  if ( $ellipsis == '...' ) {
3569  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3570  }
3571  # Check if there is clearly no need to truncate
3572  if ( $length <= 0 ) {
3573  return $ellipsis; // no text shown, nothing to format (convention)
3574  } elseif ( strlen( $text ) <= $length ) {
3575  return $text; // string short enough even *with* HTML (short-circuit)
3576  }
3577 
3578  $dispLen = 0; // innerHTML legth so far
3579  $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3580  $tagType = 0; // 0-open, 1-close
3581  $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3582  $entityState = 0; // 0-not entity, 1-entity
3583  $tag = $ret = ''; // accumulated tag name, accumulated result string
3584  $openTags = []; // open tag stack
3585  $maybeState = null; // possible truncation state
3586 
3587  $textLen = strlen( $text );
3588  $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3589  for ( $pos = 0; true; ++$pos ) {
3590  # Consider truncation once the display length has reached the maximim.
3591  # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3592  # Check that we're not in the middle of a bracket/entity...
3593  if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3594  if ( !$testingEllipsis ) {
3595  $testingEllipsis = true;
3596  # Save where we are; we will truncate here unless there turn out to
3597  # be so few remaining characters that truncation is not necessary.
3598  if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3599  $maybeState = [ $ret, $openTags ]; // save state
3600  }
3601  } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3602  # String in fact does need truncation, the truncation point was OK.
3603  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
3604  list( $ret, $openTags ) = $maybeState; // reload state
3605  $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3606  $ret .= $ellipsis; // add ellipsis
3607  break;
3608  }
3609  }
3610  if ( $pos >= $textLen ) {
3611  break; // extra iteration just for above checks
3612  }
3613 
3614  # Read the next char...
3615  $ch = $text[$pos];
3616  $lastCh = $pos ? $text[$pos - 1] : '';
3617  $ret .= $ch; // add to result string
3618  if ( $ch == '<' ) {
3619  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3620  $entityState = 0; // for bad HTML
3621  $bracketState = 1; // tag started (checking for backslash)
3622  } elseif ( $ch == '>' ) {
3623  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3624  $entityState = 0; // for bad HTML
3625  $bracketState = 0; // out of brackets
3626  } elseif ( $bracketState == 1 ) {
3627  if ( $ch == '/' ) {
3628  $tagType = 1; // close tag (e.g. "</span>")
3629  } else {
3630  $tagType = 0; // open tag (e.g. "<span>")
3631  $tag .= $ch;
3632  }
3633  $bracketState = 2; // building tag name
3634  } elseif ( $bracketState == 2 ) {
3635  if ( $ch != ' ' ) {
3636  $tag .= $ch;
3637  } else {
3638  // Name found (e.g. "<a href=..."), add on tag attributes...
3639  $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3640  }
3641  } elseif ( $bracketState == 0 ) {
3642  if ( $entityState ) {
3643  if ( $ch == ';' ) {
3644  $entityState = 0;
3645  $dispLen++; // entity is one displayed char
3646  }
3647  } else {
3648  if ( $neLength == 0 && !$maybeState ) {
3649  // Save state without $ch. We want to *hit* the first
3650  // display char (to get tags) but not *use* it if truncating.
3651  $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3652  }
3653  if ( $ch == '&' ) {
3654  $entityState = 1; // entity found, (e.g. "&#160;")
3655  } else {
3656  $dispLen++; // this char is displayed
3657  // Add the next $max display text chars after this in one swoop...
3658  $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3659  $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3660  $dispLen += $skipped;
3661  $pos += $skipped;
3662  }
3663  }
3664  }
3665  }
3666  // Close the last tag if left unclosed by bad HTML
3667  $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3668  while ( count( $openTags ) > 0 ) {
3669  $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3670  }
3671  return $ret;
3672  }
3673 
3685  private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3686  if ( $len === null ) {
3687  $len = -1; // -1 means "no limit" for strcspn
3688  } elseif ( $len < 0 ) {
3689  $len = 0; // sanity
3690  }
3691  $skipCount = 0;
3692  if ( $start < strlen( $text ) ) {
3693  $skipCount = strcspn( $text, $search, $start, $len );
3694  $ret .= substr( $text, $start, $skipCount );
3695  }
3696  return $skipCount;
3697  }
3698 
3708  private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3709  $tag = ltrim( $tag );
3710  if ( $tag != '' ) {
3711  if ( $tagType == 0 && $lastCh != '/' ) {
3712  $openTags[] = $tag; // tag opened (didn't close itself)
3713  } elseif ( $tagType == 1 ) {
3714  if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3715  array_pop( $openTags ); // tag closed
3716  }
3717  }
3718  $tag = '';
3719  }
3720  }
3721 
3730  public function convertGrammar( $word, $case ) {
3731  global $wgGrammarForms;
3732  if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3733  return $wgGrammarForms[$this->getCode()][$case][$word];
3734  }
3735 
3736  $grammarTransformations = $this->getGrammarTransformations();
3737 
3738  if ( isset( $grammarTransformations[$case] ) ) {
3739  $forms = $grammarTransformations[$case];
3740 
3741  // Some names of grammar rules are aliases for other rules.
3742  // In such cases the value is a string rather than object,
3743  // so load the actual rules.
3744  if ( is_string( $forms ) ) {
3745  $forms = $grammarTransformations[$forms];
3746  }
3747 
3748  foreach ( array_values( $forms ) as $rule ) {
3749  $form = $rule[0];
3750 
3751  if ( $form === '@metadata' ) {
3752  continue;
3753  }
3754 
3755  $replacement = $rule[1];
3756 
3757  $regex = '/' . addcslashes( $form, '/' ) . '/u';
3758  $patternMatches = preg_match( $regex, $word );
3759 
3760  if ( $patternMatches === false ) {
3761  wfLogWarning(
3762  'An error occurred while processing grammar. ' .
3763  "Word: '$word'. Regex: /$form/."
3764  );
3765  } elseif ( $patternMatches === 1 ) {
3766  $word = preg_replace( $regex, $replacement, $word );
3767 
3768  break;
3769  }
3770  }
3771  }
3772 
3773  return $word;
3774  }
3775 
3781  public function getGrammarForms() {
3782  global $wgGrammarForms;
3783  if ( isset( $wgGrammarForms[$this->getCode()] )
3784  && is_array( $wgGrammarForms[$this->getCode()] )
3785  ) {
3786  return $wgGrammarForms[$this->getCode()];
3787  }
3788 
3789  return [];
3790  }
3791 
3801  public function getGrammarTransformations() {
3802  if ( $this->grammarTransformCache !== null ) {
3804  }
3805 
3806  $grammarDataFile = __DIR__ . "/data/grammarTransformations/{$this->getCode()}.json";
3807 
3808  $this->grammarTransformCache = is_readable( $grammarDataFile )
3809  ? FormatJson::decode( file_get_contents( $grammarDataFile ), true )
3810  : [];
3811 
3812  if ( $this->grammarTransformCache === null ) {
3813  throw new MWException( "Invalid grammar data for \"{$this->getCode()}\"." );
3814  }
3815 
3817  }
3818 
3838  public function gender( $gender, $forms ) {
3839  if ( !count( $forms ) ) {
3840  return '';
3841  }
3842  $forms = $this->preConvertPlural( $forms, 2 );
3843  if ( $gender === 'male' ) {
3844  return $forms[0];
3845  }
3846  if ( $gender === 'female' ) {
3847  return $forms[1];
3848  }
3849  return $forms[2] ?? $forms[0];
3850  }
3851 
3867  public function convertPlural( $count, $forms ) {
3868  // Handle explicit n=pluralform cases
3869  $forms = $this->handleExplicitPluralForms( $count, $forms );
3870  if ( is_string( $forms ) ) {
3871  return $forms;
3872  }
3873  if ( !count( $forms ) ) {
3874  return '';
3875  }
3876 
3877  $pluralForm = $this->getPluralRuleIndexNumber( $count );
3878  $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3879  return $forms[$pluralForm];
3880  }
3881 
3897  protected function handleExplicitPluralForms( $count, array $forms ) {
3898  foreach ( $forms as $index => $form ) {
3899  if ( preg_match( '/\d+=/i', $form ) ) {
3900  $pos = strpos( $form, '=' );
3901  if ( substr( $form, 0, $pos ) === (string)$count ) {
3902  return substr( $form, $pos + 1 );
3903  }
3904  unset( $forms[$index] );
3905  }
3906  }
3907  return array_values( $forms );
3908  }
3909 
3918  protected function preConvertPlural( /* Array */ $forms, $count ) {
3919  return array_pad( $forms, $count, end( $forms ) );
3920  }
3921 
3938  public function embedBidi( $text = '' ) {
3939  $dir = self::strongDirFromContent( $text );
3940  if ( $dir === 'ltr' ) {
3941  // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
3942  return self::LRE . $text . self::PDF;
3943  }
3944  if ( $dir === 'rtl' ) {
3945  // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
3946  return self::RLE . $text . self::PDF;
3947  }
3948  // No strong directionality: do not wrap
3949  return $text;
3950  }
3951 
3965  public function translateBlockExpiry( $str, User $user = null, $now = 0 ) {
3966  $duration = SpecialBlock::getSuggestedDurations( $this );
3967  foreach ( $duration as $show => $value ) {
3968  if ( strcmp( $str, $value ) == 0 ) {
3969  return htmlspecialchars( trim( $show ) );
3970  }
3971  }
3972 
3973  if ( wfIsInfinity( $str ) ) {
3974  foreach ( $duration as $show => $value ) {
3975  if ( wfIsInfinity( $value ) ) {
3976  return htmlspecialchars( trim( $show ) );
3977  }
3978  }
3979  }
3980 
3981  // If all else fails, return a standard duration or timestamp description.
3982  $time = strtotime( $str, $now );
3983  if ( $time === false ) { // Unknown format. Return it as-is in case.
3984  return $str;
3985  } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
3986  // The result differs based on current time, so the difference
3987  // is a fixed duration length.
3988  return $this->formatDuration( $time - $now );
3989  } else { // It's an absolute timestamp.
3990  if ( $time === 0 ) {
3991  // wfTimestamp() handles 0 as current time instead of epoch.
3992  $time = '19700101000000';
3993  }
3994  if ( $user ) {
3995  return $this->userTimeAndDate( $time, $user );
3996  }
3997  return $this->timeanddate( $time );
3998  }
3999  }
4000 
4008  public function segmentForDiff( $text ) {
4009  return $text;
4010  }
4011 
4018  public function unsegmentForDiff( $text ) {
4019  return $text;
4020  }
4021 
4028  protected function newConverter() {
4029  return new FakeConverter( $this );
4030  }
4031 
4038  public function getConverter() {
4039  return $this->mConverter;
4040  }
4041 
4050  public function autoConvert( $text, $variant = false ) {
4051  return $this->mConverter->autoConvert( $text, $variant );
4052  }
4053 
4060  public function autoConvertToAllVariants( $text ) {
4061  return $this->mConverter->autoConvertToAllVariants( $text );
4062  }
4063 
4075  public function convert( $text ) {
4076  return $this->mConverter->convert( $text );
4077  }
4078 
4085  public function convertTitle( $title ) {
4086  return $this->mConverter->convertTitle( $title );
4087  }
4088 
4097  public function convertNamespace( $ns, $variant = null ) {
4098  return $this->mConverter->convertNamespace( $ns, $variant );
4099  }
4100 
4106  public function hasVariants() {
4107  return count( $this->getVariants() ) > 1;
4108  }
4109 
4120  public function hasVariant( $variant ) {
4121  return $variant && ( $variant === $this->mConverter->validateVariant( $variant ) );
4122  }
4123 
4130  public function convertHtml( $text ) {
4131  return htmlspecialchars( $this->convert( $text ) );
4132  }
4133 
4138  public function convertCategoryKey( $key ) {
4139  return $this->mConverter->convertCategoryKey( $key );
4140  }
4141 
4148  public function getVariants() {
4149  return $this->mConverter->getVariants();
4150  }
4151 
4155  public function getPreferredVariant() {
4156  return $this->mConverter->getPreferredVariant();
4157  }
4158 
4162  public function getDefaultVariant() {
4163  return $this->mConverter->getDefaultVariant();
4164  }
4165 
4169  public function getURLVariant() {
4170  return $this->mConverter->getURLVariant();
4171  }
4172 
4185  public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4186  $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
4187  }
4188 
4195  public function getExtraHashOptions() {
4196  return $this->mConverter->getExtraHashOptions();
4197  }
4198 
4205  public function updateConversionTable( Title $title ) {
4206  $this->mConverter->updateConversionTable( $title );
4207  }
4208 
4215  public function linkTrail() {
4216  return $this->localisationCache->getItem( $this->mCode, 'linkTrail' );
4217  }
4218 
4225  public function linkPrefixCharset() {
4226  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixCharset' );
4227  }
4228 
4237  public function getParentLanguage() {
4238  return MediaWikiServices::getInstance()->getLanguageFactory()
4239  ->getParentLanguage( $this->getCode() );
4240  }
4241 
4249  public function equals( Language $lang ) {
4250  return $lang === $this || $lang->getCode() === $this->mCode;
4251  }
4252 
4261  public function getCode() {
4262  return $this->mCode;
4263  }
4264 
4275  public function getHtmlCode() {
4276  if ( is_null( $this->mHtmlCode ) ) {
4277  $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
4278  }
4279  return $this->mHtmlCode;
4280  }
4281 
4289  public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4290  $m = null;
4291  preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4292  preg_quote( $suffix, '/' ) . '/', $filename, $m );
4293  if ( !count( $m ) ) {
4294  return false;
4295  }
4296  return str_replace( '_', '-', strtolower( $m[1] ) );
4297  }
4298 
4307  public static function classFromCode( $code, $fallback = true ) {
4308  wfDeprecated( __METHOD__, '1.35' );
4309 
4310  if ( $fallback && $code == 'en' ) {
4311  return 'Language';
4312  } else {
4313  return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
4314  }
4315  }
4316 
4327  public static function getFileName( $prefix, $code, $suffix = '.php' ) {
4328  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4329  ->getFileName( $prefix, $code, $suffix );
4330  }
4331 
4337  public static function getMessagesFileName( $code ) {
4338  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4339  ->getMessagesFileName( $code );
4340  }
4341 
4349  public static function getJsonMessagesFileName( $code ) {
4350  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4351  ->getJsonMessagesFileName( $code );
4352  }
4353 
4362  public static function getFallbackFor( $code ) {
4363  return MediaWikiServices::getInstance()->getLanguageFallback()->getFirst( $code )
4364  ?? false;
4365  }
4366 
4379  public static function getFallbacksFor( $code, $mode = self::MESSAGES_FALLBACKS ) {
4380  return MediaWikiServices::getInstance()->getLanguageFallback()->getAll( $code, $mode );
4381  }
4382 
4393  public static function getFallbacksIncludingSiteLanguage( $code ) {
4394  return MediaWikiServices::getInstance()->getLanguageFallback()
4395  ->getAllIncludingSiteLanguage( $code );
4396  }
4397 
4409  public static function getMessagesFor( $code ) {
4410  return self::getLocalisationCache()->getItem( $code, 'messages' );
4411  }
4412 
4423  public static function getMessageFor( $key, $code ) {
4424  return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4425  }
4426 
4437  public static function getMessageKeysFor( $code ) {
4438  return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
4439  }
4440 
4445  private function fixVariableInNamespace( $talk ) {
4446  if ( strpos( $talk, '$1' ) === false ) {
4447  return $talk;
4448  }
4449 
4450  global $wgMetaNamespace;
4451  $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4452 
4453  # Allow grammar transformations
4454  # Allowing full message-style parsing would make simple requests
4455  # such as action=raw much more expensive than they need to be.
4456  # This will hopefully cover most cases.
4457  $talk = preg_replace_callback(
4458  '/{{grammar:(.*?)\|(.*?)}}/i',
4459  function ( $m ) {
4460  return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4461  },
4462  $talk
4463  );
4464  return str_replace( ' ', '_', $talk );
4465  }
4466 
4477  public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
4478  static $dbInfinity;
4479  if ( $dbInfinity === null ) {
4480  $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
4481  }
4482 
4483  if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4484  return $format === true
4485  ? $this->getMessageFromDB( 'infiniteblock' )
4486  : $infinity;
4487  } else {
4488  return $format === true
4489  ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4490  : wfTimestamp( $format, $expiry );
4491  }
4492  }
4493 
4508  public function formatTimePeriod( $seconds, $format = [] ) {
4509  if ( !is_array( $format ) ) {
4510  $format = [ 'avoid' => $format ]; // For backwards compatibility
4511  }
4512  if ( !isset( $format['avoid'] ) ) {
4513  $format['avoid'] = false;
4514  }
4515  if ( !isset( $format['noabbrevs'] ) ) {
4516  $format['noabbrevs'] = false;
4517  }
4518  $secondsMsg = wfMessage(
4519  $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4520  $minutesMsg = wfMessage(
4521  $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4522  $hoursMsg = wfMessage(
4523  $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4524  $daysMsg = wfMessage(
4525  $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4526 
4527  if ( round( $seconds * 10 ) < 100 ) {
4528  $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4529  $s = $secondsMsg->params( $s )->text();
4530  } elseif ( round( $seconds ) < 60 ) {
4531  $s = $this->formatNum( round( $seconds ) );
4532  $s = $secondsMsg->params( $s )->text();
4533  } elseif ( round( $seconds ) < 3600 ) {
4534  $minutes = floor( $seconds / 60 );
4535  $secondsPart = round( fmod( $seconds, 60 ) );
4536  if ( $secondsPart == 60 ) {
4537  $secondsPart = 0;
4538  $minutes++;
4539  }
4540  $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4541  $s .= ' ';
4542  $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4543  } elseif ( round( $seconds ) <= 2 * 86400 ) {
4544  $hours = floor( $seconds / 3600 );
4545  $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4546  $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4547  if ( $secondsPart == 60 ) {
4548  $secondsPart = 0;
4549  $minutes++;
4550  }
4551  if ( $minutes == 60 ) {
4552  $minutes = 0;
4553  $hours++;
4554  }
4555  $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4556  $s .= ' ';
4557  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4558  if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes', 'avoidhours' ] ) ) {
4559  $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4560  }
4561  } else {
4562  $days = floor( $seconds / 86400 );
4563  if ( $format['avoid'] === 'avoidhours' ) {
4564  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4565  if ( $hours == 24 ) {
4566  $hours = 0;
4567  $days++;
4568  }
4569  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4570  } elseif ( $format['avoid'] === 'avoidminutes' ) {
4571  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4572  if ( $hours == 24 ) {
4573  $hours = 0;
4574  $days++;
4575  }
4576  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4577  $s .= ' ';
4578  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4579  } elseif ( $format['avoid'] === 'avoidseconds' ) {
4580  $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4581  $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4582  if ( $minutes == 60 ) {
4583  $minutes = 0;
4584  $hours++;
4585  }
4586  if ( $hours == 24 ) {
4587  $hours = 0;
4588  $days++;
4589  }
4590  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4591  $s .= ' ';
4592  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4593  $s .= ' ';
4594  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4595  } else {
4596  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4597  $s .= ' ';
4598  $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4599  }
4600  }
4601  return $s;
4602  }
4603 
4615  public function formatBitrate( $bps ) {
4616  return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4617  }
4618 
4625  public function formatComputingNumbers( $size, $boundary, $messageKey ) {
4626  if ( $size <= 0 ) {
4627  return str_replace( '$1', $this->formatNum( $size ),
4628  $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4629  );
4630  }
4631  $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' ];
4632  $index = 0;
4633 
4634  $maxIndex = count( $sizes ) - 1;
4635  while ( $size >= $boundary && $index < $maxIndex ) {
4636  $index++;
4637  $size /= $boundary;
4638  }
4639 
4640  // For small sizes no decimal places necessary
4641  $round = 0;
4642  if ( $index > 1 ) {
4643  // For MB and bigger two decimal places are smarter
4644  $round = 2;
4645  }
4646  $msg = str_replace( '$1', $sizes[$index], $messageKey );
4647 
4648  $size = round( $size, $round );
4649  $text = $this->getMessageFromDB( $msg );
4650  return str_replace( '$1', $this->formatNum( $size ), $text );
4651  }
4652 
4663  public function formatSize( $size ) {
4664  return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4665  }
4666 
4676  public function specialList( $page, $details, $oppositedm = true ) {
4677  if ( !$details ) {
4678  return $page;
4679  }
4680 
4681  $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4682  return $page .
4683  $dirmark .
4684  $this->msg( 'word-separator' )->escaped() .
4685  $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4686  }
4687 
4700  public function viewPrevNext( Title $title, $offset, $limit,
4701  array $query = [], $atend = false
4702  ) {
4703  wfDeprecated( __METHOD__, '1.34' );
4704  // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4705 
4706  # Make 'previous' link
4707  $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4708  if ( $offset > 0 ) {
4709  $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4710  $query, $prev, 'prevn-title', 'mw-prevlink' );
4711  } else {
4712  $plink = htmlspecialchars( $prev );
4713  }
4714 
4715  # Make 'next' link
4716  $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4717  if ( $atend ) {
4718  $nlink = htmlspecialchars( $next );
4719  } else {
4720  $nlink = $this->numLink( $title, $offset + $limit, $limit,
4721  $query, $next, 'nextn-title', 'mw-nextlink' );
4722  }
4723 
4724  # Make links to set number of items per page
4725  $numLinks = [];
4726  foreach ( [ 20, 50, 100, 250, 500 ] as $num ) {
4727  $numLinks[] = $this->numLink( $title, $offset, $num,
4728  $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4729  }
4730 
4731  return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4732  )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4733  }
4734 
4747  private function numLink( Title $title, $offset, $limit, array $query, $link,
4748  $tooltipMsg, $class
4749  ) {
4750  $query = [ 'limit' => $limit, 'offset' => $offset ] + $query;
4751  $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4752  ->numParams( $limit )->text();
4753 
4754  return Html::element( 'a', [ 'href' => $title->getLocalURL( $query ),
4755  'title' => $tooltip, 'class' => $class ], $link );
4756  }
4757 
4763  public function getConvRuleTitle() {
4764  return $this->mConverter->getConvRuleTitle();
4765  }
4766 
4772  public function getCompiledPluralRules() {
4773  $pluralRules =
4774  $this->localisationCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4775  $fallbacks = $this->langFallback->getAll( $this->mCode );
4776  if ( !$pluralRules ) {
4777  foreach ( $fallbacks as $fallbackCode ) {
4778  $pluralRules = $this->localisationCache
4779  ->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4780  if ( $pluralRules ) {
4781  break;
4782  }
4783  }
4784  }
4785  return $pluralRules;
4786  }
4787 
4793  public function getPluralRules() {
4794  $pluralRules =
4795  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4796  $fallbacks = $this->langFallback->getAll( $this->mCode );
4797  if ( !$pluralRules ) {
4798  foreach ( $fallbacks as $fallbackCode ) {
4799  $pluralRules = $this->localisationCache
4800  ->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4801  if ( $pluralRules ) {
4802  break;
4803  }
4804  }
4805  }
4806  return $pluralRules;
4807  }
4808 
4814  public function getPluralRuleTypes() {
4815  $pluralRuleTypes =
4816  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4817  $fallbacks = $this->langFallback->getAll( $this->mCode );
4818  if ( !$pluralRuleTypes ) {
4819  foreach ( $fallbacks as $fallbackCode ) {
4820  $pluralRuleTypes = $this->localisationCache
4821  ->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4822  if ( $pluralRuleTypes ) {
4823  break;
4824  }
4825  }
4826  }
4827  return $pluralRuleTypes;
4828  }
4829 
4835  public function getPluralRuleIndexNumber( $number ) {
4836  $pluralRules = $this->getCompiledPluralRules();
4837  $form = Evaluator::evaluateCompiled( $number, $pluralRules );
4838  return $form;
4839  }
4840 
4849  public function getPluralRuleType( $number ) {
4850  $index = $this->getPluralRuleIndexNumber( $number );
4851  $pluralRuleTypes = $this->getPluralRuleTypes();
4852  return $pluralRuleTypes[$index] ?? 'other';
4853  }
4854 }
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
getMessage( $key)
Definition: Language.php:2581
getPluralRuleType( $number)
Find the plural rule type appropriate for the given number For example, if the language is set to Ara...
Definition: Language.php:4849
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
static $mMonthAbbrevMsgs
Definition: Language.php:181
getSpecialPageAliases()
Get special page names, as an associative array canonical name => array of valid names, including aliases.
Definition: Language.php:3136
static array $mLangObjCache
Definition: Language.php:101
getPluralRuleTypes()
Get the plural rule types for the language.
Definition: Language.php:4814
firstChar( $s)
Get the first character of a string.
Definition: Language.php:2891
getHumanTimestamp(MWTimestamp $time, MWTimestamp $relativeTo=null, User $user=null)
Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
Definition: Language.php:2475
static getLocalisationCache()
Get the LocalisationCache instance.
Definition: Language.php:446
Wrapper around strtr() that holds replacements.
ucwords( $str)
Definition: Language.php:2710
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
static hebrewNumeral( $num)
Hebrew Gematria number formatting up to 9999.
Definition: Language.php:2004
translateBlockExpiry( $str, User $user=null, $now=0)
Definition: Language.php:3965
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
segmentByWord( $string)
Some languages such as Chinese require word segmentation, Specify such segmentation when overridden i...
Definition: Language.php:2826
normalize( $s)
Convert a UTF-8 string to normal form C.
Definition: Language.php:2954
handleExplicitPluralForms( $count, array $forms)
Handles explicit plural forms for Language::convertPlural()
Definition: Language.php:3897
getDurationIntervals( $seconds, array $chosenIntervals=[])
Takes a number of seconds and returns an array with a set of corresponding intervals.
Definition: Language.php:2320
getVariantname( $code, $usemsg=true)
short names for language variants used for language conversion links.
Definition: Language.php:785
setNamespaces(array $namespaces)
Arbitrarily set all of the namespace names at once.
Definition: Language.php:567
removeBadCharLast( $string)
Remove bytes that represent an incomplete Unicode character at the end of string (e.g.
Definition: Language.php:3514
static romanNumeral( $num)
Roman number formatting up to 10000.
Definition: Language.php:1973
getDirMark( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3057
getHtmlCode()
Get the code in BCP 47 format which we can use inside of html lang="" tags.
Definition: Language.php:4275
static isUtf8( $value)
Test whether a string is valid UTF-8.
Definition: StringUtils.php:44
truncate_skip(&$ret, $text, $search, $start, $len=null)
truncateHtml() helper function like strcspn() but adds the skipped chars to $ret
Definition: Language.php:3685
$IP
Definition: WebStart.php:41
equals(Language $lang)
Compare with an other language object.
Definition: Language.php:4249
lcfirst( $str)
Definition: Language.php:2667
static $IRANIAN_DAYS
Definition: Language.php:1548
newConverter()
Construct a new LanguageConverter suitable for this language.
Definition: Language.php:4028
offsetForUser(User $user)
Adjust the timestamp depending on the given user&#39;s preferences.
Definition: MWTimestamp.php:79
alignEnd()
Return &#39;right&#39; or &#39;left&#39; as appropriate alignment for line-end for this language&#39;s text direction...
Definition: Language.php:3025
static insertSpace( $string, $pattern)
Definition: Language.php:2869
getFallbackLanguages()
Definition: Language.php:508
userTimeAndDate( $ts, User $user, array $options=[])
Get the formatted date and time for the given timestamp and formatted for the given user...
Definition: Language.php:2456
if(!isset( $args[0])) $lang
$namespaceAliases
Definition: Language.php:78
hasVariants()
Check if this is a language with variants.
Definition: Language.php:4106
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user&#39;s current setting for a given option.
Definition: User.php:2969
getCompiledPluralRules()
Get the compiled plural rules for the language.
Definition: Language.php:4772
getLocalNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:676
const DURATION_INTERVALS
Definition: Language.php:248
convertCategoryKey( $key)
Definition: Language.php:4138
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
getLocalURL( $query='', $query2=false)
Get a URL with no fragment or server name (relative URL) from a Title object.
Definition: Title.php:2172
const IRANIAN_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:186
truncateForDatabase( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified length in bytes, appending an optional string (e.g.
Definition: Language.php:3411
const ALL
Return all known languages in fetchLanguageName(s).
Definition: Language.php:52
$wgMetaNamespace
Name of the project namespace.
fallback8bitEncoding()
Definition: Language.php:2803
wfIsInfinity( $str)
Determine input string is represents as infinity.
unsegmentForDiff( $text)
and unsegment to show the result
Definition: Language.php:4018
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:3708
const HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
Definition: Language.php:217
A fake language variant converter.
linkTrail()
A regular expression to match legal word-trailing characters which should be merged onto a link of th...
Definition: Language.php:4215
getAllMessages()
Definition: Language.php:2588
$wgNamespaceAliases
Namespace aliases.
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
getPluralRuleIndexNumber( $number)
Find the index number of the plural rule appropriate for the given number.
Definition: Language.php:4835
getVariants()
Get the list of variants supported by this language see sample implementation in LanguageZh.php.
Definition: Language.php:4148
const PDF
Definition: Language.php:272
$dateFormatStrings
Definition: Language.php:73
static hebrewYearStart( $year)
This calculates the Hebrew year start, as days since 1 September.
Definition: Language.php:1812
getNamespaceAliases()
Definition: Language.php:685
LanguageConverter FakeConverter $mConverter
Definition: Language.php:65
minimumGroupingDigits()
Definition: Language.php:3328
static $mMonthMsgs
Definition: Language.php:154
convertForSearchResult( $termsArray)
Definition: Language.php:2879
$wgExtraGenderNamespaces
Same as above, but for namespaces with gender distinction.
static getFileName( $prefix, $code, $suffix='.php')
Get the name of a file for a certain language code.
Definition: Language.php:4327
const MONTH_MESSAGES
Definition: Language.php:145
convertTitle( $title)
Convert a Title object to a string in the preferred variant.
Definition: Language.php:4085
static classFromCode( $code, $fallback=true)
Definition: Language.php:4307
internalUserTimeAndDate( $type, $ts, User $user, array $options)
Internal helper function for userDate(), userTime() and userTimeAndDate()
Definition: Language.php:2371
__construct( $code=null, LocalisationCache $localisationCache=null, LanguageNameUtils $langNameUtils=null, LanguageFallback $langFallback=null)
Calling this directly is deprecated.
Definition: Language.php:458
array $wgOverrideUcfirstCharacters
List of Unicode characters for which capitalization is overridden in Language::ucfirst.
$wgTranslateNumerals
For Hindi and Arabic use local numerals instead of Western style (0-9) numerals in interface...
static $mWeekdayAbbrevMsgs
Definition: Language.php:140
lc( $str, $first=false)
Definition: Language.php:2690
$mMagicExtensions
Definition: Language.php:68
LocalisationCache $localisationCache
Definition: Language.php:86
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:420
const WEEKDAY_MESSAGES
Definition: Language.php:120
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
truncateHtml( $text, $length, $ellipsis='...')
Truncate a string of valid HTML to a specified length in bytes, appending an optional string (e...
Definition: Language.php:3566
ucfirst( $str)
Definition: Language.php:2613
semicolonList(array $list)
Take a list of strings and build a locale-friendly semicolon-separated list, using the local semicolo...
Definition: Language.php:3377
userAdjust( $ts, $tz=false)
Used by date() and time() to adjust the time output.
Definition: Language.php:2091
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4423
formatNum( $number, $nocommafy=false)
Normally we output all numbers in plain en_US style, that is 293,291.235 for twohundredninetythreetho...
Definition: Language.php:3179
Language false $mParentLanguage
Definition: Language.php:71
static getFallbackFor( $code)
Get the first fallback for a given language.
Definition: Language.php:4362
timeanddate( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2275
formatExpiry( $expiry, $format=true, $infinity='infinity')
Decode an expiry (block, protection, etc) which has come from the DB.
Definition: Language.php:4477
listToText(array $list)
Take a list of strings and build a locale-friendly comma-separated list, using the local comma-separa...
Definition: Language.php:3340
static tsToYear( $ts, $cName)
Algorithm to convert Gregorian dates to Thai solar dates, Minguo dates or Minguo dates.
Definition: Language.php:1850
const NS_PROJECT
Definition: Defines.php:64
static $mHijriCalendarMonthMsgs
Definition: Language.php:243
linkPrefixCharset()
A regular expression character set to match legal word-prefixing characters which should be merged on...
Definition: Language.php:4225
static getMain()
Get the RequestContext object associated with the main request.
getPreferredVariant()
Definition: Language.php:4155
static getMessagesFor( $code)
Get all messages for a given language WARNING: this may take a long time.
Definition: Language.php:4409
$minimumGroupingDigits
removeBadCharFirst( $string)
Remove bytes that represent an incomplete Unicode character at the start of string (e...
Definition: Language.php:3540
getDirMarkEntity( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3040
__destruct()
Reduce memory usage PhanTypeSuspiciousNonTraversableForeach.
Definition: Language.php:498
static strongDirFromContent( $text='')
Gets directionality of the first strongly directional codepoint, for embedBidi()
Definition: Language.php:1956
getMagic( $mw)
Fill a MagicWord object with data from here.
Definition: Language.php:3119
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4437
static getFallbacksIncludingSiteLanguage( $code)
Get the ordered list of fallback languages, ending with the fallback language chain for the site lang...
Definition: Language.php:4393
getDefaultVariant()
Definition: Language.php:4162
getNsText( $index)
Get a namespace value by key.
Definition: Language.php:606
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:115
viewPrevNext(Title $title, $offset, $limit, array $query=[], $atend=false)
Generate (prev x| next x) (20|50|100...) type links for paging.
Definition: Language.php:4700
getConverter()
Return the LanguageConverter used in the Language.
Definition: Language.php:4038
static $mIranianCalendarMonthMsgs
Definition: Language.php:196
const NS_PROJECT_TALK
Definition: Defines.php:65
array [] null $grammarTransformCache
Definition: Language.php:95
autoConvertToAllVariants( $text)
convert text to all supported variants
Definition: Language.php:4060
getBookstoreList()
Exports $wgBookstoreListEn.
Definition: Language.php:516
capitalizeAllNouns()
Definition: Language.php:3069
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
emphasize( $text)
Italic is unsuitable for some languages.
Definition: Language.php:3153
date( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2236
isMultibyte( $str)
Definition: Language.php:2702
segmentForDiff( $text)
languages like Chinese need to be segmented in order for the diff to be of any use ...
Definition: Language.php:4008
$wgAllUnicodeFixes
Set this to always convert certain Unicode sequences to modern ones regardless of the content languag...
normalizeForSearch( $string)
Some languages have special punctuation need to be normalized.
Definition: Language.php:2837
static $strongDirRegex
Directionality test regex for embedBidi().
Definition: Language.php:287
static tsToHijri( $ts)
Converting Gregorian dates to Hijri dates.
Definition: Language.php:1622
needsGenderDistinction()
Whether this language uses gender-dependent namespace aliases.
Definition: Language.php:652
getURLVariant()
Definition: Language.php:4169
LanguageNameUtils $langNameUtils
Definition: Language.php:89
caseFold( $s)
Return a case-folded representation of $s.
Definition: Language.php:2780
updateConversionTable(Title $title)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
Definition: Language.php:4205
mbUpperChar( $char)
Convert character to uppercase, allowing overrides of the default mb_upper behaviour, which is buggy in many ways.
Definition: Language.php:2657
$wgMetaNamespaceTalk
Name of the project talk namespace.
static tsToIranian( $ts)
Algorithm by Roozbeh Pournader and Mohammad Toossi to convert Gregorian dates to Iranian dates...
Definition: Language.php:1562
const LRE
Unicode directional formatting characters, for embedBidi()
Definition: Language.php:270
const MONTH_GENITIVE_MESSAGES
Definition: Language.php:159
getNamespaceIds()
Definition: Language.php:737
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:297
dateFormat( $usePrefs=true)
This is meant to be used by time(), date(), and timeanddate() to get the date preference they&#39;re supp...
Definition: Language.php:2169
static $mHebrewCalendarMonthMsgs
Definition: Language.php:212
pipeList(array $list)
Same as commaList, but separate it with the pipe instead.
Definition: Language.php:3389
getGenderNsText( $index, $gender)
Returns gender-dependent namespace alias if available.
Definition: Language.php:637
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with &#39;_&#39; changed to &#39; &#39;...
Definition: Language.php:624
$mExtendedSpecialPageAliases
Definition: Language.php:74
getPluralRules()
Get the plural rules for the language.
Definition: Language.php:4793
getDefaultDateFormat()
Definition: Language.php:816
embedBidi( $text='')
Wraps argument with unicode control characters for directionality safety.
Definition: Language.php:3938
resetNamespaces()
Resets all of the namespace caches.
Definition: Language.php:575
getDateFormatString( $type, $pref)
Get a format string for a given type and preference.
Definition: Language.php:2200
time( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2255
getMagicWords()
Get all magic words from cache.
Definition: Language.php:3110
getGrammarTransformations()
Get the grammar transformations data for the language.
Definition: Language.php:3801
numLink(Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class)
Helper function for viewPrevNext() that generates links.
Definition: Language.php:4747
static getMessagesFileName( $code)
Definition: Language.php:4337
static getDefaultOption( $opt)
Get a given default option value.
Definition: User.php:1747
convertGrammar( $word, $case)
Grammatical transformations, needed for inflected languages Invoked by putting {{grammar:case|word}} ...
Definition: Language.php:3730
const HIJRI_CALENDAR_MONTH_MESSAGES
Definition: Language.php:233
digitTransformTable()
Definition: Language.php:3314
getConvRuleTitle()
Get the conversion rule title, if any.
Definition: Language.php:4763
formatTimePeriod( $seconds, $format=[])
Formats a time given in seconds into a string representation of that time.
Definition: Language.php:4508
userDate( $ts, User $user, array $options=[])
Get the formatted date for the given timestamp and formatted for the given user.
Definition: Language.php:2410
getNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:767
autoConvert( $text, $variant=false)
convert text to a variant
Definition: Language.php:4050
static getJsonMessagesFileName( $code)
Definition: Language.php:4349
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:349
ucwordbreaks( $str)
capitalize words at word breaks
Definition: Language.php:2736
$wgExtraNamespaces
Additional namespaces.
static convertDoubleWidth( $string)
convert double-width roman characters to single-width.
Definition: Language.php:2849
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:2512
getCode()
Get the internal language code for this language object.
Definition: Language.php:4261
digitGroupingPattern()
Definition: Language.php:3307
specialList( $page, $details, $oppositedm=true)
Make a list item, used by various special pages.
Definition: Language.php:4676
static isKnownLanguageTag( $tag)
Returns true if a language code is an IETF tag known to MediaWiki.
Definition: Language.php:435
$fallback
Definition: MessagesAb.php:11
$digitGroupingPattern
Definition: MessagesAs.php:167
static isSupportedLanguage( $code)
Checks whether any localisation is available for that language tag in MediaWiki (MessagesXx.php exists).
Definition: Language.php:329
convertNamespace( $ns, $variant=null)
Convert a namespace index to a string in the preferred variant.
Definition: Language.php:4097
getArrow( $direction='forwards')
An arrow, depending on the language direction.
Definition: Language.php:3080
LanguageFallback $langFallback
Definition: Language.php:92
formatSize( $size)
Format a size in bytes for output, using an appropriate unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question.
Definition: Language.php:4663
convertHtml( $text)
Perform output conversion on a string, and encode for safe HTML output.
Definition: Language.php:4130
array null $namespaceNames
Definition: Language.php:77
commafy( $number)
Adds commas to a given number.
Definition: Language.php:3242
$transformData
ReplacementArray object caches.
Definition: Language.php:83
static getCodeFromFileName( $filename, $prefix='Language', $suffix='.php')
Get the language code from a file name.
Definition: Language.php:4289
getExtraHashOptions()
returns language specific options used by User::getPageRenderHash() for example, the preferred langua...
Definition: Language.php:4195
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4379
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static tsToHebrew( $ts)
Converting Gregorian dates to Hebrew dates.
Definition: Language.php:1674
preConvertPlural($forms, $count)
Checks that convertPlural was given an array and pads it to requested amount of forms by copying the ...
Definition: Language.php:3918
findVariantLink(&$link, &$nt, $ignoreOtherCond=false)
If a language supports multiple variants, it is possible that non-existing link in one variant actual...
Definition: Language.php:4185
$wgGrammarForms
Some languages need different word forms, usually for different cases.
const SUPPORTED
Return in fetchLanguageName(s) only the languages for which we have at least some localisation...
Definition: Language.php:60
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: Language.php:4120
formatBitrate( $bps)
Format a bitrate for output, using an appropriate unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question.
Definition: Language.php:4615
const AS_AUTONYMS
Return autonyms in fetchLanguageName(s).
Definition: Language.php:45
transformUsingPairFile( $file, $string)
Transform a string using serialized data stored in the given file (which must be in the serialized su...
Definition: Language.php:2979
separatorTransformTable()
Definition: Language.php:3321
isRTL()
For right-to-left language support.
Definition: Language.php:2993
getDatePreference()
Get the user&#39;s preferred date format.
Definition: User.php:3293
sprintfDate( $format, $ts, DateTimeZone $zone=null, &$ttl='unused')
This is a workalike of PHP&#39;s date() function, but with better internationalisation, a reduced set of format characters, and a better escaping format.
Definition: Language.php:1078
getParentLanguage()
Get the "parent" language which has a converter to convert a "compatible" language (in another varian...
Definition: Language.php:4237
static clearCaches()
Intended for tests that may change configuration in a way that invalidates caches.
Definition: Language.php:307
getDir()
Return the correct HTML &#39;dir&#39; attribute value for this language.
Definition: Language.php:3001
getFormattedNamespaces()
A convenience function that returns getNamespaces() with spaces instead of underscores in values...
Definition: Language.php:587
$wgLocalTZoffset
Set an offset from UTC in minutes to use for the default timezone setting for anonymous users and new...
iconv( $in, $out, $string)
Definition: Language.php:2598
const RLE
Definition: Language.php:271
static $mMonthGenMsgs
Definition: Language.php:168
static $mWeekdayMsgs
Definition: Language.php:128
const WEEKDAY_ABBREVIATED_MESSAGES
Definition: Language.php:133
linkPrefixExtension()
To allow "foo[[bar]]" to extend the link over the whole word "foobar".
Definition: Language.php:3102
msg( $msg)
Get message object in this language.
Definition: Language.php:893
const MESSAGES_FALLBACKS
Return a fallback chain for messages in getFallbacksFor.
Definition: Language.php:108
const DB_REPLICA
Definition: defines.php:25
$mNamespaceIds
Definition: Language.php:78
uc( $str, $first=false)
Definition: Language.php:2636
getGrammarForms()
Get the grammar forms for the content language.
Definition: Language.php:3781
fixVariableInNamespace( $talk)
Definition: Language.php:4445
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
const MONTH_ABBREVIATED_MESSAGES
Definition: Language.php:173
formatComputingNumbers( $size, $boundary, $messageKey)
Definition: Language.php:4625
const HEBREW_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:201
userTime( $ts, User $user, array $options=[])
Get the formatted time for the given timestamp and formatted for the given user.
Definition: Language.php:2433
getNamespaces()
Returns an array of localised namespaces indexed by their numbers.
Definition: Language.php:526
static isValidCode( $code)
Returns true if a language code string is of a valid form, whether or not it exists.
Definition: Language.php:405
commaList(array $list)
Take a list of strings and build a locale-friendly comma-separated list, using the local comma-separa...
Definition: Language.php:3364
static $mHebrewCalendarMonthGenMsgs
Definition: Language.php:228
const NS_USER_TALK
Definition: Defines.php:63
truncateForVisual( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified number of characters, appending an optional string (e...
Definition: Language.php:3435
gender( $gender, $forms)
Provides an alternative text depending on specified gender.
Definition: Language.php:3838
A service that provides utilities to do with language names and codes.
getMessageFromDB( $msg)
Get a message from the MediaWiki namespace.
Definition: Language.php:883
hasWordBreaks()
Most writing systems use whitespace to break up words.
Definition: Language.php:2815
convert( $text)
convert text to different variants of a language.
Definition: Language.php:4075
const static array $durationIntervals
Definition: Language.php:265
alignStart()
Return &#39;left&#39; or &#39;right&#39; as appropriate alignment for line-start for this language&#39;s text direction...
Definition: Language.php:3013
return true
Definition: router.php:92
checkTitleEncoding( $s)
TODO: $s is not always a string per T218883.
Definition: Language.php:2789
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
convertPlural( $count, $forms)
Plural form transformations, needed for some languages.
Definition: Language.php:3867
formatNumNoSeparators( $number)
Front-end for non-commafied formatNum.
Definition: Language.php:3207
parseFormattedNumber( $number)
Definition: Language.php:3215
truncateInternal( $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring)
Internal method used for truncation.
Definition: Language.php:3461
while(( $__line=Maintenance::readconsole()) !==false) print n
Definition: eval.php:64
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static $GREG_DAYS
Definition: Language.php:1547
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:2294
$matches