MediaWiki  master
Language.php
Go to the documentation of this file.
1 <?php
25 use CLDRPluralRuleParser\Evaluator;
33 use Wikimedia\Assert\Assert;
34 
41 class Language {
47  public const AS_AUTONYMS = LanguageNameUtils::AUTONYMS;
48 
54  public const ALL = LanguageNameUtils::ALL;
55 
62  public const SUPPORTED = LanguageNameUtils::SUPPORTED;
63 
71  public function __get( string $name ) {
72  if ( $name == "mConverter" ) {
74  'Access to Language::$mConverter was deprecated in MediaWiki 1.35',
75  '1.35' );
76  return $this->getConverter();
77  }
78  throw new RuntimeException( "Cannot get '$name' property." );
79  }
80 
81  public $mCode;
82 
86  public $mMagicExtensions = [];
87 
88  private $mHtmlCode = null;
89 
94  public $dateFormatStrings = [];
95 
102 
104  protected $namespaceNames;
106 
111  public $transformData = [];
112 
115 
117  private $langNameUtils;
118 
120  private $langFallback;
121 
124 
129 
133  private $hookContainer;
134 
138  private $hookRunner;
139 
144  public static $mLangObjCache = [];
145 
151  public const MESSAGES_FALLBACKS = LanguageFallback::MESSAGES;
152 
158  public const STRICT_FALLBACKS = LanguageFallback::STRICT;
159 
163  public const WEEKDAY_MESSAGES = [
164  'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
165  'friday', 'saturday'
166  ];
167 
172 
177  'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
178  ];
179 
184 
188  public const MONTH_MESSAGES = [
189  'january', 'february', 'march', 'april', 'may_long', 'june',
190  'july', 'august', 'september', 'october', 'november',
191  'december'
192  ];
193 
198 
202  public const MONTH_GENITIVE_MESSAGES = [
203  'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
204  'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
205  'december-gen'
206  ];
207 
212 
216  public const MONTH_ABBREVIATED_MESSAGES = [
217  'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
218  'sep', 'oct', 'nov', 'dec'
219  ];
220 
225 
230  'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
231  'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
232  'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
233  'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
234  ];
235 
240 
245  'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
246  'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
247  'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
248  'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
249  'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
250  ];
251 
256 
261  'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
262  'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
263  'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
264  'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
265  'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
266  ];
267 
272 
277  'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
278  'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
279  'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
280  'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
281  ];
282 
287 
291  protected const DURATION_INTERVALS = [
292  'millennia' => 31556952000,
293  'centuries' => 3155695200,
294  'decades' => 315569520,
295  'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
296  'weeks' => 604800,
297  'days' => 86400,
298  'hours' => 3600,
299  'minutes' => 60,
300  'seconds' => 1,
301  ];
302 
309 
313  private const LRE = "\u{202A}"; // U+202A LEFT-TO-RIGHT EMBEDDING
314  private const RLE = "\u{202B}"; // U+202B RIGHT-TO-LEFT EMBEDDING
315  private const PDF = "\u{202C}"; // U+202C POP DIRECTIONAL FORMATTING
316 
328  // @codeCoverageIgnoreStart
329  // phpcs:ignore Generic.Files.LineLength
330  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';
331  // @codeCoverageIgnoreEnd
332 
340  public static function factory( $code ) {
341  return MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( $code );
342  }
343 
350  public static function clearCaches() {
351  wfDeprecated( __METHOD__, '1.35' );
352 
353  $services = MediaWikiServices::getInstance();
354 
355  $services->resetServiceForTesting( 'LanguageFallback' );
356  $services->resetServiceForTesting( 'LanguageNameUtils' );
357  $services->resetServiceForTesting( 'LocalisationCache' );
358  $services->resetServiceForTesting( 'LanguageFactory' );
359 
360  self::$mLangObjCache = [];
361  }
362 
372  public static function isSupportedLanguage( $code ) {
373  return MediaWikiServices::getInstance()->getLanguageNameUtils()
374  ->isSupportedLanguage( $code );
375  }
376 
392  public static function isWellFormedLanguageTag( $code, $lenient = false ) {
393  $alpha = '[a-z]';
394  $digit = '[0-9]';
395  $alphanum = '[a-z0-9]';
396  $x = 'x'; # private use singleton
397  $singleton = '[a-wy-z]'; # other singleton
398  $s = $lenient ? '[-_]' : '-';
399 
400  $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
401  $script = "$alpha{4}"; # ISO 15924
402  $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
403  $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
404  $extension = "$singleton(?:$s$alphanum{2,8})+";
405  $privateUse = "$x(?:$s$alphanum{1,8})+";
406 
407  # Define certain grandfathered codes, since otherwise the regex is pretty useless.
408  # Since these are limited, this is safe even later changes to the registry --
409  # the only oddity is that it might change the type of the tag, and thus
410  # the results from the capturing groups.
411  # https://www.iana.org/assignments/language-subtag-registry
412 
413  $grandfathered = "en{$s}GB{$s}oed"
414  . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
415  . "|no{$s}(?:bok|nyn)"
416  . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
417  . "|zh{$s}min{$s}nan";
418 
419  $variantList = "$variant(?:$s$variant)*";
420  $extensionList = "$extension(?:$s$extension)*";
421 
422  $langtag = "(?:($language)"
423  . "(?:$s$script)?"
424  . "(?:$s$region)?"
425  . "(?:$s$variantList)?"
426  . "(?:$s$extensionList)?"
427  . "(?:$s$privateUse)?)";
428 
429  # The final breakdown, with capturing groups for each of these components
430  # The variants, extensions, grandfathered, and private-use may have interior '-'
431 
432  $root = "^(?:$langtag|$privateUse|$grandfathered)$";
433 
434  return (bool)preg_match( "/$root/", strtolower( $code ) );
435  }
436 
449  public static function isValidCode( $code ) {
450  return MediaWikiServices::getInstance()->getLanguageNameUtils()->isValidCode( $code );
451  }
452 
464  public static function isValidBuiltInCode( $code ) {
465  return MediaWikiServices::getInstance()->getLanguageNameUtils()
466  ->isValidBuiltInCode( $code );
467  }
468 
479  public static function isKnownLanguageTag( $tag ) {
480  return MediaWikiServices::getInstance()->getLanguageNameUtils()
481  ->isKnownLanguageTag( $tag );
482  }
483 
490  public static function getLocalisationCache() {
491  return MediaWikiServices::getInstance()->getLocalisationCache();
492  }
493 
504  public function __construct(
505  $code = null,
511  ) {
512  if ( !func_num_args() ) {
513  // Old calling convention, deprecated
514  if ( static::class === 'Language' ) {
515  $this->mCode = 'en';
516  } else {
517  $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
518  }
519 
520  $services = MediaWikiServices::getInstance();
521  $this->localisationCache = $services->getLocalisationCache();
522  $this->langNameUtils = $services->getLanguageNameUtils();
523  $this->langFallback = $services->getLanguageFallback();
524  $this->converterFactory = $services->getLanguageConverterFactory();
525  $this->hookContainer = $services->getHookContainer();
526  $this->hookRunner = new HookRunner( $this->hookContainer );
527  return;
528  }
529 
530  Assert::parameter( $code !== null, '$code',
531  'Parameters cannot be null unless all are omitted' );
532  Assert::parameter( $localisationCache !== null, '$localisationCache',
533  'Parameters cannot be null unless all are omitted' );
534  Assert::parameter( $langNameUtils !== null, '$langNameUtils',
535  'Parameters cannot be null unless all are omitted' );
536  Assert::parameter( $langFallback !== null, '$langFallback',
537  'Parameters cannot be null unless all are omitted' );
538  Assert::parameter( $converterFactory !== null, '$converterFactory',
539  'Parameters cannot be null unless all are omitted' );
540  Assert::parameter( $hookContainer !== null, '$hookContainer',
541  'Parameters cannot be null unless all are omitted' );
542 
543  $this->mCode = $code;
544  $this->localisationCache = $localisationCache;
545  $this->langNameUtils = $langNameUtils;
546  $this->langFallback = $langFallback;
547  $this->converterFactory = $converterFactory;
548  $this->hookContainer = $hookContainer;
549  $this->hookRunner = new HookRunner( $hookContainer );
550  }
551 
556  public function __destruct() {
557  foreach ( $this as $name => $value ) {
558  unset( $this->$name );
559  }
560  }
561 
566  public function getFallbackLanguages() {
567  return $this->langFallback->getAll( $this->mCode );
568  }
569 
574  public function getBookstoreList() {
575  return $this->localisationCache->getItem( $this->mCode, 'bookstoreList' );
576  }
577 
584  public function getNamespaces() {
585  if ( $this->namespaceNames === null ) {
587 
588  $validNamespaces = MediaWikiServices::getInstance()->getNamespaceInfo()->
589  getCanonicalNamespaces();
590 
591  $this->namespaceNames = $wgExtraNamespaces +
592  $this->localisationCache->getItem( $this->mCode, 'namespaceNames' );
593  $this->namespaceNames += $validNamespaces;
594 
595  $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
596  if ( $wgMetaNamespaceTalk ) {
597  $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
598  } else {
599  $talk = $this->namespaceNames[NS_PROJECT_TALK];
600  $this->namespaceNames[NS_PROJECT_TALK] =
601  $this->fixVariableInNamespace( $talk );
602  }
603 
604  # Sometimes a language will be localised but not actually exist on this wiki.
605  foreach ( $this->namespaceNames as $key => $text ) {
606  if ( !isset( $validNamespaces[$key] ) ) {
607  unset( $this->namespaceNames[$key] );
608  }
609  }
610 
611  # The above mixing may leave namespaces out of canonical order.
612  # Re-order by namespace ID number...
613  ksort( $this->namespaceNames );
614 
615  $this->getHookRunner()->onLanguageGetNamespaces( $this->namespaceNames );
616  }
617 
618  return $this->namespaceNames;
619  }
620 
625  public function setNamespaces( array $namespaces ) {
626  $this->namespaceNames = $namespaces;
627  $this->mNamespaceIds = null;
628  }
629 
633  public function resetNamespaces() {
634  $this->namespaceNames = null;
635  $this->mNamespaceIds = null;
636  $this->namespaceAliases = null;
637  }
638 
645  public function getFormattedNamespaces() {
646  $ns = $this->getNamespaces();
647  foreach ( $ns as $k => $v ) {
648  $ns[$k] = strtr( $v, '_', ' ' );
649  }
650  return $ns;
651  }
652 
664  public function getNsText( $index ) {
665  $ns = $this->getNamespaces();
666  return $ns[$index] ?? false;
667  }
668 
682  public function getFormattedNsText( $index ) {
683  $ns = $this->getNsText( $index );
684  return strtr( $ns, '_', ' ' );
685  }
686 
695  public function getGenderNsText( $index, $gender ) {
697 
699  (array)$this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
700 
701  return $ns[$index][$gender] ?? $this->getNsText( $index );
702  }
703 
710  public function needsGenderDistinction() {
712  if ( count( $wgExtraGenderNamespaces ) > 0 ) {
713  // $wgExtraGenderNamespaces overrides everything
714  return true;
715  } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
717  // $wgExtraNamespaces overrides any gender aliases specified in i18n files
718  return false;
719  } else {
720  // Check what is in i18n files
721  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceGenderAliases' );
722  return count( $aliases ) > 0;
723  }
724  }
725 
734  public function getLocalNsIndex( $text ) {
735  $lctext = $this->lc( $text );
736  $ids = $this->getNamespaceIds();
737  return $ids[$lctext] ?? false;
738  }
739 
744  public function getNamespaceAliases() {
745  if ( $this->namespaceAliases === null ) {
746  $aliases = $this->localisationCache->getItem( $this->mCode, 'namespaceAliases' );
747  if ( !$aliases ) {
748  $aliases = [];
749  } else {
750  foreach ( $aliases as $name => $index ) {
751  if ( $index === NS_PROJECT_TALK ) {
752  unset( $aliases[$name] );
753  $name = $this->fixVariableInNamespace( $name );
754  $aliases[$name] = $index;
755  }
756  }
757  }
758 
760  $genders = $wgExtraGenderNamespaces + (array)$this->localisationCache
761  ->getItem( $this->mCode, 'namespaceGenderAliases' );
762  foreach ( $genders as $index => $forms ) {
763  foreach ( $forms as $alias ) {
764  $aliases[$alias] = $index;
765  }
766  }
767 
768  # Also add converted namespace names as aliases, to avoid confusion.
769  $convertedNames = [];
770  foreach ( $this->getConverter()->getVariants() as $variant ) {
771  if ( $variant === $this->mCode ) {
772  continue;
773  }
774  foreach ( $this->getNamespaces() as $ns => $_ ) {
775  $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
776  }
777  }
778 
779  $this->namespaceAliases = $aliases + $convertedNames;
780 
781  // In the case of conflicts between $wgNamespaceAliases and other sources
782  // of aliasing, $wgNamespaceAliases wins.
783  global $wgNamespaceAliases;
784  $this->namespaceAliases = $wgNamespaceAliases + $this->namespaceAliases;
785 
786  # Filter out aliases to namespaces that don't exist, e.g. from extensions
787  # that aren't loaded here but are included in the l10n cache.
788  # (array_intersect preserves keys from its first argument)
789  $this->namespaceAliases = array_intersect(
790  $this->namespaceAliases,
791  array_keys( $this->getNamespaces() )
792  );
793  }
794 
796  }
797 
801  public function getNamespaceIds() {
802  if ( $this->mNamespaceIds === null ) {
803  # Put namespace names and aliases into a hashtable.
804  # If this is too slow, then we should arrange it so that it is done
805  # before caching. The catch is that at pre-cache time, the above
806  # class-specific fixup hasn't been done.
807  $this->mNamespaceIds = [];
808  foreach ( $this->getNamespaces() as $index => $name ) {
809  $this->mNamespaceIds[$this->lc( $name )] = $index;
810  }
811  foreach ( $this->getNamespaceAliases() as $name => $index ) {
812  $this->mNamespaceIds[$this->lc( $name )] = $index;
813  }
814  }
815  return $this->mNamespaceIds;
816  }
817 
825  public function getNsIndex( $text ) {
826  $lctext = $this->lc( $text );
827  $ns = MediaWikiServices::getInstance()->getNamespaceInfo()->
828  getCanonicalIndex( $lctext );
829  if ( $ns !== null ) {
830  return $ns;
831  }
832  $ids = $this->getNamespaceIds();
833  return $ids[$lctext] ?? false;
834  }
835 
843  public function getVariantname( $code, $usemsg = true ) {
844  $msg = "variantname-$code";
845  if ( $usemsg && wfMessage( $msg )->exists() ) {
846  return $this->getMessageFromDB( $msg );
847  }
848  $name = $this->langNameUtils->getLanguageName( $code );
849  if ( $name ) {
850  return $name; # if it's defined as a language name, show that
851  } else {
852  # otherwise, output the language code
853  return $code;
854  }
855  }
856 
860  public function getDatePreferences() {
861  return $this->localisationCache->getItem( $this->mCode, 'datePreferences' );
862  }
863 
867  public function getDateFormats() {
868  return $this->localisationCache->getItem( $this->mCode, 'dateFormats' );
869  }
870 
874  public function getDefaultDateFormat() {
875  $df = $this->localisationCache->getItem( $this->mCode, 'defaultDateFormat' );
876  if ( $df === 'dmy or mdy' ) {
877  global $wgAmericanDates;
878  return $wgAmericanDates ? 'mdy' : 'dmy';
879  } else {
880  return $df;
881  }
882  }
883 
887  public function getDatePreferenceMigrationMap() {
888  return $this->localisationCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
889  }
890 
894  public function getExtraUserToggles() {
895  wfDeprecated( __METHOD__, '1.34' );
896  return [];
897  }
898 
914  public static function fetchLanguageNames(
915  $inLanguage = LanguageNameUtils::AUTONYMS,
916  $include = 'mw'
917  ) {
918  return MediaWikiServices::getInstance()->getLanguageNameUtils()
919  ->getLanguageNames( $inLanguage, $include );
920  }
921 
931  public static function fetchLanguageName(
932  $code,
933  $inLanguage = LanguageNameUtils::AUTONYMS,
934  $include = LanguageNameUtils::ALL
935  ) {
936  return MediaWikiServices::getInstance()->getLanguageNameUtils()
937  ->getLanguageName( $code, $inLanguage, $include );
938  }
939 
946  public function getMessageFromDB( $msg ) {
947  return $this->msg( $msg )->text();
948  }
949 
956  protected function msg( $msg ) {
957  return wfMessage( $msg )->inLanguage( $this );
958  }
959 
964  public function getMonthName( $key ) {
965  return $this->getMessageFromDB( self::MONTH_MESSAGES[$key - 1] );
966  }
967 
971  public function getMonthNamesArray() {
972  $monthNames = [ '' ];
973  for ( $i = 1; $i < 13; $i++ ) {
974  $monthNames[] = $this->getMonthName( $i );
975  }
976  return $monthNames;
977  }
978 
983  public function getMonthNameGen( $key ) {
984  return $this->getMessageFromDB( self::MONTH_GENITIVE_MESSAGES[$key - 1] );
985  }
986 
991  public function getMonthAbbreviation( $key ) {
992  return $this->getMessageFromDB( self::MONTH_ABBREVIATED_MESSAGES[$key - 1] );
993  }
994 
998  public function getMonthAbbreviationsArray() {
999  $monthNames = [ '' ];
1000  for ( $i = 1; $i < 13; $i++ ) {
1001  $monthNames[] = $this->getMonthAbbreviation( $i );
1002  }
1003  return $monthNames;
1004  }
1005 
1010  public function getWeekdayName( $key ) {
1011  return $this->getMessageFromDB( self::WEEKDAY_MESSAGES[$key - 1] );
1012  }
1013 
1018  public function getWeekdayAbbreviation( $key ) {
1019  return $this->getMessageFromDB( self::WEEKDAY_ABBREVIATED_MESSAGES[$key - 1] );
1020  }
1021 
1026  private function getIranianCalendarMonthName( $key ) {
1027  return $this->getMessageFromDB( self::IRANIAN_CALENDAR_MONTHS_MESSAGES[$key - 1] );
1028  }
1029 
1034  private function getHebrewCalendarMonthName( $key ) {
1035  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTHS_MESSAGES[$key - 1] );
1036  }
1037 
1042  private function getHebrewCalendarMonthNameGen( $key ) {
1043  return $this->getMessageFromDB( self::HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES[$key - 1] );
1044  }
1045 
1050  private function getHijriCalendarMonthName( $key ) {
1051  return $this->getMessageFromDB( self::HIJRI_CALENDAR_MONTH_MESSAGES[$key - 1] );
1052  }
1053 
1062  private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1063  if ( !$dateTimeObj ) {
1064  $dateTimeObj = DateTime::createFromFormat(
1065  'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1066  );
1067  }
1068  return $dateTimeObj->format( $code );
1069  }
1070 
1141  public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
1142  $s = '';
1143  $raw = false;
1144  $roman = false;
1145  $hebrewNum = false;
1146  $dateTimeObj = false;
1147  $rawToggle = false;
1148  $iranian = false;
1149  $hebrew = false;
1150  $hijri = false;
1151  $thai = false;
1152  $minguo = false;
1153  $tenno = false;
1154 
1155  $usedSecond = false;
1156  $usedMinute = false;
1157  $usedHour = false;
1158  $usedAMPM = false;
1159  $usedDay = false;
1160  $usedWeek = false;
1161  $usedMonth = false;
1162  $usedYear = false;
1163  $usedISOYear = false;
1164  $usedIsLeapYear = false;
1165 
1166  $usedHebrewMonth = false;
1167  $usedIranianMonth = false;
1168  $usedHijriMonth = false;
1169  $usedHebrewYear = false;
1170  $usedIranianYear = false;
1171  $usedHijriYear = false;
1172  $usedTennoYear = false;
1173 
1174  if ( strlen( $ts ) !== 14 ) {
1175  throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1176  }
1177 
1178  if ( !ctype_digit( $ts ) ) {
1179  throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1180  }
1181 
1182  $formatLength = strlen( $format );
1183  for ( $p = 0; $p < $formatLength; $p++ ) {
1184  $num = false;
1185  $code = $format[$p];
1186  if ( $code == 'x' && $p < $formatLength - 1 ) {
1187  $code .= $format[++$p];
1188  }
1189 
1190  if ( ( $code === 'xi'
1191  || $code === 'xj'
1192  || $code === 'xk'
1193  || $code === 'xm'
1194  || $code === 'xo'
1195  || $code === 'xt' )
1196  && $p < $formatLength - 1 ) {
1197  $code .= $format[++$p];
1198  }
1199 
1200  switch ( $code ) {
1201  case 'xx':
1202  $s .= 'x';
1203  break;
1204  case 'xn':
1205  $raw = true;
1206  break;
1207  case 'xN':
1208  $rawToggle = !$rawToggle;
1209  break;
1210  case 'xr':
1211  $roman = true;
1212  break;
1213  case 'xh':
1214  $hebrewNum = true;
1215  break;
1216  case 'xg':
1217  $usedMonth = true;
1218  $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1219  break;
1220  case 'xjx':
1221  $usedHebrewMonth = true;
1222  if ( !$hebrew ) {
1223  $hebrew = self::tsToHebrew( $ts );
1224  }
1225  $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1226  break;
1227  case 'd':
1228  $usedDay = true;
1229  $num = substr( $ts, 6, 2 );
1230  break;
1231  case 'D':
1232  $usedDay = true;
1233  $s .= $this->getWeekdayAbbreviation(
1234  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1235  );
1236  break;
1237  case 'j':
1238  $usedDay = true;
1239  $num = intval( substr( $ts, 6, 2 ) );
1240  break;
1241  case 'xij':
1242  $usedDay = true;
1243  if ( !$iranian ) {
1244  $iranian = self::tsToIranian( $ts );
1245  }
1246  $num = $iranian[2];
1247  break;
1248  case 'xmj':
1249  $usedDay = true;
1250  if ( !$hijri ) {
1251  $hijri = self::tsToHijri( $ts );
1252  }
1253  $num = $hijri[2];
1254  break;
1255  case 'xjj':
1256  $usedDay = true;
1257  if ( !$hebrew ) {
1258  $hebrew = self::tsToHebrew( $ts );
1259  }
1260  $num = $hebrew[2];
1261  break;
1262  case 'l':
1263  $usedDay = true;
1264  $s .= $this->getWeekdayName(
1265  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1266  );
1267  break;
1268  case 'F':
1269  $usedMonth = true;
1270  $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1271  break;
1272  case 'xiF':
1273  $usedIranianMonth = true;
1274  if ( !$iranian ) {
1275  $iranian = self::tsToIranian( $ts );
1276  }
1277  $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1278  break;
1279  case 'xmF':
1280  $usedHijriMonth = true;
1281  if ( !$hijri ) {
1282  $hijri = self::tsToHijri( $ts );
1283  }
1284  $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1285  break;
1286  case 'xjF':
1287  $usedHebrewMonth = true;
1288  if ( !$hebrew ) {
1289  $hebrew = self::tsToHebrew( $ts );
1290  }
1291  $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1292  break;
1293  case 'm':
1294  $usedMonth = true;
1295  $num = substr( $ts, 4, 2 );
1296  break;
1297  case 'M':
1298  $usedMonth = true;
1299  $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1300  break;
1301  case 'n':
1302  $usedMonth = true;
1303  $num = intval( substr( $ts, 4, 2 ) );
1304  break;
1305  case 'xin':
1306  $usedIranianMonth = true;
1307  if ( !$iranian ) {
1308  $iranian = self::tsToIranian( $ts );
1309  }
1310  $num = $iranian[1];
1311  break;
1312  case 'xmn':
1313  $usedHijriMonth = true;
1314  if ( !$hijri ) {
1315  $hijri = self::tsToHijri( $ts );
1316  }
1317  $num = $hijri[1];
1318  break;
1319  case 'xjn':
1320  $usedHebrewMonth = true;
1321  if ( !$hebrew ) {
1322  $hebrew = self::tsToHebrew( $ts );
1323  }
1324  $num = $hebrew[1];
1325  break;
1326  case 'xjt':
1327  $usedHebrewMonth = true;
1328  if ( !$hebrew ) {
1329  $hebrew = self::tsToHebrew( $ts );
1330  }
1331  $num = $hebrew[3];
1332  break;
1333  case 'Y':
1334  $usedYear = true;
1335  $num = substr( $ts, 0, 4 );
1336  break;
1337  case 'xiY':
1338  $usedIranianYear = true;
1339  if ( !$iranian ) {
1340  $iranian = self::tsToIranian( $ts );
1341  }
1342  $num = $iranian[0];
1343  break;
1344  case 'xmY':
1345  $usedHijriYear = true;
1346  if ( !$hijri ) {
1347  $hijri = self::tsToHijri( $ts );
1348  }
1349  $num = $hijri[0];
1350  break;
1351  case 'xjY':
1352  $usedHebrewYear = true;
1353  if ( !$hebrew ) {
1354  $hebrew = self::tsToHebrew( $ts );
1355  }
1356  $num = $hebrew[0];
1357  break;
1358  case 'xkY':
1359  $usedYear = true;
1360  if ( !$thai ) {
1361  $thai = self::tsToYear( $ts, 'thai' );
1362  }
1363  $num = $thai[0];
1364  break;
1365  case 'xoY':
1366  $usedYear = true;
1367  if ( !$minguo ) {
1368  $minguo = self::tsToYear( $ts, 'minguo' );
1369  }
1370  $num = $minguo[0];
1371  break;
1372  case 'xtY':
1373  $usedTennoYear = true;
1374  if ( !$tenno ) {
1375  $tenno = self::tsToYear( $ts, 'tenno' );
1376  }
1377  $num = $tenno[0];
1378  break;
1379  case 'y':
1380  $usedYear = true;
1381  $num = substr( $ts, 2, 2 );
1382  break;
1383  case 'xiy':
1384  $usedIranianYear = true;
1385  if ( !$iranian ) {
1386  $iranian = self::tsToIranian( $ts );
1387  }
1388  $num = substr( $iranian[0], -2 );
1389  break;
1390  case 'xit':
1391  $usedIranianYear = true;
1392  if ( !$iranian ) {
1393  $iranian = self::tsToIranian( $ts );
1394  }
1395  $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
1396  break;
1397  case 'xiz':
1398  $usedIranianYear = true;
1399  if ( !$iranian ) {
1400  $iranian = self::tsToIranian( $ts );
1401  }
1402  $num = $iranian[3];
1403  break;
1404  case 'a':
1405  $usedAMPM = true;
1406  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1407  break;
1408  case 'A':
1409  $usedAMPM = true;
1410  $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1411  break;
1412  case 'g':
1413  $usedHour = true;
1414  $h = substr( $ts, 8, 2 );
1415  $num = $h % 12 ?: 12;
1416  break;
1417  case 'G':
1418  $usedHour = true;
1419  $num = intval( substr( $ts, 8, 2 ) );
1420  break;
1421  case 'h':
1422  $usedHour = true;
1423  $h = substr( $ts, 8, 2 );
1424  $num = sprintf( '%02d', $h % 12 ?: 12 );
1425  break;
1426  case 'H':
1427  $usedHour = true;
1428  $num = substr( $ts, 8, 2 );
1429  break;
1430  case 'i':
1431  $usedMinute = true;
1432  $num = substr( $ts, 10, 2 );
1433  break;
1434  case 's':
1435  $usedSecond = true;
1436  $num = substr( $ts, 12, 2 );
1437  break;
1438  case 'c':
1439  case 'r':
1440  $usedSecond = true;
1441  // fall through
1442  case 'e':
1443  case 'O':
1444  case 'P':
1445  case 'T':
1446  $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1447  break;
1448  case 'w':
1449  case 'N':
1450  case 'z':
1451  $usedDay = true;
1452  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1453  break;
1454  case 'W':
1455  $usedWeek = true;
1456  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1457  break;
1458  case 't':
1459  $usedMonth = true;
1460  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1461  break;
1462  case 'L':
1463  $usedIsLeapYear = true;
1464  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1465  break;
1466  case 'o':
1467  $usedISOYear = true;
1468  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1469  break;
1470  case 'U':
1471  $usedSecond = true;
1472  // fall through
1473  case 'I':
1474  case 'Z':
1475  $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1476  break;
1477  case '\\':
1478  # Backslash escaping
1479  if ( $p < $formatLength - 1 ) {
1480  $s .= $format[++$p];
1481  } else {
1482  $s .= '\\';
1483  }
1484  break;
1485  case '"':
1486  # Quoted literal
1487  if ( $p < $formatLength - 1 ) {
1488  $endQuote = strpos( $format, '"', $p + 1 );
1489  if ( $endQuote === false ) {
1490  # No terminating quote, assume literal "
1491  $s .= '"';
1492  } else {
1493  $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1494  $p = $endQuote;
1495  }
1496  } else {
1497  # Quote at end of string, assume literal "
1498  $s .= '"';
1499  }
1500  break;
1501  default:
1502  $s .= $format[$p];
1503  }
1504  if ( $num !== false ) {
1505  if ( $rawToggle || $raw ) {
1506  $s .= $num;
1507  $raw = false;
1508  } elseif ( $roman ) {
1509  $s .= self::romanNumeral( $num );
1510  $roman = false;
1511  } elseif ( $hebrewNum ) {
1512  $s .= self::hebrewNumeral( $num );
1513  $hebrewNum = false;
1514  } else {
1515  $s .= $this->formatNum( $num, true );
1516  }
1517  }
1518  }
1519 
1520  if ( $ttl === 'unused' ) {
1521  // No need to calculate the TTL, the caller wont use it anyway.
1522  } elseif ( $usedSecond ) {
1523  $ttl = 1;
1524  } elseif ( $usedMinute ) {
1525  $ttl = 60 - substr( $ts, 12, 2 );
1526  } elseif ( $usedHour ) {
1527  $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1528  } elseif ( $usedAMPM ) {
1529  $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1530  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1531  } elseif (
1532  $usedDay ||
1533  $usedHebrewMonth ||
1534  $usedIranianMonth ||
1535  $usedHijriMonth ||
1536  $usedHebrewYear ||
1537  $usedIranianYear ||
1538  $usedHijriYear ||
1539  $usedTennoYear
1540  ) {
1541  // @todo Someone who understands the non-Gregorian calendars
1542  // should write proper logic for them so that they don't need purged every day.
1543  $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1544  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1545  } else {
1546  $possibleTtls = [];
1547  $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1548  substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1549  if ( $usedWeek ) {
1550  $possibleTtls[] =
1551  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1552  $timeRemainingInDay;
1553  } elseif ( $usedISOYear ) {
1554  // December 28th falls on the last ISO week of the year, every year.
1555  // The last ISO week of a year can be 52 or 53.
1556  $lastWeekOfISOYear = DateTime::createFromFormat(
1557  'Ymd',
1558  substr( $ts, 0, 4 ) . '1228',
1559  $zone ?: new DateTimeZone( 'UTC' )
1560  )->format( 'W' );
1561  $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1562  $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1563  $timeRemainingInWeek =
1564  ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1565  + $timeRemainingInDay;
1566  $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1567  }
1568 
1569  if ( $usedMonth ) {
1570  $possibleTtls[] =
1571  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1572  substr( $ts, 6, 2 ) ) * 86400
1573  + $timeRemainingInDay;
1574  } elseif ( $usedYear ) {
1575  $possibleTtls[] =
1576  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1577  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1578  + $timeRemainingInDay;
1579  } elseif ( $usedIsLeapYear ) {
1580  $year = substr( $ts, 0, 4 );
1581  $timeRemainingInYear =
1582  ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1583  self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1584  + $timeRemainingInDay;
1585  $mod = $year % 4;
1586  if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1587  // this isn't a leap year. see when the next one starts
1588  $nextCandidate = $year - $mod + 4;
1589  if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1590  $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1591  $timeRemainingInYear;
1592  } else {
1593  $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1594  $timeRemainingInYear;
1595  }
1596  } else {
1597  // this is a leap year, so the next year isn't
1598  $possibleTtls[] = $timeRemainingInYear;
1599  }
1600  }
1601 
1602  if ( $possibleTtls ) {
1603  $ttl = min( $possibleTtls );
1604  }
1605  }
1606 
1607  return $s;
1608  }
1609 
1610  private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1611  private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1612 
1625  private static function tsToIranian( $ts ) {
1626  $gy = substr( $ts, 0, 4 ) - 1600;
1627  $gm = substr( $ts, 4, 2 ) - 1;
1628  $gd = substr( $ts, 6, 2 ) - 1;
1629 
1630  # Days passed from the beginning (including leap years)
1631  $gDayNo = 365 * $gy
1632  + floor( ( $gy + 3 ) / 4 )
1633  - floor( ( $gy + 99 ) / 100 )
1634  + floor( ( $gy + 399 ) / 400 );
1635 
1636  // Add days of the past months of this year
1637  for ( $i = 0; $i < $gm; $i++ ) {
1638  $gDayNo += self::$GREG_DAYS[$i];
1639  }
1640 
1641  // Leap years
1642  if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1643  $gDayNo++;
1644  }
1645 
1646  // Days passed in current month
1647  $gDayNo += (int)$gd;
1648 
1649  $jDayNo = $gDayNo - 79;
1650 
1651  $jNp = floor( $jDayNo / 12053 );
1652  $jDayNo %= 12053;
1653 
1654  $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1655  $jDayNo %= 1461;
1656 
1657  if ( $jDayNo >= 366 ) {
1658  $jy += floor( ( $jDayNo - 1 ) / 365 );
1659  $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1660  }
1661 
1662  $jz = $jDayNo;
1663 
1664  for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1665  $jDayNo -= self::$IRANIAN_DAYS[$i];
1666  }
1667 
1668  $jm = $i + 1;
1669  $jd = $jDayNo + 1;
1670 
1671  return [ $jy, $jm, $jd, $jz ];
1672  }
1673 
1685  private static function tsToHijri( $ts ) {
1686  $year = substr( $ts, 0, 4 );
1687  $month = substr( $ts, 4, 2 );
1688  $day = substr( $ts, 6, 2 );
1689 
1690  $zyr = $year;
1691  $zd = $day;
1692  $zm = $month;
1693  $zy = $zyr;
1694 
1695  if (
1696  ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1697  ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1698  ) {
1699  $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1700  (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1701  (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1702  $zd - 32075;
1703  } else {
1704  $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1705  (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1706  }
1707 
1708  $zl = $zjd - 1948440 + 10632;
1709  $zn = (int)( ( $zl - 1 ) / 10631 );
1710  $zl = $zl - 10631 * $zn + 354;
1711  $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1712  ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1713  $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1714  ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1715  $zm = (int)( ( 24 * $zl ) / 709 );
1716  $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1717  $zy = 30 * $zn + $zj - 30;
1718 
1719  return [ $zy, $zm, $zd ];
1720  }
1721 
1737  private static function tsToHebrew( $ts ) {
1738  # Parse date
1739  $year = substr( $ts, 0, 4 );
1740  $month = substr( $ts, 4, 2 );
1741  $day = substr( $ts, 6, 2 );
1742 
1743  # Calculate Hebrew year
1744  $hebrewYear = $year + 3760;
1745 
1746  # Month number when September = 1, August = 12
1747  $month += 4;
1748  if ( $month > 12 ) {
1749  # Next year
1750  $month -= 12;
1751  $year++;
1752  $hebrewYear++;
1753  }
1754 
1755  # Calculate day of year from 1 September
1756  $dayOfYear = $day;
1757  for ( $i = 1; $i < $month; $i++ ) {
1758  if ( $i == 6 ) {
1759  # February
1760  $dayOfYear += 28;
1761  # Check if the year is leap
1762  if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1763  $dayOfYear++;
1764  }
1765  } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1766  $dayOfYear += 30;
1767  } else {
1768  $dayOfYear += 31;
1769  }
1770  }
1771 
1772  # Calculate the start of the Hebrew year
1773  $start = self::hebrewYearStart( $hebrewYear );
1774 
1775  # Calculate next year's start
1776  if ( $dayOfYear <= $start ) {
1777  # Day is before the start of the year - it is the previous year
1778  # Next year's start
1779  $nextStart = $start;
1780  # Previous year
1781  $year--;
1782  $hebrewYear--;
1783  # Add days since previous year's 1 September
1784  $dayOfYear += 365;
1785  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1786  # Leap year
1787  $dayOfYear++;
1788  }
1789  # Start of the new (previous) year
1790  $start = self::hebrewYearStart( $hebrewYear );
1791  } else {
1792  # Next year's start
1793  $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1794  }
1795 
1796  # Calculate Hebrew day of year
1797  $hebrewDayOfYear = $dayOfYear - $start;
1798 
1799  # Difference between year's days
1800  $diff = $nextStart - $start;
1801  # Add 12 (or 13 for leap years) days to ignore the difference between
1802  # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1803  # difference is only about the year type
1804  if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1805  $diff += 13;
1806  } else {
1807  $diff += 12;
1808  }
1809 
1810  # Check the year pattern, and is leap year
1811  # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1812  # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1813  # and non-leap years
1814  $yearPattern = $diff % 30;
1815  # Check if leap year
1816  $isLeap = $diff >= 30;
1817 
1818  # Calculate day in the month from number of day in the Hebrew year
1819  # Don't check Adar - if the day is not in Adar, we will stop before;
1820  # if it is in Adar, we will use it to check if it is Adar I or Adar II
1821  $hebrewDay = $hebrewDayOfYear;
1822  $hebrewMonth = 1;
1823  $days = 0;
1824  while ( $hebrewMonth <= 12 ) {
1825  # Calculate days in this month
1826  if ( $isLeap && $hebrewMonth == 6 ) {
1827  # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1828  $days = 30;
1829  if ( $hebrewDay <= $days ) {
1830  # Day in Adar I
1831  $hebrewMonth = 13;
1832  } else {
1833  # Subtract the days of Adar I
1834  $hebrewDay -= $days;
1835  # Try Adar II
1836  $days = 29;
1837  if ( $hebrewDay <= $days ) {
1838  # Day in Adar II
1839  $hebrewMonth = 14;
1840  }
1841  }
1842  } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1843  # Cheshvan in a complete year (otherwise as the rule below)
1844  $days = 30;
1845  } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1846  # Kislev in an incomplete year (otherwise as the rule below)
1847  $days = 29;
1848  } else {
1849  # Odd months have 30 days, even have 29
1850  $days = 30 - ( $hebrewMonth - 1 ) % 2;
1851  }
1852  if ( $hebrewDay <= $days ) {
1853  # In the current month
1854  break;
1855  } else {
1856  # Subtract the days of the current month
1857  $hebrewDay -= $days;
1858  # Try in the next month
1859  $hebrewMonth++;
1860  }
1861  }
1862 
1863  return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1864  }
1865 
1875  private static function hebrewYearStart( $year ) {
1876  $a = ( 12 * ( $year - 1 ) + 17 ) % 19;
1877  $b = ( $year - 1 ) % 4;
1878  $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1879  if ( $m < 0 ) {
1880  $m--;
1881  }
1882  $Mar = intval( $m );
1883  if ( $m < 0 ) {
1884  $m++;
1885  }
1886  $m -= $Mar;
1887 
1888  $c = ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7;
1889  if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1890  $Mar++;
1891  } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1892  $Mar += 2;
1893  } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1894  $Mar++;
1895  }
1896 
1897  $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1898  return $Mar;
1899  }
1900 
1913  private static function tsToYear( $ts, $cName ) {
1914  $gy = substr( $ts, 0, 4 );
1915  $gm = substr( $ts, 4, 2 );
1916  $gd = substr( $ts, 6, 2 );
1917 
1918  if ( !strcmp( $cName, 'thai' ) ) {
1919  # Thai solar dates
1920  # Add 543 years to the Gregorian calendar
1921  # Months and days are identical
1922  $gy_offset = $gy + 543;
1923  # fix for dates between 1912 and 1941
1924  # https://en.wikipedia.org/?oldid=836596673#New_year
1925  if ( $gy >= 1912 && $gy <= 1940 ) {
1926  if ( $gm <= 3 ) {
1927  $gy_offset--;
1928  }
1929  $gm = ( $gm - 3 ) % 12;
1930  }
1931  } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1932  # Minguo dates
1933  # Deduct 1911 years from the Gregorian calendar
1934  # Months and days are identical
1935  $gy_offset = $gy - 1911;
1936  } elseif ( !strcmp( $cName, 'tenno' ) ) {
1937  # Nengō dates up to Meiji period
1938  # Deduct years from the Gregorian calendar
1939  # depending on the nengo periods
1940  # Months and days are identical
1941  if ( ( $gy < 1912 )
1942  || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1943  || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1944  ) {
1945  # Meiji period
1946  $gy_gannen = $gy - 1868 + 1;
1947  $gy_offset = $gy_gannen;
1948  if ( $gy_gannen == 1 ) {
1949  $gy_offset = '元';
1950  }
1951  $gy_offset = '明治' . $gy_offset;
1952  } elseif (
1953  ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1954  ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1955  ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1956  ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1957  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1958  ) {
1959  # Taishō period
1960  $gy_gannen = $gy - 1912 + 1;
1961  $gy_offset = $gy_gannen;
1962  if ( $gy_gannen == 1 ) {
1963  $gy_offset = '元';
1964  }
1965  $gy_offset = '大正' . $gy_offset;
1966  } elseif (
1967  ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1968  ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1969  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1970  ) {
1971  # Shōwa period
1972  $gy_gannen = $gy - 1926 + 1;
1973  $gy_offset = $gy_gannen;
1974  if ( $gy_gannen == 1 ) {
1975  $gy_offset = '元';
1976  }
1977  $gy_offset = '昭和' . $gy_offset;
1978  } elseif (
1979  ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd >= 8 ) ) ||
1980  ( ( $gy > 1989 ) && ( $gy < 2019 ) ) ||
1981  ( ( $gy == 2019 ) && ( $gm < 5 ) )
1982  ) {
1983  # Heisei period
1984  $gy_gannen = $gy - 1989 + 1;
1985  $gy_offset = $gy_gannen;
1986  if ( $gy_gannen == 1 ) {
1987  $gy_offset = '元';
1988  }
1989  $gy_offset = '平成' . $gy_offset;
1990  } else {
1991  # Reiwa period
1992  $gy_gannen = $gy - 2019 + 1;
1993  $gy_offset = $gy_gannen;
1994  if ( $gy_gannen == 1 ) {
1995  $gy_offset = '元';
1996  }
1997  $gy_offset = '令和' . $gy_offset;
1998  }
1999  } else {
2000  $gy_offset = $gy;
2001  }
2002 
2003  return [ $gy_offset, $gm, $gd ];
2004  }
2005 
2019  private static function strongDirFromContent( $text = '' ) {
2020  if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
2021  return null;
2022  }
2023  if ( $matches[1] === '' ) {
2024  return 'rtl';
2025  }
2026  return 'ltr';
2027  }
2028 
2036  public static function romanNumeral( $num ) {
2037  static $table = [
2038  [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
2039  [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
2040  [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
2041  [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
2042  'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
2043  ];
2044 
2045  $num = intval( $num );
2046  if ( $num > 10000 || $num <= 0 ) {
2047  return $num;
2048  }
2049 
2050  $s = '';
2051  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2052  if ( $num >= $pow10 ) {
2053  $s .= $table[$i][(int)floor( $num / $pow10 )];
2054  }
2055  $num %= $pow10;
2056  }
2057  return $s;
2058  }
2059 
2067  public static function hebrewNumeral( $num ) {
2068  static $table = [
2069  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
2070  [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
2071  [ '',
2072  [ 'ק' ],
2073  [ 'ר' ],
2074  [ 'ש' ],
2075  [ 'ת' ],
2076  [ 'ת', 'ק' ],
2077  [ 'ת', 'ר' ],
2078  [ 'ת', 'ש' ],
2079  [ 'ת', 'ת' ],
2080  [ 'ת', 'ת', 'ק' ],
2081  [ 'ת', 'ת', 'ר' ],
2082  ],
2083  [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
2084  ];
2085 
2086  $num = intval( $num );
2087  if ( $num > 9999 || $num <= 0 ) {
2088  return $num;
2089  }
2090 
2091  // Round thousands have special notations
2092  if ( $num === 1000 ) {
2093  return "א' אלף";
2094  } elseif ( $num % 1000 === 0 ) {
2095  return $table[0][$num / 1000] . "' אלפים";
2096  }
2097 
2098  $letters = [];
2099 
2100  for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2101  if ( $num >= $pow10 ) {
2102  if ( $num === 15 || $num === 16 ) {
2103  $letters[] = $table[0][9];
2104  $letters[] = $table[0][$num - 9];
2105  $num = 0;
2106  } else {
2107  $letters = array_merge(
2108  $letters,
2109  (array)$table[$i][intval( $num / $pow10 )]
2110  );
2111 
2112  if ( $pow10 === 1000 ) {
2113  $letters[] = "'";
2114  }
2115  }
2116  }
2117 
2118  $num %= $pow10;
2119  }
2120 
2121  $preTransformLength = count( $letters );
2122  if ( $preTransformLength === 1 ) {
2123  // Add geresh (single quote) to one-letter numbers
2124  $letters[] = "'";
2125  } else {
2126  $lastIndex = $preTransformLength - 1;
2127  $letters[$lastIndex] = str_replace(
2128  [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2129  [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2130  $letters[$lastIndex]
2131  );
2132 
2133  // Add gershayim (double quote) to multiple-letter numbers,
2134  // but exclude numbers with only one letter after the thousands
2135  // (1001-1009, 1020, 1030, 2001-2009, etc.)
2136  if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2137  $letters[] = "'";
2138  } else {
2139  array_splice( $letters, -1, 0, '"' );
2140  }
2141  }
2142 
2143  return implode( $letters );
2144  }
2145 
2154  public function userAdjust( $ts, $tz = false ) {
2155  global $wgLocalTZoffset;
2156 
2157  if ( $tz === false ) {
2158  $optionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
2159  $tz = $optionsLookup->getOption(
2161  'timecorrection'
2162  );
2163  }
2164 
2165  $data = explode( '|', $tz, 3 );
2166 
2167  if ( $data[0] == 'ZoneInfo' ) {
2168  try {
2169  $userTZ = new DateTimeZone( $data[2] );
2170  $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
2171  $date->setTimezone( $userTZ );
2172  return $date->format( 'YmdHis' );
2173  } catch ( Exception $e ) {
2174  // Unrecognized timezone, default to 'Offset' with the stored offset.
2175  $data[0] = 'Offset';
2176  }
2177  }
2178 
2179  // @phan-suppress-next-line PhanSuspiciousValueComparison
2180  if ( $data[0] == 'System' || $tz == '' ) {
2181  # Global offset in minutes.
2182  $minDiff = $wgLocalTZoffset;
2183  } elseif ( $data[0] == 'Offset' ) {
2184  $minDiff = intval( $data[1] );
2185  } else {
2186  $data = explode( ':', $tz );
2187  if ( count( $data ) == 2 ) {
2188  $data[0] = intval( $data[0] );
2189  $data[1] = intval( $data[1] );
2190  $minDiff = abs( $data[0] ) * 60 + $data[1];
2191  if ( $data[0] < 0 ) {
2192  $minDiff = -$minDiff;
2193  }
2194  } else {
2195  $minDiff = intval( $data[0] ) * 60;
2196  }
2197  }
2198 
2199  # No difference ? Return time unchanged
2200  if ( $minDiff == 0 ) {
2201  return $ts;
2202  }
2203 
2204  Wikimedia\suppressWarnings(); // E_STRICT system time bitching
2205  # Generate an adjusted date; take advantage of the fact that mktime
2206  # will normalize out-of-range values so we don't have to split $minDiff
2207  # into hours and minutes.
2208  $t = mktime( (
2209  (int)substr( $ts, 8, 2 ) ), # Hours
2210  (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2211  (int)substr( $ts, 12, 2 ), # Seconds
2212  (int)substr( $ts, 4, 2 ), # Month
2213  (int)substr( $ts, 6, 2 ), # Day
2214  (int)substr( $ts, 0, 4 ) ); # Year
2215 
2216  $date = date( 'YmdHis', $t );
2217  Wikimedia\restoreWarnings();
2218 
2219  return $date;
2220  }
2221 
2237  public function dateFormat( $usePrefs = true ) {
2238  if ( is_bool( $usePrefs ) ) {
2239  if ( $usePrefs ) {
2240  $datePreference = RequestContext::getMain()
2241  ->getUser()
2242  ->getDatePreference();
2243  } else {
2244  $datePreference = (string)User::getDefaultOption( 'date' );
2245  }
2246  } else {
2247  $datePreference = (string)$usePrefs;
2248  }
2249 
2250  // return int
2251  if ( $datePreference == '' ) {
2252  return 'default';
2253  }
2254 
2255  return $datePreference;
2256  }
2257 
2268  public function getDateFormatString( $type, $pref ) {
2269  $wasDefault = false;
2270  if ( $pref == 'default' ) {
2271  $wasDefault = true;
2272  $pref = $this->getDefaultDateFormat();
2273  }
2274 
2275  if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2276  $df = $this->localisationCache
2277  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2278 
2279  if ( $type === 'pretty' && $df === null ) {
2280  $df = $this->getDateFormatString( 'date', $pref );
2281  }
2282 
2283  if ( !$wasDefault && $df === null ) {
2284  $pref = $this->getDefaultDateFormat();
2285  $df = $this->localisationCache
2286  ->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2287  }
2288 
2289  $this->dateFormatStrings[$type][$pref] = $df;
2290  }
2291  return $this->dateFormatStrings[$type][$pref];
2292  }
2293 
2304  public function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2305  $ts = wfTimestamp( TS_MW, $ts );
2306  if ( $adj ) {
2307  $ts = $this->userAdjust( $ts, $timecorrection );
2308  }
2309  $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2310  return $this->sprintfDate( $df, $ts );
2311  }
2312 
2323  public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2324  $ts = wfTimestamp( TS_MW, $ts );
2325  if ( $adj ) {
2326  $ts = $this->userAdjust( $ts, $timecorrection );
2327  }
2328  $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2329  return $this->sprintfDate( $df, $ts );
2330  }
2331 
2343  public function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2344  $ts = wfTimestamp( TS_MW, $ts );
2345  if ( $adj ) {
2346  $ts = $this->userAdjust( $ts, $timecorrection );
2347  }
2348  $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2349  return $this->sprintfDate( $df, $ts );
2350  }
2351 
2362  public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2363  $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2364 
2365  $segments = [];
2366 
2367  foreach ( $intervals as $intervalName => $intervalValue ) {
2368  // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2369  // duration-years, duration-decades, duration-centuries, duration-millennia
2370  $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2371  $segments[] = $message->inLanguage( $this )->escaped();
2372  }
2373 
2374  return $this->listToText( $segments );
2375  }
2376 
2388  public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2389  if ( empty( $chosenIntervals ) ) {
2390  $chosenIntervals = [
2391  'millennia',
2392  'centuries',
2393  'decades',
2394  'years',
2395  'days',
2396  'hours',
2397  'minutes',
2398  'seconds'
2399  ];
2400  }
2401 
2402  $intervals = array_intersect_key( self::DURATION_INTERVALS, array_flip( $chosenIntervals ) );
2403  $sortedNames = array_keys( $intervals );
2404  $smallestInterval = array_pop( $sortedNames );
2405 
2406  $segments = [];
2407 
2408  foreach ( $intervals as $name => $length ) {
2409  $value = floor( $seconds / $length );
2410 
2411  if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2412  $seconds -= $value * $length;
2413  $segments[$name] = $value;
2414  }
2415  }
2416 
2417  return $segments;
2418  }
2419 
2439  private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2440  $ts = wfTimestamp( TS_MW, $ts );
2441  $options += [ 'timecorrection' => true, 'format' => true ];
2442  if ( $options['timecorrection'] !== false ) {
2443  if ( $options['timecorrection'] === true ) {
2444  $offset = $user->getOption( 'timecorrection' );
2445  } else {
2446  $offset = $options['timecorrection'];
2447  }
2448  $ts = $this->userAdjust( $ts, $offset );
2449  }
2450  if ( $options['format'] === true ) {
2451  $format = $user->getDatePreference();
2452  } else {
2453  $format = $options['format'];
2454  }
2455  $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2456  return $this->sprintfDate( $df, $ts );
2457  }
2458 
2478  public function userDate( $ts, User $user, array $options = [] ) {
2479  return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2480  }
2481 
2501  public function userTime( $ts, User $user, array $options = [] ) {
2502  return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2503  }
2504 
2524  public function userTimeAndDate( $ts, User $user, array $options = [] ) {
2525  return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2526  }
2527 
2543  public function getHumanTimestamp(
2544  MWTimestamp $time, MWTimestamp $relativeTo = null, User $user = null
2545  ) {
2546  if ( $relativeTo === null ) {
2547  $relativeTo = new MWTimestamp();
2548  }
2549  if ( $user === null ) {
2550  $user = RequestContext::getMain()->getUser();
2551  }
2552 
2553  // Adjust for the user's timezone.
2554  $offsetThis = $time->offsetForUser( $user );
2555  $offsetRel = $relativeTo->offsetForUser( $user );
2556 
2557  $ts = '';
2558  if ( $this->getHookRunner()->onGetHumanTimestamp( $ts, $time, $relativeTo, $user, $this ) ) {
2559  $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2560  }
2561 
2562  // Reset the timezone on the objects.
2563  $time->timestamp->sub( $offsetThis );
2564  $relativeTo->timestamp->sub( $offsetRel );
2565 
2566  return $ts;
2567  }
2568 
2580  private function getHumanTimestampInternal(
2581  MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2582  ) {
2583  $diff = $ts->diff( $relativeTo );
2584  $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2585  (int)$relativeTo->timestamp->format( 'w' ) );
2586  $days = $diff->days ?: (int)$diffDay;
2587  if ( $diff->invert || $days > 5
2588  && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2589  ) {
2590  // Timestamps are in different years: use full timestamp
2591  // Also do full timestamp for future dates
2595  $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2596  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2597  } elseif ( $days > 5 ) {
2598  // Timestamps are in same year, but more than 5 days ago: show day and month only.
2599  $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2600  $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2601  } elseif ( $days > 1 ) {
2602  // Timestamp within the past week: show the day of the week and time
2603  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2604  $weekday = self::WEEKDAY_MESSAGES[$ts->timestamp->format( 'w' )];
2605  // Messages:
2606  // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2607  $ts = wfMessage( "$weekday-at" )
2608  ->inLanguage( $this )
2609  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2610  ->text();
2611  } elseif ( $days == 1 ) {
2612  // Timestamp was yesterday: say 'yesterday' and the time.
2613  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2614  $ts = wfMessage( 'yesterday-at' )
2615  ->inLanguage( $this )
2616  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2617  ->text();
2618  } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2619  // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2620  $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2621  $ts = wfMessage( 'today-at' )
2622  ->inLanguage( $this )
2623  ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2624  ->text();
2625 
2626  // From here on in, the timestamp was soon enough ago so that we can simply say
2627  // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2628  } elseif ( $diff->h == 1 ) {
2629  // Less than 90 minutes, but more than an hour ago.
2630  $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2631  } elseif ( $diff->i >= 1 ) {
2632  // A few minutes ago.
2633  $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2634  } elseif ( $diff->s >= 30 ) {
2635  // Less than a minute, but more than 30 sec ago.
2636  $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2637  } else {
2638  // Less than 30 seconds ago.
2639  $ts = wfMessage( 'just-now' )->text();
2640  }
2641 
2642  return $ts;
2643  }
2644 
2649  public function getMessage( $key ) {
2650  return $this->localisationCache->getSubitem( $this->mCode, 'messages', $key );
2651  }
2652 
2656  public function getAllMessages() {
2657  return $this->localisationCache->getItem( $this->mCode, 'messages' );
2658  }
2659 
2666  public function iconv( $in, $out, $string ) {
2667  # Even with //IGNORE iconv can whine about illegal characters in
2668  # *input* string. We just ignore those too.
2669  # REF: https://bugs.php.net/bug.php?id=37166
2670  # REF: https://phabricator.wikimedia.org/T18885
2671  Wikimedia\suppressWarnings();
2672  $text = iconv( $in, $out . '//IGNORE', $string );
2673  Wikimedia\restoreWarnings();
2674  return $text;
2675  }
2676 
2681  public function ucfirst( $str ) {
2682  $octetCode = ord( $str );
2683  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2684  if ( $octetCode < 96 ) {
2685  // Assume this is an uppercase/uncased ASCII character
2686  return (string)$str;
2687  } elseif ( $octetCode < 128 ) {
2688  // Assume this is a lowercase/uncased ASCII character
2689  return ucfirst( $str );
2690  }
2691 
2692  $first = mb_substr( $str, 0, 1 );
2693  return ( strlen( $first ) !== 1 )
2694  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2695  ? $this->mbUpperChar( $first ) . mb_substr( $str, 1 )
2696  // Assume this is a non-multibyte character and LC_CASE is appropriate
2697  : ucfirst( $str );
2698  }
2699 
2705  public function uc( $str, $first = false ) {
2706  if ( $first ) {
2707  return $this->ucfirst( $str );
2708  } else {
2709  return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2710  }
2711  }
2712 
2726  protected function mbUpperChar( $char ) {
2728 
2729  return $wgOverrideUcfirstCharacters[$char] ?? mb_strtoupper( $char );
2730  }
2731 
2736  public function lcfirst( $str ) {
2737  $octetCode = ord( $str );
2738  // See https://en.wikipedia.org/wiki/ASCII#Printable_characters
2739  if ( $octetCode < 96 ) {
2740  // Assume this is an uppercase/uncased ASCII character
2741  return lcfirst( $str );
2742  } elseif ( $octetCode < 128 ) {
2743  // Assume this is a lowercase/uncased ASCII character
2744  return (string)$str;
2745  }
2746 
2747  return $this->isMultibyte( $str )
2748  // Assume this is a multibyte character and mb_internal_encoding() is appropriate
2749  ? mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 )
2750  // Assume this is a non-multibyte character and LC_CASE is appropriate
2751  : lcfirst( $str );
2752  }
2753 
2759  public function lc( $str, $first = false ) {
2760  if ( $first ) {
2761  return $this->lcfirst( $str );
2762  } else {
2763  return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2764  }
2765  }
2766 
2771  private function isMultibyte( $str ) {
2772  return strlen( $str ) !== mb_strlen( $str );
2773  }
2774 
2779  public function ucwords( $str ) {
2780  if ( $this->isMultibyte( $str ) ) {
2781  $str = $this->lc( $str );
2782 
2783  // regexp to find first letter in each word (i.e. after each space)
2784  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2785 
2786  // function to use to capitalize a single char
2787  return preg_replace_callback(
2788  $replaceRegexp,
2789  function ( $matches ) {
2790  return mb_strtoupper( $matches[0] );
2791  },
2792  $str
2793  );
2794  } else {
2795  return ucwords( strtolower( $str ) );
2796  }
2797  }
2798 
2805  public function ucwordbreaks( $str ) {
2806  if ( $this->isMultibyte( $str ) ) {
2807  $str = $this->lc( $str );
2808 
2809  // since \b doesn't work for UTF-8, we explicitely define word break chars
2810  $breaks = "[ \-\‍(\‍)\}\{\.,\?!]";
2811 
2812  // find first letter after word break
2813  $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2814  "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2815 
2816  return preg_replace_callback(
2817  $replaceRegexp,
2818  function ( $matches ) {
2819  return mb_strtoupper( $matches[0] );
2820  },
2821  $str
2822  );
2823  } else {
2824  return preg_replace_callback(
2825  '/\b([\w\x80-\xff]+)\b/',
2826  function ( $matches ) {
2827  return $this->ucfirst( $matches[1] );
2828  },
2829  $str
2830  );
2831  }
2832  }
2833 
2849  public function caseFold( $s ) {
2850  return $this->uc( $s );
2851  }
2852 
2858  public function checkTitleEncoding( $s ) {
2859  if ( is_array( $s ) ) {
2860  throw new MWException( 'Given array to checkTitleEncoding.' );
2861  }
2862  if ( StringUtils::isUtf8( $s ) ) {
2863  return $s;
2864  }
2865 
2866  return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2867  }
2868 
2872  public function fallback8bitEncoding() {
2873  return $this->localisationCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2874  }
2875 
2884  public function hasWordBreaks() {
2885  return true;
2886  }
2887 
2895  public function segmentByWord( $string ) {
2896  return $string;
2897  }
2898 
2906  public function normalizeForSearch( $string ) {
2907  return self::convertDoubleWidth( $string );
2908  }
2909 
2918  protected static function convertDoubleWidth( $string ) {
2919  static $full = null;
2920  static $half = null;
2921 
2922  if ( $full === null ) {
2923  $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2924  $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2925  $full = str_split( $fullWidth, 3 );
2926  $half = str_split( $halfWidth );
2927  }
2928 
2929  $string = str_replace( $full, $half, $string );
2930  return $string;
2931  }
2932 
2938  protected static function insertSpace( $string, $pattern ) {
2939  $string = preg_replace( $pattern, " $1 ", $string );
2940  $string = preg_replace( '/ +/', ' ', $string );
2941  return $string;
2942  }
2943 
2948  public function convertForSearchResult( $termsArray ) {
2949  # some languages, e.g. Chinese, need to do a conversion
2950  # in order for search results to be displayed correctly
2951  return $termsArray;
2952  }
2953 
2960  public function firstChar( $s ) {
2961  $firstChar = mb_substr( $s, 0, 1 );
2962 
2963  if ( $firstChar !== false ) {
2964  if ( strlen( $firstChar ) != 3 ) {
2965  return $firstChar;
2966  }
2967 
2968  // Break down Hangul syllables to grab the first jamo
2969  $code = mb_ord( $firstChar );
2970  if ( $code < 0xac00 || $code >= 0xd7a4 ) {
2971  return $firstChar;
2972  } elseif ( $code < 0xb098 ) {
2973  return "\u{3131}";
2974  } elseif ( $code < 0xb2e4 ) {
2975  return "\u{3134}";
2976  } elseif ( $code < 0xb77c ) {
2977  return "\u{3137}";
2978  } elseif ( $code < 0xb9c8 ) {
2979  return "\u{3139}";
2980  } elseif ( $code < 0xbc14 ) {
2981  return "\u{3141}";
2982  } elseif ( $code < 0xc0ac ) {
2983  return "\u{3142}";
2984  } elseif ( $code < 0xc544 ) {
2985  return "\u{3145}";
2986  } elseif ( $code < 0xc790 ) {
2987  return "\u{3147}";
2988  } elseif ( $code < 0xcc28 ) {
2989  return "\u{3148}";
2990  } elseif ( $code < 0xce74 ) {
2991  return "\u{314A}";
2992  } elseif ( $code < 0xd0c0 ) {
2993  return "\u{314B}";
2994  } elseif ( $code < 0xd30c ) {
2995  return "\u{314C}";
2996  } elseif ( $code < 0xd558 ) {
2997  return "\u{314D}";
2998  } else {
2999  return "\u{314E}";
3000  }
3001  }
3002 
3003  return '';
3004  }
3005 
3017  public function normalize( $s ) {
3018  global $wgAllUnicodeFixes, $IP;
3019 
3020  $s = UtfNormal\Validator::cleanUp( $s );
3021  if ( $wgAllUnicodeFixes ) {
3022  $s = $this->transformUsingPairFile( 'normalize-ar.php', $s, $IP );
3023  $s = $this->transformUsingPairFile( 'normalize-ml.php', $s, $IP );
3024  }
3025 
3026  return $s;
3027  }
3028 
3044  protected function transformUsingPairFile( $file, $string, $basePath = null ) {
3045  if ( isset( $this->transformData[$file] ) ) {
3046  wfDeprecated(
3047  'Modification of Language::$transformData is deprecated since MediaWiki 1.35',
3048  '1.35'
3049  );
3050  return $this->transformData[$file]->replace( $string );
3051  }
3052 
3053  if ( $basePath === null ) {
3054  wfDeprecated( __METHOD__ . ' without $basePath', '1.35' );
3055  global $IP;
3056  $basePath = $IP;
3057  }
3058 
3059  if (
3060  $basePath === null
3061  || $basePath === ''
3062  || !file_exists( "{$basePath}/languages/data/{$file}" )
3063  ) {
3064  return $string;
3065  }
3066 
3067  if ( !isset( $this->transformData[$basePath][$file] ) ) {
3068  $data = require "{$basePath}/languages/data/{$file}";
3069  $this->transformData[$basePath][$file] = new ReplacementArray( $data );
3070  }
3071 
3072  return $this->transformData[$basePath][$file]->replace( $string );
3073  }
3074 
3080  public function isRTL() {
3081  return $this->localisationCache->getItem( $this->mCode, 'rtl' );
3082  }
3083 
3088  public function getDir() {
3089  return $this->isRTL() ? 'rtl' : 'ltr';
3090  }
3091 
3100  public function alignStart() {
3101  return $this->isRTL() ? 'right' : 'left';
3102  }
3103 
3112  public function alignEnd() {
3113  return $this->isRTL() ? 'left' : 'right';
3114  }
3115 
3127  public function getDirMarkEntity( $opposite = false ) {
3128  if ( $opposite ) {
3129  return $this->isRTL() ? '&lrm;' : '&rlm;';
3130  }
3131  return $this->isRTL() ? '&rlm;' : '&lrm;';
3132  }
3133 
3144  public function getDirMark( $opposite = false ) {
3145  $lrm = "\u{200E}"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3146  $rlm = "\u{200F}"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3147  if ( $opposite ) {
3148  return $this->isRTL() ? $lrm : $rlm;
3149  }
3150  return $this->isRTL() ? $rlm : $lrm;
3151  }
3152 
3156  public function capitalizeAllNouns() {
3157  return $this->localisationCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3158  }
3159 
3167  public function getArrow( $direction = 'forwards' ) {
3168  switch ( $direction ) {
3169  case 'forwards':
3170  return $this->isRTL() ? '←' : '→';
3171  case 'backwards':
3172  return $this->isRTL() ? '→' : '←';
3173  case 'left':
3174  return '←';
3175  case 'right':
3176  return '→';
3177  case 'up':
3178  return '↑';
3179  case 'down':
3180  return '↓';
3181  }
3182  }
3183 
3189  public function linkPrefixExtension() {
3190  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixExtension' );
3191  }
3192 
3197  public function getMagicWords() {
3198  return $this->localisationCache->getItem( $this->mCode, 'magicWords' );
3199  }
3200 
3206  public function getMagic( $mw ) {
3207  $rawEntry = $this->mMagicExtensions[$mw->mId] ??
3208  $this->localisationCache->getSubitem( $this->mCode, 'magicWords', $mw->mId );
3209 
3210  if ( !is_array( $rawEntry ) ) {
3211  wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3212  } else {
3213  $mw->mCaseSensitive = $rawEntry[0];
3214  $mw->mSynonyms = array_slice( $rawEntry, 1 );
3215  }
3216  }
3217 
3223  public function getSpecialPageAliases() {
3224  // Cache aliases because it may be slow to load them
3225  if ( $this->mExtendedSpecialPageAliases === null ) {
3226  // Initialise array
3227  $this->mExtendedSpecialPageAliases =
3228  $this->localisationCache->getItem( $this->mCode, 'specialPageAliases' );
3229  }
3230 
3231  return $this->mExtendedSpecialPageAliases;
3232  }
3233 
3240  public function emphasize( $text ) {
3241  return "<em>$text</em>";
3242  }
3243 
3266  public function formatNum( $number, $nocommafy = false ) {
3267  global $wgTranslateNumerals;
3268 
3269  $number = (string)$number;
3270  if ( !$nocommafy ) {
3271  $number = $this->commafy( $number );
3272  $s = $this->separatorTransformTable();
3273  if ( $s ) {
3274  $number = strtr( $number, $s );
3275  }
3276  }
3277 
3278  if ( $wgTranslateNumerals ) {
3279  $s = $this->digitTransformTable();
3280  if ( $s ) {
3281  $number = strtr( $number, $s );
3282  }
3283  }
3284 
3285  return $number;
3286  }
3287 
3296  public function formatNumNoSeparators( $number ) {
3297  return $this->formatNum( $number, true );
3298  }
3299 
3304  public function parseFormattedNumber( $number ) {
3305  $s = $this->digitTransformTable();
3306  if ( $s ) {
3307  // eliminate empty array values such as ''. (T66347)
3308  $s = array_filter( $s );
3309  $number = strtr( $number, array_flip( $s ) );
3310  }
3311 
3312  $s = $this->separatorTransformTable();
3313  if ( $s ) {
3314  // eliminate empty array values such as ''. (T66347)
3315  $s = array_filter( $s );
3316  $number = strtr( $number, array_flip( $s ) );
3317  }
3318 
3319  $number = strtr( $number, [ ',' => '' ] );
3320  return $number;
3321  }
3322 
3331  public function commafy( $number ) {
3332  // Validate the input argument.
3333  if ( $number === null || $number === '' ) {
3334  return '';
3335  }
3336  if ( !is_string( $number ) ) {
3337  $number = (string)$number;
3338  }
3339  $validNumberRe = '(-(?=[\d\.]))?(\d+|(?=\.\d))(\.\d*)?';
3340  if ( !preg_match( "/^{$validNumberRe}$/", $number ) ) {
3341  // wfDeprecated( __METHOD__ . ' with a non-numeric string', '1.36' );
3342  // For backwards-compat, return commafy piecewise on the valid
3343  // numbers in the string.
3344  return preg_replace_callback( "/{$validNumberRe}/", function ( $m ) {
3345  return $this->commafy( $m[0] );
3346  }, $number );
3347  }
3348 
3349  $digitGroupingPattern = $this->digitGroupingPattern();
3350  $minimumGroupingDigits = $this->minimumGroupingDigits();
3351  if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3352  // Default grouping is at thousands, use the same for ###,###,### pattern too.
3353  // In some languages it's conventional not to insert a thousands separator
3354  // in numbers that are four digits long (1000-9999).
3355  if ( $minimumGroupingDigits ) {
3356  // Number of '#' characters after last comma in the grouping pattern.
3357  // The pattern is hardcoded here, but this would vary for different patterns.
3358  $primaryGroupingSize = 3;
3359  // Maximum length of a number to suppress digit grouping for.
3360  $maximumLength = $minimumGroupingDigits + $primaryGroupingSize - 1;
3361  if ( preg_match( '/^\-?\d{1,' . $maximumLength . '}(\.\d+)?$/', $number ) ) {
3362  return $number;
3363  }
3364  }
3365  return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3366  } else {
3367  // Ref: http://cldr.unicode.org/translation/numbers-currency/number-patterns
3368  $sign = "";
3369  if ( substr( $number, 0, 1 ) === '-' ) {
3370  // For negative numbers apply the algorithm like positive number and add sign.
3371  $sign = "-";
3372  $number = substr( $number, 1 );
3373  }
3374  $integerPart = [];
3375  $decimalPart = [];
3376  $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3377  preg_match( "/^\d+/", $number, $integerPart );
3378  preg_match( "/\.\d*/", $number, $decimalPart );
3379  $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3380  if ( $groupedNumber === $number ) {
3381  // the string does not have any number part. Eg: .12345
3382  return $sign . $groupedNumber;
3383  }
3384  $start = $end = ( $integerPart ) ? strlen( $integerPart[0] ) : 0;
3385  while ( $start > 0 ) {
3386  $match = $matches[0][$numMatches - 1];
3387  $matchLen = strlen( $match );
3388  $start = $end - $matchLen;
3389  if ( $start < 0 ) {
3390  $start = 0;
3391  }
3392  $groupedNumber = substr( $number, $start, $end - $start ) . $groupedNumber;
3393  $end = $start;
3394  if ( $numMatches > 1 ) {
3395  // use the last pattern for the rest of the number
3396  $numMatches--;
3397  }
3398  if ( $start > 0 ) {
3399  $groupedNumber = "," . $groupedNumber;
3400  }
3401  }
3402  return $sign . $groupedNumber;
3403  }
3404  }
3405 
3409  public function digitGroupingPattern() {
3410  return $this->localisationCache->getItem( $this->mCode, 'digitGroupingPattern' );
3411  }
3412 
3416  public function digitTransformTable() {
3417  return $this->localisationCache->getItem( $this->mCode, 'digitTransformTable' );
3418  }
3419 
3423  public function separatorTransformTable() {
3424  return $this->localisationCache->getItem( $this->mCode, 'separatorTransformTable' );
3425  }
3426 
3430  public function minimumGroupingDigits() {
3431  return $this->localisationCache->getItem( $this->mCode, 'minimumGroupingDigits' );
3432  }
3433 
3442  public function listToText( array $list ) {
3443  $itemCount = count( $list );
3444  if ( $itemCount < 1 ) {
3445  return '';
3446  }
3447  $text = array_pop( $list );
3448  if ( $itemCount > 1 ) {
3449  $and = $this->msg( 'and' )->escaped();
3450  $space = $this->msg( 'word-separator' )->escaped();
3451  $comma = '';
3452  if ( $itemCount > 2 ) {
3453  $comma = $this->msg( 'comma-separator' )->escaped();
3454  }
3455  $text = implode( $comma, $list ) . $and . $space . $text;
3456  }
3457  return $text;
3458  }
3459 
3466  public function commaList( array $list ) {
3467  return implode(
3468  wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3469  $list
3470  );
3471  }
3472 
3479  public function semicolonList( array $list ) {
3480  return implode(
3481  wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3482  $list
3483  );
3484  }
3485 
3491  public function pipeList( array $list ) {
3492  return implode(
3493  wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3494  $list
3495  );
3496  }
3497 
3513  public function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3514  return $this->truncateInternal(
3515  $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
3516  );
3517  }
3518 
3537  public function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3538  // Passing encoding to mb_strlen and mb_substr is optional.
3539  // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
3540  // explicit specification of encoding is skipped.
3541  // Note: Both multibyte methods are callables invoked in truncateInternal.
3542  return $this->truncateInternal(
3543  $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
3544  );
3545  }
3546 
3563  private function truncateInternal(
3564  $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring
3565  ) {
3566  # Check if there is no need to truncate
3567  if ( $measureLength( $string ) <= abs( $length ) ) {
3568  return $string; // no need to truncate
3569  }
3570 
3571  # Use the localized ellipsis character
3572  if ( $ellipsis == '...' ) {
3573  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3574  }
3575  if ( $length == 0 ) {
3576  return $ellipsis; // convention
3577  }
3578 
3579  $stringOriginal = $string;
3580  # If ellipsis length is >= $length then we can't apply $adjustLength
3581  if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
3582  $string = $ellipsis; // this can be slightly unexpected
3583  # Otherwise, truncate and add ellipsis...
3584  } else {
3585  $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
3586  if ( $length > 0 ) {
3587  $length -= $ellipsisLength;
3588  $string = $getSubstring( $string, 0, $length ); // xyz...
3589  $string = $this->removeBadCharLast( $string );
3590  $string = rtrim( $string ) . $ellipsis;
3591  } else {
3592  $length += $ellipsisLength;
3593  $string = $getSubstring( $string, $length ); // ...xyz
3594  $string = $this->removeBadCharFirst( $string );
3595  $string = $ellipsis . ltrim( $string );
3596  }
3597  }
3598 
3599  # Do not truncate if the ellipsis makes the string longer/equal (T24181).
3600  # This check is *not* redundant if $adjustLength, due to the single case where
3601  # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3602  if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
3603  return $string;
3604  } else {
3605  return $stringOriginal;
3606  }
3607  }
3608 
3616  protected function removeBadCharLast( $string ) {
3617  if ( $string != '' ) {
3618  $char = ord( $string[strlen( $string ) - 1] );
3619  $m = [];
3620  if ( $char >= 0xc0 ) {
3621  # We got the first byte only of a multibyte char; remove it.
3622  $string = substr( $string, 0, -1 );
3623  } elseif ( $char >= 0x80 &&
3624  // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3625  preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3626  '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3627  ) {
3628  # We chopped in the middle of a character; remove it
3629  $string = $m[1];
3630  }
3631  }
3632  return $string;
3633  }
3634 
3642  protected function removeBadCharFirst( $string ) {
3643  if ( $string != '' ) {
3644  $char = ord( $string[0] );
3645  if ( $char >= 0x80 && $char < 0xc0 ) {
3646  # We chopped in the middle of a character; remove the whole thing
3647  $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3648  }
3649  }
3650  return $string;
3651  }
3652 
3668  public function truncateHtml( $text, $length, $ellipsis = '...' ) {
3669  # Use the localized ellipsis character
3670  if ( $ellipsis == '...' ) {
3671  $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3672  }
3673  # Check if there is clearly no need to truncate
3674  if ( $length <= 0 ) {
3675  return $ellipsis; // no text shown, nothing to format (convention)
3676  } elseif ( strlen( $text ) <= $length ) {
3677  return $text; // string short enough even *with* HTML (short-circuit)
3678  }
3679 
3680  $dispLen = 0; // innerHTML legth so far
3681  $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3682  $tagType = 0; // 0-open, 1-close
3683  $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3684  $entityState = 0; // 0-not entity, 1-entity
3685  $tag = $ret = ''; // accumulated tag name, accumulated result string
3686  $openTags = []; // open tag stack
3687  $maybeState = null; // possible truncation state
3688 
3689  $textLen = strlen( $text );
3690  $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3691  for ( $pos = 0; true; ++$pos ) {
3692  # Consider truncation once the display length has reached the maximim.
3693  # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3694  # Check that we're not in the middle of a bracket/entity...
3695  if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3696  if ( !$testingEllipsis ) {
3697  $testingEllipsis = true;
3698  # Save where we are; we will truncate here unless there turn out to
3699  # be so few remaining characters that truncation is not necessary.
3700  if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3701  $maybeState = [ $ret, $openTags ]; // save state
3702  }
3703  } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3704  # String in fact does need truncation, the truncation point was OK.
3705  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
3706  list( $ret, $openTags ) = $maybeState; // reload state
3707  $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3708  $ret .= $ellipsis; // add ellipsis
3709  break;
3710  }
3711  }
3712  if ( $pos >= $textLen ) {
3713  break; // extra iteration just for above checks
3714  }
3715 
3716  # Read the next char...
3717  $ch = $text[$pos];
3718  $lastCh = $pos ? $text[$pos - 1] : '';
3719  $ret .= $ch; // add to result string
3720  if ( $ch == '<' ) {
3721  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3722  $entityState = 0; // for bad HTML
3723  $bracketState = 1; // tag started (checking for backslash)
3724  } elseif ( $ch == '>' ) {
3725  $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3726  $entityState = 0; // for bad HTML
3727  $bracketState = 0; // out of brackets
3728  } elseif ( $bracketState == 1 ) {
3729  if ( $ch == '/' ) {
3730  $tagType = 1; // close tag (e.g. "</span>")
3731  } else {
3732  $tagType = 0; // open tag (e.g. "<span>")
3733  $tag .= $ch;
3734  }
3735  $bracketState = 2; // building tag name
3736  } elseif ( $bracketState == 2 ) {
3737  if ( $ch != ' ' ) {
3738  $tag .= $ch;
3739  } else {
3740  // Name found (e.g. "<a href=..."), add on tag attributes...
3741  $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3742  }
3743  } elseif ( $bracketState == 0 ) {
3744  if ( $entityState ) {
3745  if ( $ch == ';' ) {
3746  $entityState = 0;
3747  $dispLen++; // entity is one displayed char
3748  }
3749  } else {
3750  if ( $neLength == 0 && !$maybeState ) {
3751  // Save state without $ch. We want to *hit* the first
3752  // display char (to get tags) but not *use* it if truncating.
3753  $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3754  }
3755  if ( $ch == '&' ) {
3756  $entityState = 1; // entity found, (e.g. "&#160;")
3757  } else {
3758  $dispLen++; // this char is displayed
3759  // Add the next $max display text chars after this in one swoop...
3760  $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3761  $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3762  $dispLen += $skipped;
3763  $pos += $skipped;
3764  }
3765  }
3766  }
3767  }
3768  // Close the last tag if left unclosed by bad HTML
3769  $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3770  while ( count( $openTags ) > 0 ) {
3771  $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3772  }
3773  return $ret;
3774  }
3775 
3787  private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3788  if ( $len === null ) {
3789  $len = -1; // -1 means "no limit" for strcspn
3790  } elseif ( $len < 0 ) {
3791  $len = 0; // sanity
3792  }
3793  $skipCount = 0;
3794  if ( $start < strlen( $text ) ) {
3795  $skipCount = strcspn( $text, $search, $start, $len );
3796  $ret .= substr( $text, $start, $skipCount );
3797  }
3798  return $skipCount;
3799  }
3800 
3810  private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3811  $tag = ltrim( $tag );
3812  if ( $tag != '' ) {
3813  if ( $tagType == 0 && $lastCh != '/' ) {
3814  $openTags[] = $tag; // tag opened (didn't close itself)
3815  } elseif ( $tagType == 1 ) {
3816  // @phan-suppress-next-line PhanRedundantCondition
3817  if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3818  array_pop( $openTags ); // tag closed
3819  }
3820  }
3821  $tag = '';
3822  }
3823  }
3824 
3833  public function convertGrammar( $word, $case ) {
3834  global $wgGrammarForms;
3835  if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3836  return $wgGrammarForms[$this->getCode()][$case][$word];
3837  }
3838 
3839  $grammarTransformations = $this->getGrammarTransformations();
3840 
3841  if ( isset( $grammarTransformations[$case] ) ) {
3842  $forms = $grammarTransformations[$case];
3843 
3844  // Some names of grammar rules are aliases for other rules.
3845  // In such cases the value is a string rather than object,
3846  // so load the actual rules.
3847  if ( is_string( $forms ) ) {
3848  $forms = $grammarTransformations[$forms];
3849  }
3850 
3851  foreach ( array_values( $forms ) as $rule ) {
3852  $form = $rule[0];
3853 
3854  if ( $form === '@metadata' ) {
3855  continue;
3856  }
3857 
3858  $replacement = $rule[1];
3859 
3860  $regex = '/' . addcslashes( $form, '/' ) . '/u';
3861  $patternMatches = preg_match( $regex, $word );
3862 
3863  if ( $patternMatches === false ) {
3864  wfLogWarning(
3865  'An error occurred while processing grammar. ' .
3866  "Word: '$word'. Regex: /$form/."
3867  );
3868  } elseif ( $patternMatches === 1 ) {
3869  $word = preg_replace( $regex, $replacement, $word );
3870 
3871  break;
3872  }
3873  }
3874  }
3875 
3876  return $word;
3877  }
3878 
3884  public function getGrammarForms() {
3885  global $wgGrammarForms;
3886  if ( isset( $wgGrammarForms[$this->getCode()] )
3887  && is_array( $wgGrammarForms[$this->getCode()] )
3888  ) {
3889  return $wgGrammarForms[$this->getCode()];
3890  }
3891 
3892  return [];
3893  }
3894 
3904  public function getGrammarTransformations() {
3905  if ( $this->grammarTransformCache !== null ) {
3906  return $this->grammarTransformCache;
3907  }
3908 
3909  $grammarDataFile = __DIR__ . "/data/grammarTransformations/{$this->getCode()}.json";
3910 
3911  $this->grammarTransformCache = is_readable( $grammarDataFile )
3912  ? FormatJson::decode( file_get_contents( $grammarDataFile ), true )
3913  : [];
3914 
3915  if ( $this->grammarTransformCache === null ) {
3916  throw new MWException( "Invalid grammar data for \"{$this->getCode()}\"." );
3917  }
3918 
3919  return $this->grammarTransformCache;
3920  }
3921 
3941  public function gender( $gender, $forms ) {
3942  if ( !count( $forms ) ) {
3943  return '';
3944  }
3945  $forms = $this->preConvertPlural( $forms, 2 );
3946  if ( $gender === 'male' ) {
3947  return $forms[0];
3948  }
3949  if ( $gender === 'female' ) {
3950  return $forms[1];
3951  }
3952  return $forms[2] ?? $forms[0];
3953  }
3954 
3970  public function convertPlural( $count, $forms ) {
3971  // Handle explicit n=pluralform cases
3972  $forms = $this->handleExplicitPluralForms( $count, $forms );
3973  if ( is_string( $forms ) ) {
3974  return $forms;
3975  }
3976  if ( !count( $forms ) ) {
3977  return '';
3978  }
3979 
3980  $pluralForm = $this->getPluralRuleIndexNumber( $count );
3981  $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3982  return $forms[$pluralForm];
3983  }
3984 
4000  protected function handleExplicitPluralForms( $count, array $forms ) {
4001  foreach ( $forms as $index => $form ) {
4002  if ( preg_match( '/\d+=/i', $form ) ) {
4003  $pos = strpos( $form, '=' );
4004  if ( substr( $form, 0, $pos ) === (string)$count ) {
4005  return substr( $form, $pos + 1 );
4006  }
4007  unset( $forms[$index] );
4008  }
4009  }
4010  return array_values( $forms );
4011  }
4012 
4021  protected function preConvertPlural( /* Array */ $forms, $count ) {
4022  return array_pad( $forms, $count, end( $forms ) );
4023  }
4024 
4041  public function embedBidi( $text = '' ) {
4042  $dir = self::strongDirFromContent( $text );
4043  if ( $dir === 'ltr' ) {
4044  // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
4045  return self::LRE . $text . self::PDF;
4046  }
4047  if ( $dir === 'rtl' ) {
4048  // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
4049  return self::RLE . $text . self::PDF;
4050  }
4051  // No strong directionality: do not wrap
4052  return $text;
4053  }
4054 
4068  public function translateBlockExpiry( $str, User $user = null, $now = 0 ) {
4069  $duration = SpecialBlock::getSuggestedDurations( $this );
4070  foreach ( $duration as $show => $value ) {
4071  if ( strcmp( $str, $value ) == 0 ) {
4072  return htmlspecialchars( trim( $show ) );
4073  }
4074  }
4075 
4076  if ( wfIsInfinity( $str ) ) {
4077  foreach ( $duration as $show => $value ) {
4078  if ( wfIsInfinity( $value ) ) {
4079  return htmlspecialchars( trim( $show ) );
4080  }
4081  }
4082  }
4083 
4084  // If all else fails, return a standard duration or timestamp description.
4085  $time = strtotime( $str, $now );
4086  if ( $time === false ) { // Unknown format. Return it as-is in case.
4087  return $str;
4088  } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
4089  // The result differs based on current time, so the difference
4090  // is a fixed duration length.
4091  return $this->formatDuration( $time - $now );
4092  } else { // It's an absolute timestamp.
4093  if ( $time === 0 ) {
4094  // wfTimestamp() handles 0 as current time instead of epoch.
4095  $time = '19700101000000';
4096  }
4097  if ( $user ) {
4098  return $this->userTimeAndDate( $time, $user );
4099  }
4100  return $this->timeanddate( $time );
4101  }
4102  }
4103 
4111  public function segmentForDiff( $text ) {
4112  return $text;
4113  }
4114 
4121  public function unsegmentForDiff( $text ) {
4122  return $text;
4123  }
4124 
4134  public function getConverter() : ILanguageConverter {
4135  return $this->converterFactory->getLanguageConverter( $this );
4136  }
4137 
4148  public function autoConvert( $text, $variant = false ) {
4149  return $this->getConverter()->autoConvert( $text, $variant );
4150  }
4151 
4160  public function autoConvertToAllVariants( $text ) {
4161  return $this->getConverter()->autoConvertToAllVariants( $text );
4162  }
4163 
4178  public function convert( $text ) {
4179  return $this->getConverter()->convert( $text );
4180  }
4181 
4190  public function convertTitle( $title ) {
4191  return $this->getConverter()->convertTitle( $title );
4192  }
4193 
4204  public function convertNamespace( $ns, $variant = null ) {
4205  return $this->getConverter()->convertNamespace( $ns, $variant );
4206  }
4207 
4215  public function hasVariants() {
4216  return count( $this->getVariants() ) > 1;
4217  }
4218 
4231  public function hasVariant( $variant ) {
4232  return $this->getConverter()->hasVariant( $variant );
4233  }
4234 
4244  public function convertHtml( $text ) {
4245  return htmlspecialchars( $this->convert( $text ) );
4246  }
4247 
4254  public function convertCategoryKey( $key ) {
4255  return $this->getConverter()->convertCategoryKey( $key );
4256  }
4257 
4266  public function getVariants() {
4267  return $this->getConverter()->getVariants();
4268  }
4269 
4274  public function getPreferredVariant() {
4275  return $this->getConverter()->getPreferredVariant();
4276  }
4277 
4282  public function getDefaultVariant() {
4283  return $this->getConverter()->getDefaultVariant();
4284  }
4285 
4290  public function getURLVariant() {
4291  return $this->getConverter()->getURLVariant();
4292  }
4293 
4308  public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4309  $this->getConverter()->findVariantLink( $link, $nt, $ignoreOtherCond );
4310  }
4311 
4320  public function getExtraHashOptions() {
4321  return $this->getConverter()->getExtraHashOptions();
4322  }
4323 
4332  public function updateConversionTable( LinkTarget $linkTarget ) {
4333  $this->getConverter()->updateConversionTable( $linkTarget );
4334  }
4335 
4342  public function linkTrail() {
4343  return $this->localisationCache->getItem( $this->mCode, 'linkTrail' );
4344  }
4345 
4352  public function linkPrefixCharset() {
4353  return $this->localisationCache->getItem( $this->mCode, 'linkPrefixCharset' );
4354  }
4355 
4364  public function getParentLanguage() {
4365  return MediaWikiServices::getInstance()->getLanguageFactory()
4366  ->getParentLanguage( $this->getCode() );
4367  }
4368 
4376  public function equals( Language $lang ) {
4377  return $lang === $this || $lang->getCode() === $this->mCode;
4378  }
4379 
4388  public function getCode() {
4389  return $this->mCode;
4390  }
4391 
4402  public function getHtmlCode() {
4403  if ( $this->mHtmlCode === null ) {
4404  $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
4405  }
4406  return $this->mHtmlCode;
4407  }
4408 
4416  public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4417  $m = null;
4418  preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4419  preg_quote( $suffix, '/' ) . '/', $filename, $m );
4420  if ( !count( $m ) ) {
4421  return false;
4422  }
4423  return str_replace( '_', '-', strtolower( $m[1] ) );
4424  }
4425 
4434  public static function classFromCode( $code, $fallback = true ) {
4435  wfDeprecated( __METHOD__, '1.35' );
4436 
4437  if ( $fallback && $code == 'en' ) {
4438  return 'Language';
4439  } else {
4440  return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
4441  }
4442  }
4443 
4454  public static function getFileName( $prefix, $code, $suffix = '.php' ) {
4455  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4456  ->getFileName( $prefix, $code, $suffix );
4457  }
4458 
4464  public static function getMessagesFileName( $code ) {
4465  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4466  ->getMessagesFileName( $code );
4467  }
4468 
4476  public static function getJsonMessagesFileName( $code ) {
4477  return MediaWikiServices::getInstance()->getLanguageNameUtils()
4478  ->getJsonMessagesFileName( $code );
4479  }
4480 
4489  public static function getFallbackFor( $code ) {
4490  return MediaWikiServices::getInstance()->getLanguageFallback()->getFirst( $code )
4491  ?? false;
4492  }
4493 
4506  public static function getFallbacksFor( $code, $mode = LanguageFallback::MESSAGES ) {
4507  return MediaWikiServices::getInstance()->getLanguageFallback()->getAll( $code, $mode );
4508  }
4509 
4520  public static function getFallbacksIncludingSiteLanguage( $code ) {
4521  return MediaWikiServices::getInstance()->getLanguageFallback()
4522  ->getAllIncludingSiteLanguage( $code );
4523  }
4524 
4536  public static function getMessagesFor( $code ) {
4537  return self::getLocalisationCache()->getItem( $code, 'messages' );
4538  }
4539 
4550  public static function getMessageFor( $key, $code ) {
4551  return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4552  }
4553 
4564  public static function getMessageKeysFor( $code ) {
4565  return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
4566  }
4567 
4572  private function fixVariableInNamespace( $talk ) {
4573  if ( strpos( $talk, '$1' ) === false ) {
4574  return $talk;
4575  }
4576 
4577  global $wgMetaNamespace;
4578  $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4579 
4580  # Allow grammar transformations
4581  # Allowing full message-style parsing would make simple requests
4582  # such as action=raw much more expensive than they need to be.
4583  # This will hopefully cover most cases.
4584  $talk = preg_replace_callback(
4585  '/{{grammar:(.*?)\|(.*?)}}/i',
4586  function ( $m ) {
4587  return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4588  },
4589  $talk
4590  );
4591  return str_replace( ' ', '_', $talk );
4592  }
4593 
4604  public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
4605  static $dbInfinity;
4606  if ( $dbInfinity === null ) {
4607  $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
4608  }
4609 
4610  if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4611  return $format === true
4612  ? $this->getMessageFromDB( 'infiniteblock' )
4613  : $infinity;
4614  } else {
4615  return $format === true
4616  ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4617  : wfTimestamp( $format, $expiry );
4618  }
4619  }
4620 
4635  public function formatTimePeriod( $seconds, $format = [] ) {
4636  if ( !is_array( $format ) ) {
4637  $format = [ 'avoid' => $format ]; // For backwards compatibility
4638  }
4639  if ( !isset( $format['avoid'] ) ) {
4640  $format['avoid'] = false;
4641  }
4642  if ( !isset( $format['noabbrevs'] ) ) {
4643  $format['noabbrevs'] = false;
4644  }
4645  $secondsMsg = wfMessage(
4646  $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4647  $minutesMsg = wfMessage(
4648  $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4649  $hoursMsg = wfMessage(
4650  $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4651  $daysMsg = wfMessage(
4652  $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4653 
4654  if ( round( $seconds * 10 ) < 100 ) {
4655  $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4656  $s = $secondsMsg->params( $s )->text();
4657  } elseif ( round( $seconds ) < 60 ) {
4658  $s = $this->formatNum( round( $seconds ) );
4659  $s = $secondsMsg->params( $s )->text();
4660  } elseif ( round( $seconds ) < 3600 ) {
4661  $minutes = floor( $seconds / 60 );
4662  $secondsPart = round( fmod( $seconds, 60 ) );
4663  if ( $secondsPart == 60 ) {
4664  $secondsPart = 0;
4665  $minutes++;
4666  }
4667  $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4668  $s .= ' ';
4669  $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4670  } elseif ( round( $seconds ) <= 2 * 86400 ) {
4671  $hours = floor( $seconds / 3600 );
4672  $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4673  $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4674  if ( $secondsPart == 60 ) {
4675  $secondsPart = 0;
4676  $minutes++;
4677  }
4678  if ( $minutes == 60 ) {
4679  $minutes = 0;
4680  $hours++;
4681  }
4682  $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4683  $s .= ' ';
4684  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4685  if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes', 'avoidhours' ] ) ) {
4686  $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4687  }
4688  } else {
4689  $days = floor( $seconds / 86400 );
4690  if ( $format['avoid'] === 'avoidhours' ) {
4691  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4692  if ( $hours == 24 ) {
4693  $hours = 0;
4694  $days++;
4695  }
4696  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4697  } elseif ( $format['avoid'] === 'avoidminutes' ) {
4698  $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4699  if ( $hours == 24 ) {
4700  $hours = 0;
4701  $days++;
4702  }
4703  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4704  $s .= ' ';
4705  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4706  } elseif ( $format['avoid'] === 'avoidseconds' ) {
4707  $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4708  $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4709  if ( $minutes == 60 ) {
4710  $minutes = 0;
4711  $hours++;
4712  }
4713  if ( $hours == 24 ) {
4714  $hours = 0;
4715  $days++;
4716  }
4717  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4718  $s .= ' ';
4719  $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4720  $s .= ' ';
4721  $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4722  } else {
4723  $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4724  $s .= ' ';
4725  $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4726  }
4727  }
4728  return $s;
4729  }
4730 
4742  public function formatBitrate( $bps ) {
4743  return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4744  }
4745 
4752  public function formatComputingNumbers( $size, $boundary, $messageKey ) {
4753  if ( $size <= 0 ) {
4754  return str_replace( '$1', $this->formatNum( $size ),
4755  $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4756  );
4757  }
4758  $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' ];
4759  $index = 0;
4760 
4761  $maxIndex = count( $sizes ) - 1;
4762  while ( $size >= $boundary && $index < $maxIndex ) {
4763  $index++;
4764  $size /= $boundary;
4765  }
4766 
4767  // For small sizes no decimal places necessary
4768  $round = 0;
4769  if ( $index > 1 ) {
4770  // For MB and bigger two decimal places are smarter
4771  $round = 2;
4772  }
4773  $msg = str_replace( '$1', $sizes[$index], $messageKey );
4774 
4775  $size = round( $size, $round );
4776  $text = $this->getMessageFromDB( $msg );
4777  return str_replace( '$1', $this->formatNum( $size ), $text );
4778  }
4779 
4790  public function formatSize( $size ) {
4791  return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4792  }
4793 
4803  public function specialList( $page, $details, $oppositedm = true ) {
4804  if ( !$details ) {
4805  return $page;
4806  }
4807 
4808  $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4809  return $page .
4810  $dirmark .
4811  $this->msg( 'word-separator' )->escaped() .
4812  $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4813  }
4814 
4827  public function viewPrevNext( Title $title, $offset, $limit,
4828  array $query = [], $atend = false
4829  ) {
4830  wfDeprecated( __METHOD__, '1.34' );
4831  // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4832 
4833  # Make 'previous' link
4834  $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4835  if ( $offset > 0 ) {
4836  $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4837  $query, $prev, 'prevn-title', 'mw-prevlink' );
4838  } else {
4839  $plink = htmlspecialchars( $prev );
4840  }
4841 
4842  # Make 'next' link
4843  $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4844  if ( $atend ) {
4845  $nlink = htmlspecialchars( $next );
4846  } else {
4847  $nlink = $this->numLink( $title, $offset + $limit, $limit,
4848  $query, $next, 'nextn-title', 'mw-nextlink' );
4849  }
4850 
4851  # Make links to set number of items per page
4852  $numLinks = [];
4853  foreach ( [ 20, 50, 100, 250, 500 ] as $num ) {
4854  $numLinks[] = $this->numLink( $title, $offset, $num,
4855  $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4856  }
4857 
4858  return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4859  )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4860  }
4861 
4876  private function numLink( Title $title, $offset, $limit, array $query, $link,
4877  $tooltipMsg, $class
4878  ) {
4879  $query = [ 'limit' => $limit, 'offset' => $offset ] + $query;
4880  $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4881  ->numParams( $limit )->text();
4882 
4883  return Html::element( 'a', [ 'href' => $title->getLocalURL( $query ),
4884  'title' => $tooltip, 'class' => $class ], $link );
4885  }
4886 
4894  public function getConvRuleTitle() {
4895  return $this->getConverter()->getConvRuleTitle();
4896  }
4897 
4903  public function getCompiledPluralRules() {
4904  $pluralRules =
4905  $this->localisationCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4906  if ( !$pluralRules ) {
4907  $fallbacks = $this->getFallbackLanguages();
4908  foreach ( $fallbacks as $fallbackCode ) {
4909  $pluralRules = $this->localisationCache
4910  ->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4911  if ( $pluralRules ) {
4912  break;
4913  }
4914  }
4915  }
4916  return $pluralRules;
4917  }
4918 
4924  public function getPluralRules() {
4925  $pluralRules =
4926  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4927  if ( !$pluralRules ) {
4928  $fallbacks = $this->getFallbackLanguages();
4929  foreach ( $fallbacks as $fallbackCode ) {
4930  $pluralRules = $this->localisationCache
4931  ->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4932  if ( $pluralRules ) {
4933  break;
4934  }
4935  }
4936  }
4937  return $pluralRules;
4938  }
4939 
4945  public function getPluralRuleTypes() {
4946  $pluralRuleTypes =
4947  $this->localisationCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4948  if ( !$pluralRuleTypes ) {
4949  $fallbacks = $this->getFallbackLanguages();
4950  foreach ( $fallbacks as $fallbackCode ) {
4951  $pluralRuleTypes = $this->localisationCache
4952  ->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4953  if ( $pluralRuleTypes ) {
4954  break;
4955  }
4956  }
4957  }
4958  return $pluralRuleTypes;
4959  }
4960 
4966  public function getPluralRuleIndexNumber( $number ) {
4967  $pluralRules = $this->getCompiledPluralRules();
4968  $form = Evaluator::evaluateCompiled( $number, $pluralRules );
4969  return $form;
4970  }
4971 
4980  public function getPluralRuleType( $number ) {
4981  $index = $this->getPluralRuleIndexNumber( $number );
4982  $pluralRuleTypes = $this->getPluralRuleTypes();
4983  return $pluralRuleTypes[$index] ?? 'other';
4984  }
4985 
4992  protected function getHookContainer() {
4993  return $this->hookContainer;
4994  }
4995 
5004  protected function getHookRunner() {
5005  return $this->hookRunner;
5006  }
5007 }
User\getDefaultOption
static getDefaultOption( $opt)
Get a given default option value.
Definition: User.php:1558
Language\$mCode
$mCode
Definition: Language.php:81
Language\internalUserTimeAndDate
internalUserTimeAndDate( $type, $ts, User $user, array $options)
Internal helper function for userDate(), userTime() and userTimeAndDate()
Definition: Language.php:2439
Language\$langFallback
LanguageFallback $langFallback
Definition: Language.php:120
Language\getCodeFromFileName
static getCodeFromFileName( $filename, $prefix='Language', $suffix='.php')
Get the language code from a file name.
Definition: Language.php:4416
Language\getExtraHashOptions
getExtraHashOptions()
returns language specific options used by User::getPageRenderHash() for example, the preferred langua...
Definition: Language.php:4320
Language\lc
lc( $str, $first=false)
Definition: Language.php:2759
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:34
Language\parseFormattedNumber
parseFormattedNumber( $number)
Definition: Language.php:3304
Language\getURLVariant
getURLVariant()
Definition: Language.php:4290
Language\getVariantname
getVariantname( $code, $usemsg=true)
short names for language variants used for language conversion links.
Definition: Language.php:843
Language\$hookContainer
HookContainer $hookContainer
Definition: Language.php:133
Language\getHookRunner
getHookRunner()
Get a HookRunner, for running core hooks.
Definition: Language.php:5004
Language\linkPrefixExtension
linkPrefixExtension()
To allow "foo[[bar]]" to extend the link over the whole word "foobar".
Definition: Language.php:3189
Language\$langNameUtils
LanguageNameUtils $langNameUtils
Definition: Language.php:117
StringUtils\isUtf8
static isUtf8( $value)
Test whether a string is valid UTF-8.
Definition: StringUtils.php:44
Language\clearCaches
static clearCaches()
Intended for tests that may change configuration in a way that invalidates caches.
Definition: Language.php:350
Language\truncate_endBracket
truncate_endBracket(&$tag, $tagType, $lastCh, &$openTags)
truncateHtml() helper function (a) push or pop $tag from $openTags as needed (b) clear $tag value
Definition: Language.php:3810
Language\commaList
commaList(array $list)
Take a list of strings and build a locale-friendly comma-separated list, using the local comma-separa...
Definition: Language.php:3466
Language\semicolonList
semicolonList(array $list)
Take a list of strings and build a locale-friendly semicolon-separated list, using the local semicolo...
Definition: Language.php:3479
Language\$mIranianCalendarMonthMsgs
static $mIranianCalendarMonthMsgs
Definition: Language.php:239
Language\$mMonthAbbrevMsgs
static $mMonthAbbrevMsgs
Definition: Language.php:224
Language\formatSize
formatSize( $size)
Format a size in bytes for output, using an appropriate unit (B, KB, MB, GB, TB, PB,...
Definition: Language.php:4790
Language\separatorTransformTable
separatorTransformTable()
Definition: Language.php:3423
Language\WEEKDAY_ABBREVIATED_MESSAGES
const WEEKDAY_ABBREVIATED_MESSAGES
Definition: Language.php:176
Language\resetNamespaces
resetNamespaces()
Resets all of the namespace caches.
Definition: Language.php:633
Language\getConverter
getConverter()
Return the LanguageConverter used in the Language.
Definition: Language.php:4134
Language\hasVariants
hasVariants()
Check if this is a language with variants.
Definition: Language.php:4215
Language\$mWeekdayAbbrevMsgs
static $mWeekdayAbbrevMsgs
Definition: Language.php:183
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:160
Language\preConvertPlural
preConvertPlural($forms, $count)
Checks that convertPlural was given an array and pads it to requested amount of forms by copying the ...
Definition: Language.php:4021
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
Language\convertHtml
convertHtml( $text)
Perform output conversion on a string, and encode for safe HTML output.
Definition: Language.php:4244
Language\minimumGroupingDigits
minimumGroupingDigits()
Definition: Language.php:3430
Language\segmentByWord
segmentByWord( $string)
Some languages such as Chinese require word segmentation, Specify such segmentation when overridden i...
Definition: Language.php:2895
Language\iconv
iconv( $in, $out, $string)
Definition: Language.php:2666
n
while(( $__line=Maintenance::readconsole()) !==false) print n
Definition: eval.php:64
Language\getMessageFromDB
getMessageFromDB( $msg)
Get a message from the MediaWiki namespace.
Definition: Language.php:946
Language\convert
convert( $text)
convert text to different variants of a language.
Definition: Language.php:4178
Language\ALL
const ALL
Return all known languages in fetchLanguageName(s).
Definition: Language.php:54
true
return true
Definition: router.php:90
Language\convertGrammar
convertGrammar( $word, $case)
Grammatical transformations, needed for inflected languages Invoked by putting {{grammar:case|word}} ...
Definition: Language.php:3833
$fallback
$fallback
Definition: MessagesAb.php:11
Language\mbUpperChar
mbUpperChar( $char)
Convert character to uppercase, allowing overrides of the default mb_upper behaviour,...
Definition: Language.php:2726
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=LanguageFallback::MESSAGES)
Get the ordered list of fallback languages.
Definition: Language.php:4506
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1815
getUser
getUser()
Language\truncateForVisual
truncateForVisual( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified number of characters, appending an optional string (e....
Definition: Language.php:3537
Language\$mMonthGenMsgs
static $mMonthGenMsgs
Definition: Language.php:211
Language\timeanddate
timeanddate( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2343
Language\$grammarTransformCache
array[] null $grammarTransformCache
Definition: Language.php:123
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
Language\MESSAGES_FALLBACKS
const MESSAGES_FALLBACKS
Return a fallback chain for messages in getFallbacksFor.
Definition: Language.php:151
$s
$s
Definition: mergeMessageFileList.php:184
Language\$mHijriCalendarMonthMsgs
static $mHijriCalendarMonthMsgs
Definition: Language.php:286
Language\$namespaceNames
array null $namespaceNames
Definition: Language.php:104
Language\getPreferredVariant
getPreferredVariant()
Definition: Language.php:4274
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1087
$digitGroupingPattern
$digitGroupingPattern
Definition: MessagesAs.php:167
User\getDatePreference
getDatePreference()
Get the user's preferred date format.
Definition: User.php:2778
Language\getDefaultVariant
getDefaultVariant()
Definition: Language.php:4282
Language\fallback8bitEncoding
fallback8bitEncoding()
Definition: Language.php:2872
Language\embedBidi
embedBidi( $text='')
Wraps argument with unicode control characters for directionality safety.
Definition: Language.php:4041
Language\truncateInternal
truncateInternal( $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring)
Internal method used for truncation.
Definition: Language.php:3563
Language\formatTimePeriod
formatTimePeriod( $seconds, $format=[])
Formats a time given in seconds into a string representation of that time.
Definition: Language.php:4635
Language\formatBitrate
formatBitrate( $bps)
Format a bitrate for output, using an appropriate unit (bps, kbps, Mbps, Gbps, Tbps,...
Definition: Language.php:4742
Language\equals
equals(Language $lang)
Compare with an other language object.
Definition: Language.php:4376
Language\SUPPORTED
const SUPPORTED
Return in fetchLanguageName(s) only the languages for which we have at least some localisation.
Definition: Language.php:62
Language\getSpecialPageAliases
getSpecialPageAliases()
Get special page names, as an associative array canonical name => array of valid names,...
Definition: Language.php:3223
Language\__construct
__construct( $code=null, LocalisationCache $localisationCache=null, LanguageNameUtils $langNameUtils=null, LanguageFallback $langFallback=null, LanguageConverterFactory $converterFactory=null, HookContainer $hookContainer=null)
Definition: Language.php:504
Language\getMessagesFileName
static getMessagesFileName( $code)
Definition: Language.php:4464
Language\getPluralRuleTypes
getPluralRuleTypes()
Get the plural rule types for the language.
Definition: Language.php:4945
Language\capitalizeAllNouns
capitalizeAllNouns()
Definition: Language.php:3156
Language\AS_AUTONYMS
const AS_AUTONYMS
Return autonyms in fetchLanguageName(s).
Definition: Language.php:47
Language\specialList
specialList( $page, $details, $oppositedm=true)
Make a list item, used by various special pages.
Definition: Language.php:4803
MediaWiki\Languages\LanguageConverterFactory
An interface for creating language converters.
Definition: LanguageConverterFactory.php:44
Language\$mHebrewCalendarMonthGenMsgs
static $mHebrewCalendarMonthGenMsgs
Definition: Language.php:271
$wgMetaNamespace
$wgMetaNamespace
Name of the project namespace.
Definition: DefaultSettings.php:4240
Language\checkTitleEncoding
checkTitleEncoding( $s)
TODO: $s is not always a string per T218883.
Definition: Language.php:2858
Language\isWellFormedLanguageTag
static isWellFormedLanguageTag( $code, $lenient=false)
Returns true if a language code string is a well-formed language tag according to RFC 5646.
Definition: Language.php:392
Language\getFormattedNamespaces
getFormattedNamespaces()
A convenience function that returns getNamespaces() with spaces instead of underscores in values.
Definition: Language.php:645
Language\lcfirst
lcfirst( $str)
Definition: Language.php:2736
MediaWiki\Languages\LanguageNameUtils
A service that provides utilities to do with language names and codes.
Definition: LanguageNameUtils.php:42
Language\formatExpiry
formatExpiry( $expiry, $format=true, $infinity='infinity')
Decode an expiry (block, protection, etc) which has come from the DB.
Definition: Language.php:4604
Language\isKnownLanguageTag
static isKnownLanguageTag( $tag)
Returns true if a language code is an IETF tag known to MediaWiki.
Definition: Language.php:479
Language\emphasize
emphasize( $text)
Italic is unsuitable for some languages.
Definition: Language.php:3240
Language\getFallbackLanguages
getFallbackLanguages()
Definition: Language.php:566
Language\getDurationIntervals
getDurationIntervals( $seconds, array $chosenIntervals=[])
Takes a number of seconds and returns an array with a set of corresponding intervals.
Definition: Language.php:2388
Language\caseFold
caseFold( $s)
Return a case-folded representation of $s.
Definition: Language.php:2849
Language\userTimeAndDate
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:2524
Language\segmentForDiff
segmentForDiff( $text)
languages like Chinese need to be segmented in order for the diff to be of any use
Definition: Language.php:4111
Language\classFromCode
static classFromCode( $code, $fallback=true)
Definition: Language.php:4434
Language\needsGenderDistinction
needsGenderDistinction()
Whether this language uses gender-dependent namespace aliases.
Definition: Language.php:710
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
Language\getLocalisationCache
static getLocalisationCache()
Get the LocalisationCache instance.
Definition: Language.php:490
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1059
MWException
MediaWiki exception.
Definition: MWException.php:29
MWTimestamp\offsetForUser
offsetForUser(User $user)
Adjust the timestamp depending on the given user's preferences.
Definition: MWTimestamp.php:81
NS_PROJECT
const NS_PROJECT
Definition: Defines.php:73
Language\viewPrevNext
viewPrevNext(Title $title, $offset, $limit, array $query=[], $atend=false)
Generate (prev x| next x) (20|50|100...) type links for paging.
Definition: Language.php:4827
Language\$transformData
$transformData
ReplacementArray object memoize.
Definition: Language.php:111
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
Language\updateConversionTable
updateConversionTable(LinkTarget $linkTarget)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
Definition: Language.php:4332
Language\tsToIranian
static tsToIranian( $ts)
Algorithm by Roozbeh Pournader and Mohammad Toossi to convert Gregorian dates to Iranian dates.
Definition: Language.php:1625
Language\unsegmentForDiff
unsegmentForDiff( $text)
and unsegment to show the result
Definition: Language.php:4121
Language\autoConvert
autoConvert( $text, $variant=false)
convert text to a variant
Definition: Language.php:4148
Language\truncateHtml
truncateHtml( $text, $length, $ellipsis='...')
Truncate a string of valid HTML to a specified length in bytes, appending an optional string (e....
Definition: Language.php:3668
Language\normalize
normalize( $s)
Convert a UTF-8 string to normal form C.
Definition: Language.php:3017
Language\getBookstoreList
getBookstoreList()
Exports $wgBookstoreListEn.
Definition: Language.php:574
Language\$mHebrewCalendarMonthMsgs
static $mHebrewCalendarMonthMsgs
Definition: Language.php:255
Language\DURATION_INTERVALS
const DURATION_INTERVALS
Definition: Language.php:291
Language\pipeList
pipeList(array $list)
Same as commaList, but separate it with the pipe instead.
Definition: Language.php:3491
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2475
Language\convertForSearchResult
convertForSearchResult( $termsArray)
Definition: Language.php:2948
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4550
$matches
$matches
Definition: NoLocalSettings.php:24
Language\getGenderNsText
getGenderNsText( $index, $gender)
Returns gender-dependent namespace alias if available.
Definition: Language.php:695
Language\listToText
listToText(array $list)
Take a list of strings and build a locale-friendly comma-separated list, using the local comma-separa...
Definition: Language.php:3442
Language\getHtmlCode
getHtmlCode()
Get the code in BCP 47 format which we can use inside of html lang="" tags.
Definition: Language.php:4402
Language\getNamespaceAliases
getNamespaceAliases()
Definition: Language.php:744
Language\$mExtendedSpecialPageAliases
array[] $mExtendedSpecialPageAliases
memoize
Definition: Language.php:101
Language\getLocalNsIndex
getLocalNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:734
Language\userDate
userDate( $ts, User $user, array $options=[])
Get the formatted date for the given timestamp and formatted for the given user.
Definition: Language.php:2478
Language\$mMonthMsgs
static $mMonthMsgs
Definition: Language.php:197
Language\truncateForDatabase
truncateForDatabase( $string, $length, $ellipsis='...', $adjustLength=true)
Truncate a string to a specified length in bytes, appending an optional string (e....
Definition: Language.php:3513
Language\getAllMessages
getAllMessages()
Definition: Language.php:2656
Language\getMagic
getMagic( $mw)
Fill a MagicWord object with data from here.
Definition: Language.php:3206
$wgOverrideUcfirstCharacters
array $wgOverrideUcfirstCharacters
List of Unicode characters for which capitalization is overridden in Language::ucfirst.
Definition: DefaultSettings.php:3365
Language\isRTL
isRTL()
For right-to-left language support.
Definition: Language.php:3080
Language\userTime
userTime( $ts, User $user, array $options=[])
Get the formatted time for the given timestamp and formatted for the given user.
Definition: Language.php:2501
$title
$title
Definition: testCompression.php:38
Language\getNsIndex
getNsIndex( $text)
Get a namespace key by value, case insensitive.
Definition: Language.php:825
Language\MONTH_GENITIVE_MESSAGES
const MONTH_GENITIVE_MESSAGES
Definition: Language.php:202
Language\getNamespaceIds
getNamespaceIds()
Definition: Language.php:801
Language\getPluralRuleIndexNumber
getPluralRuleIndexNumber( $number)
Find the index number of the plural rule appropriate for the given number.
Definition: Language.php:4966
Language\HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
const HEBREW_CALENDAR_MONTH_GENITIVE_MESSAGES
Definition: Language.php:260
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
Language\convertDoubleWidth
static convertDoubleWidth( $string)
convert double-width roman characters to single-width.
Definition: Language.php:2918
Language\getCompiledPluralRules
getCompiledPluralRules()
Get the compiled plural rules for the language.
Definition: Language.php:4903
Language\getHumanTimestampInternal
getHumanTimestampInternal(MWTimestamp $ts, MWTimestamp $relativeTo, User $user)
Convert an MWTimestamp into a pretty human-readable timestamp using the given user preferences and re...
Definition: Language.php:2580
Language\convertCategoryKey
convertCategoryKey( $key)
Definition: Language.php:4254
Language\digitGroupingPattern
digitGroupingPattern()
Definition: Language.php:3409
Language\$hookRunner
HookRunner $hookRunner
Definition: Language.php:138
Language\ucwords
ucwords( $str)
Definition: Language.php:2779
Language\getPluralRules
getPluralRules()
Get the plural rules for the language.
Definition: Language.php:4924
Language\getArrow
getArrow( $direction='forwards')
An arrow, depending on the language direction.
Definition: Language.php:3167
Language\uc
uc( $str, $first=false)
Definition: Language.php:2705
Language\translateBlockExpiry
translateBlockExpiry( $str, User $user=null, $now=0)
Definition: Language.php:4068
Language\formatNumNoSeparators
formatNumNoSeparators( $number)
Front-end for non-commafied formatNum.
Definition: Language.php:3296
$wgTranslateNumerals
$wgTranslateNumerals
For Hindi and Arabic use local numerals instead of Western style (0-9) numerals in interface.
Definition: DefaultSettings.php:3226
Language\$mHtmlCode
$mHtmlCode
Definition: Language.php:88
Language\MONTH_ABBREVIATED_MESSAGES
const MONTH_ABBREVIATED_MESSAGES
Definition: Language.php:216
$wgNamespaceAliases
$wgNamespaceAliases
Define extra namespace aliases.
Definition: DefaultSettings.php:4308
Language\isValidBuiltInCode
static isValidBuiltInCode( $code)
Returns true if a language code is of a valid form for the purposes of internal customisation of Medi...
Definition: Language.php:464
Language\$converterFactory
LanguageConverterFactory $converterFactory
Definition: Language.php:128
Language\formatDuration
formatDuration( $seconds, array $chosenIntervals=[])
Takes a number of seconds and turns it into a text using values such as hours and minutes.
Definition: Language.php:2362
Language\setNamespaces
setNamespaces(array $namespaces)
Arbitrarily set all of the namespace names at once.
Definition: Language.php:625
Language\linkPrefixCharset
linkPrefixCharset()
A regular expression character set to match legal word-prefixing characters which should be merged on...
Definition: Language.php:4352
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:72
ReplacementArray
Wrapper around strtr() that holds replacements.
Definition: ReplacementArray.php:24
Language\findVariantLink
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:4308
Language\fixVariableInNamespace
fixVariableInNamespace( $talk)
Definition: Language.php:4572
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:28
Language\ucwordbreaks
ucwordbreaks( $str)
capitalize words at word breaks
Definition: Language.php:2805
Language\getNsText
getNsText( $index)
Get a namespace value by key.
Definition: Language.php:664
$wgLocalTZoffset
$wgLocalTZoffset
Set an offset from UTC in minutes to use for the default timezone setting for anonymous users and new...
Definition: DefaultSettings.php:3352
Language\getCode
getCode()
Get the internal language code for this language object.
Definition: Language.php:4388
Language\LRE
const LRE
Unicode directional formatting characters, for embedBidi()
Definition: Language.php:313
Language\getPluralRuleType
getPluralRuleType( $number)
Find the plural rule type appropriate for the given number For example, if the language is set to Ara...
Definition: Language.php:4980
User\getOption
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2577
Language\dateFormat
dateFormat( $usePrefs=true)
This is meant to be used by time(), date(), and timeanddate() to get the date preference they're supp...
Definition: Language.php:2237
$wgMetaNamespaceTalk
$wgMetaNamespaceTalk
Name of the project talk namespace.
Definition: DefaultSettings.php:4249
Language\hebrewNumeral
static hebrewNumeral( $num)
Hebrew Gematria number formatting up to 9999.
Definition: Language.php:2067
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2793
Language\getFormattedNsText
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with '_' changed to ' ',...
Definition: Language.php:682
Language\getMessagesFor
static getMessagesFor( $code)
Get all messages for a given language WARNING: this may take a long time.
Definition: Language.php:4536
NS_PROJECT_TALK
const NS_PROJECT_TALK
Definition: Defines.php:74
Language\handleExplicitPluralForms
handleExplicitPluralForms( $count, array $forms)
Handles explicit plural forms for Language::convertPlural()
Definition: Language.php:4000
Language\RLE
const RLE
Definition: Language.php:314
Language\getFileName
static getFileName( $prefix, $code, $suffix='.php')
Get the name of a file for a certain language code.
Definition: Language.php:4454
LocalisationCache
Class for caching the contents of localisation files, Messages*.php and *.i18n.php.
Definition: LocalisationCache.php:43
Language\MONTH_MESSAGES
const MONTH_MESSAGES
Definition: Language.php:188
Language\getHookContainer
getHookContainer()
Get a HookContainer, for hook metadata and running extension hooks.
Definition: Language.php:4992
Language\HEBREW_CALENDAR_MONTHS_MESSAGES
const HEBREW_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:244
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:454
Language\getDirMark
getDirMark( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3144
Language\normalizeForSearch
normalizeForSearch( $string)
Some languages have special punctuation need to be normalized.
Definition: Language.php:2906
Language\isValidCode
static isValidCode( $code)
Returns true if a language code string is of a valid form, whether or not it exists.
Definition: Language.php:449
Language\__get
__get(string $name)
Use PHP's magic __get handler to handle lazy accessing to deprecated mConverter.
Definition: Language.php:71
Language\userAdjust
userAdjust( $ts, $tz=false)
Used by date() and time() to adjust the time output.
Definition: Language.php:2154
Language\formatComputingNumbers
formatComputingNumbers( $size, $boundary, $messageKey)
Definition: Language.php:4752
Language\$mLangObjCache
static array $mLangObjCache
Definition: Language.php:144
Language\getFallbackFor
static getFallbackFor( $code)
Get the first fallback for a given language.
Definition: Language.php:4489
Language\getParentLanguage
getParentLanguage()
Get the "parent" language which has a converter to convert a "compatible" language (in another varian...
Definition: Language.php:4364
Language\$dateFormatStrings
$dateFormatStrings
memoize
Definition: Language.php:94
Language\hasWordBreaks
hasWordBreaks()
Most writing systems use whitespace to break up words.
Definition: Language.php:2884
Language\getDir
getDir()
Return the correct HTML 'dir' attribute value for this language.
Definition: Language.php:3088
Language\date
date( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2304
Language\alignEnd
alignEnd()
Return 'right' or 'left' as appropriate alignment for line-end for this language's text direction.
Definition: Language.php:3112
Title
Represents a title within MediaWiki.
Definition: Title.php:41
Language\truncate_skip
truncate_skip(&$ret, $text, $search, $start, $len=null)
truncateHtml() helper function like strcspn() but adds the skipped chars to $ret
Definition: Language.php:3787
Language\getVariants
getVariants()
Get the list of variants supported by this language see sample implementation in LanguageZh....
Definition: Language.php:4266
Language\convertPlural
convertPlural( $count, $forms)
Plural form transformations, needed for some languages.
Definition: Language.php:3970
$minimumGroupingDigits
$minimumGroupingDigits
Definition: MessagesBe_tarask.php:239
Language\getFallbacksIncludingSiteLanguage
static getFallbacksIncludingSiteLanguage( $code)
Get the ordered list of fallback languages, ending with the fallback language chain for the site lang...
Definition: Language.php:4520
$wgGrammarForms
$wgGrammarForms
Some languages need different word forms, usually for different cases.
Definition: DefaultSettings.php:3110
Language\transformUsingPairFile
transformUsingPairFile( $file, $string, $basePath=null)
Transform a string using serialized data stored in the given file (which must be in the serialized su...
Definition: Language.php:3044
Language\getGrammarForms
getGrammarForms()
Get the grammar forms for the content language.
Definition: Language.php:3884
Language\removeBadCharFirst
removeBadCharFirst( $string)
Remove bytes that represent an incomplete Unicode character at the start of string (e....
Definition: Language.php:3642
Language\$strongDirRegex
static $strongDirRegex
Directionality test regex for embedBidi().
Definition: Language.php:330
LanguageCode\bcp47
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: LanguageCode.php:175
$wgExtraGenderNamespaces
$wgExtraGenderNamespaces
Same as above, but for namespaces with gender distinction.
Definition: DefaultSettings.php:4285
Language\getMessage
getMessage( $key)
Definition: Language.php:2649
Language\getGrammarTransformations
getGrammarTransformations()
Get the grammar transformations data for the language.
Definition: Language.php:3904
Language\getMessageKeysFor
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4564
Language\getJsonMessagesFileName
static getJsonMessagesFileName( $code)
Definition: Language.php:4476
Language\IRANIAN_CALENDAR_MONTHS_MESSAGES
const IRANIAN_CALENDAR_MONTHS_MESSAGES
Definition: Language.php:229
Language\firstChar
firstChar( $s)
Get the first character of a string.
Definition: Language.php:2960
$basePath
$basePath
Definition: addSite.php:5
NS_USER
const NS_USER
Definition: Defines.php:71
Language\getNamespaces
getNamespaces()
Returns an array of localised namespaces indexed by their numbers.
Definition: Language.php:584
Language\$localisationCache
LocalisationCache $localisationCache
Definition: Language.php:114
SpecialBlock\getSuggestedDurations
static getSuggestedDurations(Language $lang=null, $includeOther=true)
Get an array of suggested block durations from MediaWiki:Ipboptions.
Definition: SpecialBlock.php:901
Language\removeBadCharLast
removeBadCharLast( $string)
Remove bytes that represent an incomplete Unicode character at the end of string (e....
Definition: Language.php:3616
Language\romanNumeral
static romanNumeral( $num)
Roman number formatting up to 10000.
Definition: Language.php:2036
Language\getConvRuleTitle
getConvRuleTitle()
Get the conversion rule title, if any.
Definition: Language.php:4894
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:340
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
Language\PDF
const PDF
Definition: Language.php:315
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1074
Language\$namespaceAliases
$namespaceAliases
Definition: Language.php:105
Language\tsToHijri
static tsToHijri( $ts)
Converting Gregorian dates to Hijri dates.
Definition: Language.php:1685
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:562
Language\getHumanTimestamp
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:2543
$t
$t
Definition: testCompression.php:74
Language\time
time( $ts, $adj=false, $format=true, $timecorrection=false)
Definition: Language.php:2323
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
Language\insertSpace
static insertSpace( $string, $pattern)
Definition: Language.php:2938
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
Language\isMultibyte
isMultibyte( $str)
Definition: Language.php:2771
Language\alignStart
alignStart()
Return 'left' or 'right' as appropriate alignment for line-start for this language's text direction.
Definition: Language.php:3100
Language\isSupportedLanguage
static isSupportedLanguage( $code)
Checks whether any localisation is available for that language tag in MediaWiki (MessagesXx....
Definition: Language.php:372
Language\$mWeekdayMsgs
static $mWeekdayMsgs
Definition: Language.php:171
Language\digitTransformTable
digitTransformTable()
Definition: Language.php:3416
Language\tsToYear
static tsToYear( $ts, $cName)
Algorithm to convert Gregorian dates to Thai solar dates, Minguo dates or Minguo dates.
Definition: Language.php:1913
Language\getDirMarkEntity
getDirMarkEntity( $opposite=false)
A hidden direction mark (LRM or RLM), depending on the language direction.
Definition: Language.php:3127
Language\strongDirFromContent
static strongDirFromContent( $text='')
Gets directionality of the first strongly directional codepoint, for embedBidi()
Definition: Language.php:2019
Language\hebrewYearStart
static hebrewYearStart( $year)
This calculates the Hebrew year start, as days since 1 September.
Definition: Language.php:1875
Language\$mNamespaceIds
$mNamespaceIds
Definition: Language.php:105
$IP
$IP
Definition: WebStart.php:49
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
Language\getDateFormatString
getDateFormatString( $type, $pref)
Get a format string for a given type and preference.
Definition: Language.php:2268
Language\getMagicWords
getMagicWords()
Get all magic words from cache.
Definition: Language.php:3197
Language\hasVariant
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: Language.php:4231
Language\numLink
numLink(Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class)
Helper function for viewPrevNext() that generates links.
Definition: Language.php:4876
Language\__destruct
__destruct()
Reduce memory usage PhanTypeSuspiciousNonTraversableForeach.
Definition: Language.php:556
Language\commafy
commafy( $number)
Adds commas to a given number.
Definition: Language.php:3331
Language\HIJRI_CALENDAR_MONTH_MESSAGES
const HIJRI_CALENDAR_MONTH_MESSAGES
Definition: Language.php:276
Language\STRICT_FALLBACKS
const STRICT_FALLBACKS
Return a strict fallback chain in getFallbacksFor.
Definition: Language.php:158
$wgExtraNamespaces
$wgExtraNamespaces
Additional namespaces.
Definition: DefaultSettings.php:4277
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:41
Language\$durationIntervals
static array $durationIntervals
Definition: Language.php:308
Language\tsToHebrew
static tsToHebrew( $ts)
Converting Gregorian dates to Hebrew dates.
Definition: Language.php:1737
Language\autoConvertToAllVariants
autoConvertToAllVariants( $text)
convert text to all supported variants
Definition: Language.php:4160
Language\linkTrail
linkTrail()
A regular expression to match legal word-trailing characters which should be merged onto a link of th...
Definition: Language.php:4342
$wgAllUnicodeFixes
$wgAllUnicodeFixes
Set this to always convert certain Unicode sequences to modern ones regardless of the content languag...
Definition: DefaultSettings.php:3188
Language\ucfirst
ucfirst( $str)
Definition: Language.php:2681
Language\$mMagicExtensions
$mMagicExtensions
Definition: Language.php:86
Language\gender
gender( $gender, $forms)
Provides an alternative text depending on specified gender.
Definition: Language.php:3941
Language\WEEKDAY_MESSAGES
const WEEKDAY_MESSAGES
Definition: Language.php:163
Language\formatNum
formatNum( $number, $nocommafy=false)
Normally we output all numbers in plain en_US style, that is 293,291.235 for two hundred ninety-three...
Definition: Language.php:3266
$type
$type
Definition: testCompression.php:52
Language\convertNamespace
convertNamespace( $ns, $variant=null)
Convert a namespace index to a string in the preferred variant.
Definition: Language.php:4204
Language\convertTitle
convertTitle( $title)
Convert a Title object to a string in the preferred variant.
Definition: Language.php:4190