Merge "Localisation updates from https://translatewiki.net."
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * Internationalisation code.
4 * See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more information.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Language
23 */
24
25 /**
26 * @defgroup Language Language
27 */
28
29 use CLDRPluralRuleParser\Evaluator;
30 use MediaWiki\MediaWikiServices;
31 use Wikimedia\Assert\Assert;
32
33 /**
34 * Internationalisation code
35 * @ingroup Language
36 */
37 class Language {
38 /**
39 * Return autonyms in fetchLanguageName(s).
40 * @since 1.32
41 */
42 const AS_AUTONYMS = null;
43
44 /**
45 * Return all known languages in fetchLanguageName(s).
46 * @since 1.32
47 */
48 const ALL = 'all';
49
50 /**
51 * Return in fetchLanguageName(s) only the languages for which we have at
52 * least some localisation.
53 * @since 1.32
54 */
55 const SUPPORTED = 'mwfile';
56
57 /**
58 * @var LanguageConverter|FakeConverter
59 */
60 public $mConverter;
61
62 public $mVariants, $mCode, $mLoaded = false;
63 public $mMagicExtensions = [];
64 private $mHtmlCode = null;
65 /** @var Language|false */
66 private $mParentLanguage = false;
67
68 public $dateFormatStrings = [];
69 public $mExtendedSpecialPageAliases;
70
71 /** @var array|null */
72 protected $namespaceNames;
73 protected $mNamespaceIds, $namespaceAliases;
74
75 /**
76 * ReplacementArray object caches
77 */
78 public $transformData = [];
79
80 /**
81 * @var LocalisationCache
82 */
83 public static $dataCache;
84
85 public static $mLangObjCache = [];
86
87 /**
88 * Return a fallback chain for messages in getFallbacksFor
89 * @since 1.32
90 */
91 const MESSAGES_FALLBACKS = 0;
92
93 /**
94 * Return a strict fallback chain in getFallbacksFor
95 * @since 1.32
96 */
97 const STRICT_FALLBACKS = 1;
98
99 public static $mWeekdayMsgs = [
100 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
101 'friday', 'saturday'
102 ];
103
104 public static $mWeekdayAbbrevMsgs = [
105 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
106 ];
107
108 public static $mMonthMsgs = [
109 'january', 'february', 'march', 'april', 'may_long', 'june',
110 'july', 'august', 'september', 'october', 'november',
111 'december'
112 ];
113 public static $mMonthGenMsgs = [
114 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
115 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
116 'december-gen'
117 ];
118 public static $mMonthAbbrevMsgs = [
119 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
120 'sep', 'oct', 'nov', 'dec'
121 ];
122
123 public static $mIranianCalendarMonthMsgs = [
124 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
125 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
126 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
127 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
128 ];
129
130 public static $mHebrewCalendarMonthMsgs = [
131 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
132 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
133 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
134 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
135 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
136 ];
137
138 public static $mHebrewCalendarMonthGenMsgs = [
139 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
140 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
141 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
142 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
143 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
144 ];
145
146 public static $mHijriCalendarMonthMsgs = [
147 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
148 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
149 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
150 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
151 ];
152
153 /**
154 * @since 1.20
155 * @var array
156 */
157 public static $durationIntervals = [
158 'millennia' => 31556952000,
159 'centuries' => 3155695200,
160 'decades' => 315569520,
161 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
162 'weeks' => 604800,
163 'days' => 86400,
164 'hours' => 3600,
165 'minutes' => 60,
166 'seconds' => 1,
167 ];
168
169 /**
170 * Cache for language fallbacks.
171 * @see Language::getFallbacksIncludingSiteLanguage
172 * @since 1.21
173 * @var array
174 */
175 private static $fallbackLanguageCache = [];
176
177 /**
178 * Cache for grammar rules data
179 * @var MapCacheLRU|null
180 */
181 private static $grammarTransformations;
182
183 /**
184 * Cache for language names
185 * @var HashBagOStuff|null
186 */
187 private static $languageNameCache;
188
189 /**
190 * Unicode directional formatting characters, for embedBidi()
191 */
192 private static $lre = "\u{202A}"; // U+202A LEFT-TO-RIGHT EMBEDDING
193 private static $rle = "\u{202B}"; // U+202B RIGHT-TO-LEFT EMBEDDING
194 private static $pdf = "\u{202C}"; // U+202C POP DIRECTIONAL FORMATTING
195
196 /**
197 * Directionality test regex for embedBidi(). Matches the first strong directionality codepoint:
198 * - in group 1 if it is LTR
199 * - in group 2 if it is RTL
200 * Does not match if there is no strong directionality codepoint.
201 *
202 * The form is '/(?:([strong ltr codepoint])|([strong rtl codepoint]))/u' .
203 *
204 * Generated by UnicodeJS (see tools/strongDir) from the UCD; see
205 * https://phabricator.wikimedia.org/diffusion/GUJS/ .
206 */
207 // @codeCoverageIgnoreStart
208 // phpcs:ignore Generic.Files.LineLength
209 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';
210 // @codeCoverageIgnoreEnd
211
212 /**
213 * Get a cached or new language object for a given language code
214 * @param string $code
215 * @throws MWException
216 * @return Language
217 */
218 static function factory( $code ) {
219 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
220
221 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
222 $code = $wgDummyLanguageCodes[$code];
223 }
224
225 // get the language object to process
226 $langObj = self::$mLangObjCache[$code] ?? self::newFromCode( $code );
227
228 // merge the language object in to get it up front in the cache
229 self::$mLangObjCache = array_merge( [ $code => $langObj ], self::$mLangObjCache );
230 // get rid of the oldest ones in case we have an overflow
231 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
232
233 return $langObj;
234 }
235
236 /**
237 * Create a language object for a given language code
238 * @param string $code
239 * @param bool $fallback Whether we're going through language fallback chain
240 * @throws MWException
241 * @return Language
242 */
243 protected static function newFromCode( $code, $fallback = false ) {
244 if ( !self::isValidCode( $code ) ) {
245 throw new MWException( "Invalid language code \"$code\"" );
246 }
247
248 if ( !self::isValidBuiltInCode( $code ) ) {
249 // It's not possible to customise this code with class files, so
250 // just return a Language object. This is to support uselang= hacks.
251 $lang = new Language;
252 $lang->mCode = $code;
253 return $lang;
254 }
255
256 // Check if there is a language class for the code
257 $class = self::classFromCode( $code, $fallback );
258 // LanguageCode does not inherit Language
259 if ( class_exists( $class ) && is_a( $class, 'Language', true ) ) {
260 $lang = new $class;
261 return $lang;
262 }
263
264 // Keep trying the fallback list until we find an existing class
265 $fallbacks = self::getFallbacksFor( $code );
266 foreach ( $fallbacks as $fallbackCode ) {
267 if ( !self::isValidBuiltInCode( $fallbackCode ) ) {
268 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
269 }
270
271 $class = self::classFromCode( $fallbackCode );
272 if ( class_exists( $class ) ) {
273 $lang = new $class;
274 $lang->mCode = $code;
275 return $lang;
276 }
277 }
278
279 throw new MWException( "Invalid fallback sequence for language '$code'" );
280 }
281
282 /**
283 * Intended for tests that may change configuration in a way that invalidates caches.
284 *
285 * @since 1.32
286 */
287 public static function clearCaches() {
288 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
289 throw new MWException( __METHOD__ . ' must not be used outside tests' );
290 }
291 self::$dataCache = null;
292 // Reinitialize $dataCache, since it's expected to always be available
293 self::getLocalisationCache();
294 self::$mLangObjCache = [];
295 self::$fallbackLanguageCache = [];
296 self::$grammarTransformations = null;
297 self::$languageNameCache = null;
298 }
299
300 /**
301 * Checks whether any localisation is available for that language tag
302 * in MediaWiki (MessagesXx.php exists).
303 *
304 * @param string $code Language tag (in lower case)
305 * @return bool Whether language is supported
306 * @since 1.21
307 */
308 public static function isSupportedLanguage( $code ) {
309 if ( !self::isValidBuiltInCode( $code ) ) {
310 return false;
311 }
312
313 if ( $code === 'qqq' ) {
314 return false;
315 }
316
317 return is_readable( self::getMessagesFileName( $code ) ) ||
318 is_readable( self::getJsonMessagesFileName( $code ) );
319 }
320
321 /**
322 * Returns true if a language code string is a well-formed language tag
323 * according to RFC 5646.
324 * This function only checks well-formedness; it doesn't check that
325 * language, script or variant codes actually exist in the repositories.
326 *
327 * Based on regexes by Mark Davis of the Unicode Consortium:
328 * https://www.unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
329 *
330 * @param string $code
331 * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
332 *
333 * @return bool
334 * @since 1.21
335 */
336 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
337 $alpha = '[a-z]';
338 $digit = '[0-9]';
339 $alphanum = '[a-z0-9]';
340 $x = 'x'; # private use singleton
341 $singleton = '[a-wy-z]'; # other singleton
342 $s = $lenient ? '[-_]' : '-';
343
344 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
345 $script = "$alpha{4}"; # ISO 15924
346 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
347 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
348 $extension = "$singleton(?:$s$alphanum{2,8})+";
349 $privateUse = "$x(?:$s$alphanum{1,8})+";
350
351 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
352 # Since these are limited, this is safe even later changes to the registry --
353 # the only oddity is that it might change the type of the tag, and thus
354 # the results from the capturing groups.
355 # https://www.iana.org/assignments/language-subtag-registry
356
357 $grandfathered = "en{$s}GB{$s}oed"
358 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
359 . "|no{$s}(?:bok|nyn)"
360 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
361 . "|zh{$s}min{$s}nan";
362
363 $variantList = "$variant(?:$s$variant)*";
364 $extensionList = "$extension(?:$s$extension)*";
365
366 $langtag = "(?:($language)"
367 . "(?:$s$script)?"
368 . "(?:$s$region)?"
369 . "(?:$s$variantList)?"
370 . "(?:$s$extensionList)?"
371 . "(?:$s$privateUse)?)";
372
373 # The final breakdown, with capturing groups for each of these components
374 # The variants, extensions, grandfathered, and private-use may have interior '-'
375
376 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
377
378 return (bool)preg_match( "/$root/", strtolower( $code ) );
379 }
380
381 /**
382 * Returns true if a language code string is of a valid form, whether or
383 * not it exists. This includes codes which are used solely for
384 * customisation via the MediaWiki namespace.
385 *
386 * @param string $code
387 *
388 * @return bool
389 */
390 public static function isValidCode( $code ) {
391 static $cache = [];
392 Assert::parameterType( 'string', $code, '$code' );
393 if ( !isset( $cache[$code] ) ) {
394 // People think language codes are html safe, so enforce it.
395 // Ideally we should only allow a-zA-Z0-9-
396 // but, .+ and other chars are often used for {{int:}} hacks
397 // see bugs T39564, T39587, T38938
398 $cache[$code] =
399 // Protect against path traversal
400 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
401 && !preg_match( MediaWikiTitleCodec::getTitleInvalidRegex(), $code );
402 }
403 return $cache[$code];
404 }
405
406 /**
407 * Returns true if a language code is of a valid form for the purposes of
408 * internal customisation of MediaWiki, via Messages*.php or *.json.
409 *
410 * @param string $code
411 *
412 * @since 1.18
413 * @return bool
414 */
415 public static function isValidBuiltInCode( $code ) {
416 Assert::parameterType( 'string', $code, '$code' );
417
418 return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
419 }
420
421 /**
422 * Returns true if a language code is an IETF tag known to MediaWiki.
423 *
424 * @param string $tag
425 *
426 * @since 1.21
427 * @return bool
428 */
429 public static function isKnownLanguageTag( $tag ) {
430 // Quick escape for invalid input to avoid exceptions down the line
431 // when code tries to process tags which are not valid at all.
432 if ( !self::isValidBuiltInCode( $tag ) ) {
433 return false;
434 }
435
436 if ( isset( MediaWiki\Languages\Data\Names::$names[$tag] )
437 || self::fetchLanguageName( $tag, $tag ) !== ''
438 ) {
439 return true;
440 }
441
442 return false;
443 }
444
445 /**
446 * Get the LocalisationCache instance
447 *
448 * @return LocalisationCache
449 */
450 public static function getLocalisationCache() {
451 if ( is_null( self::$dataCache ) ) {
452 global $wgLocalisationCacheConf;
453 $class = $wgLocalisationCacheConf['class'];
454 self::$dataCache = new $class( $wgLocalisationCacheConf );
455 }
456 return self::$dataCache;
457 }
458
459 function __construct() {
460 $this->mConverter = new FakeConverter( $this );
461 // Set the code to the name of the descendant
462 if ( static::class === 'Language' ) {
463 $this->mCode = 'en';
464 } else {
465 $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
466 }
467 self::getLocalisationCache();
468 }
469
470 /**
471 * Reduce memory usage
472 * @suppress PhanTypeSuspiciousNonTraversableForeach
473 */
474 function __destruct() {
475 foreach ( $this as $name => $value ) {
476 unset( $this->$name );
477 }
478 }
479
480 /**
481 * Hook which will be called if this is the content language.
482 * Descendants can use this to register hook functions or modify globals
483 */
484 function initContLang() {
485 }
486
487 /**
488 * @return array
489 * @since 1.19
490 */
491 public function getFallbackLanguages() {
492 return self::getFallbacksFor( $this->mCode );
493 }
494
495 /**
496 * Exports $wgBookstoreListEn
497 * @return array
498 */
499 public function getBookstoreList() {
500 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
501 }
502
503 /**
504 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
505 * available in localised form, it will be included in English.
506 *
507 * @return string[] List of localized namespace names, indexed by numeric namespace ID.
508 */
509 public function getNamespaces() {
510 if ( is_null( $this->namespaceNames ) ) {
511 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
512
513 $validNamespaces = MediaWikiServices::getInstance()->getNamespaceInfo()->
514 getCanonicalNamespaces();
515
516 $this->namespaceNames = $wgExtraNamespaces +
517 self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
518 $this->namespaceNames += $validNamespaces;
519
520 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
521 if ( $wgMetaNamespaceTalk ) {
522 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
523 } else {
524 $talk = $this->namespaceNames[NS_PROJECT_TALK];
525 $this->namespaceNames[NS_PROJECT_TALK] =
526 $this->fixVariableInNamespace( $talk );
527 }
528
529 # Sometimes a language will be localised but not actually exist on this wiki.
530 // @phan-suppress-next-line PhanTypeMismatchForeach
531 foreach ( $this->namespaceNames as $key => $text ) {
532 if ( !isset( $validNamespaces[$key] ) ) {
533 unset( $this->namespaceNames[$key] );
534 }
535 }
536
537 # The above mixing may leave namespaces out of canonical order.
538 # Re-order by namespace ID number...
539 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
540 ksort( $this->namespaceNames );
541
542 Hooks::run( 'LanguageGetNamespaces', [ &$this->namespaceNames ] );
543 }
544
545 return $this->namespaceNames;
546 }
547
548 /**
549 * Arbitrarily set all of the namespace names at once. Mainly used for testing
550 * @param array $namespaces Array of namespaces (id => name)
551 */
552 public function setNamespaces( array $namespaces ) {
553 $this->namespaceNames = $namespaces;
554 $this->mNamespaceIds = null;
555 }
556
557 /**
558 * Resets all of the namespace caches. Mainly used for testing
559 */
560 public function resetNamespaces() {
561 $this->namespaceNames = null;
562 $this->mNamespaceIds = null;
563 $this->namespaceAliases = null;
564 }
565
566 /**
567 * A convenience function that returns getNamespaces() with spaces instead of underscores
568 * in values. Useful for producing output to be displayed e.g. in `<select>` forms.
569 *
570 * @return array
571 */
572 public function getFormattedNamespaces() {
573 $ns = $this->getNamespaces();
574 foreach ( $ns as $k => $v ) {
575 $ns[$k] = strtr( $v, '_', ' ' );
576 }
577 return $ns;
578 }
579
580 /**
581 * Get a namespace value by key
582 *
583 * <code>
584 * $mw_ns = $lang->getNsText( NS_MEDIAWIKI );
585 * echo $mw_ns; // prints 'MediaWiki'
586 * </code>
587 *
588 * @param int $index The array key of the namespace to return
589 * @return string|bool String if the namespace value exists, otherwise false
590 */
591 public function getNsText( $index ) {
592 $ns = $this->getNamespaces();
593 return $ns[$index] ?? false;
594 }
595
596 /**
597 * A convenience function that returns the same thing as
598 * getNsText() except with '_' changed to ' ', useful for
599 * producing output.
600 *
601 * <code>
602 * $mw_ns = $lang->getFormattedNsText( NS_MEDIAWIKI_TALK );
603 * echo $mw_ns; // prints 'MediaWiki talk'
604 * </code>
605 *
606 * @param int $index The array key of the namespace to return
607 * @return string Namespace name without underscores (empty string if namespace does not exist)
608 */
609 public function getFormattedNsText( $index ) {
610 $ns = $this->getNsText( $index );
611 return strtr( $ns, '_', ' ' );
612 }
613
614 /**
615 * Returns gender-dependent namespace alias if available.
616 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
617 * @param int $index Namespace index
618 * @param string $gender Gender key (male, female... )
619 * @return string
620 * @since 1.18
621 */
622 public function getGenderNsText( $index, $gender ) {
623 global $wgExtraGenderNamespaces;
624
625 $ns = $wgExtraGenderNamespaces +
626 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
627
628 return $ns[$index][$gender] ?? $this->getNsText( $index );
629 }
630
631 /**
632 * Whether this language uses gender-dependent namespace aliases.
633 * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
634 * @return bool
635 * @since 1.18
636 */
637 public function needsGenderDistinction() {
638 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
639 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
640 // $wgExtraGenderNamespaces overrides everything
641 return true;
642 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
643 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
644 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
645 return false;
646 } else {
647 // Check what is in i18n files
648 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
649 return count( $aliases ) > 0;
650 }
651 }
652
653 /**
654 * Get a namespace key by value, case insensitive.
655 * Only matches namespace names for the current language, not the
656 * canonical ones defined in Namespace.php.
657 *
658 * @param string $text
659 * @return int|bool An integer if $text is a valid value otherwise false
660 */
661 function getLocalNsIndex( $text ) {
662 $lctext = $this->lc( $text );
663 $ids = $this->getNamespaceIds();
664 return $ids[$lctext] ?? false;
665 }
666
667 /**
668 * @return array
669 */
670 public function getNamespaceAliases() {
671 if ( is_null( $this->namespaceAliases ) ) {
672 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
673 if ( !$aliases ) {
674 $aliases = [];
675 } else {
676 foreach ( $aliases as $name => $index ) {
677 if ( $index === NS_PROJECT_TALK ) {
678 unset( $aliases[$name] );
679 $name = $this->fixVariableInNamespace( $name );
680 $aliases[$name] = $index;
681 }
682 }
683 }
684
685 global $wgExtraGenderNamespaces;
686 $genders = $wgExtraGenderNamespaces +
687 (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
688 foreach ( $genders as $index => $forms ) {
689 foreach ( $forms as $alias ) {
690 $aliases[$alias] = $index;
691 }
692 }
693
694 # Also add converted namespace names as aliases, to avoid confusion.
695 $convertedNames = [];
696 foreach ( $this->getVariants() as $variant ) {
697 if ( $variant === $this->mCode ) {
698 continue;
699 }
700 foreach ( $this->getNamespaces() as $ns => $_ ) {
701 $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
702 }
703 }
704
705 $this->namespaceAliases = $aliases + $convertedNames;
706
707 # Filter out aliases to namespaces that don't exist, e.g. from extensions
708 # that aren't loaded here but are included in the l10n cache.
709 # (array_intersect preserves keys from its first argument)
710 $this->namespaceAliases = array_intersect(
711 $this->namespaceAliases,
712 array_keys( $this->getNamespaces() )
713 );
714 }
715
716 return $this->namespaceAliases;
717 }
718
719 /**
720 * @return array
721 */
722 public function getNamespaceIds() {
723 if ( is_null( $this->mNamespaceIds ) ) {
724 global $wgNamespaceAliases;
725 # Put namespace names and aliases into a hashtable.
726 # If this is too slow, then we should arrange it so that it is done
727 # before caching. The catch is that at pre-cache time, the above
728 # class-specific fixup hasn't been done.
729 $this->mNamespaceIds = [];
730 foreach ( $this->getNamespaces() as $index => $name ) {
731 $this->mNamespaceIds[$this->lc( $name )] = $index;
732 }
733 foreach ( $this->getNamespaceAliases() as $name => $index ) {
734 $this->mNamespaceIds[$this->lc( $name )] = $index;
735 }
736 if ( $wgNamespaceAliases ) {
737 foreach ( $wgNamespaceAliases as $name => $index ) {
738 $this->mNamespaceIds[$this->lc( $name )] = $index;
739 }
740 }
741 }
742 return $this->mNamespaceIds;
743 }
744
745 /**
746 * Get a namespace key by value, case insensitive. Canonical namespace
747 * names override custom ones defined for the current language.
748 *
749 * @param string $text
750 * @return int|bool An integer if $text is a valid value otherwise false
751 */
752 public function getNsIndex( $text ) {
753 $lctext = $this->lc( $text );
754 $ns = MediaWikiServices::getInstance()->getNamespaceInfo()->
755 getCanonicalIndex( $lctext );
756 if ( $ns !== null ) {
757 return $ns;
758 }
759 $ids = $this->getNamespaceIds();
760 return $ids[$lctext] ?? false;
761 }
762
763 /**
764 * short names for language variants used for language conversion links.
765 *
766 * @param string $code
767 * @param bool $usemsg Use the "variantname-xyz" message if it exists
768 * @return string
769 */
770 public function getVariantname( $code, $usemsg = true ) {
771 $msg = "variantname-$code";
772 if ( $usemsg && wfMessage( $msg )->exists() ) {
773 return $this->getMessageFromDB( $msg );
774 }
775 $name = self::fetchLanguageName( $code );
776 if ( $name ) {
777 return $name; # if it's defined as a language name, show that
778 } else {
779 # otherwise, output the language code
780 return $code;
781 }
782 }
783
784 /**
785 * @return string[]|bool List of date format preference keys, or false if disabled.
786 */
787 public function getDatePreferences() {
788 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
789 }
790
791 /**
792 * @return array
793 */
794 function getDateFormats() {
795 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
796 }
797
798 /**
799 * @return array|string
800 */
801 public function getDefaultDateFormat() {
802 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
803 if ( $df === 'dmy or mdy' ) {
804 global $wgAmericanDates;
805 return $wgAmericanDates ? 'mdy' : 'dmy';
806 } else {
807 return $df;
808 }
809 }
810
811 /**
812 * @return array
813 */
814 public function getDatePreferenceMigrationMap() {
815 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
816 }
817
818 /**
819 * @return array
820 */
821 public function getExtraUserToggles() {
822 wfDeprecated( __METHOD__, '1.34' );
823 return [];
824 }
825
826 /**
827 * @param string $tog
828 * @return string
829 */
830 function getUserToggle( $tog ) {
831 return $this->getMessageFromDB( "tog-$tog" );
832 }
833
834 /**
835 * Get an array of language names, indexed by code.
836 * @param null|string $inLanguage Code of language in which to return the names
837 * Use self::AS_AUTONYMS for autonyms (native names)
838 * @param string $include One of:
839 * self::ALL all available languages
840 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
841 * self::SUPPORTED only if the language is in 'mw' *and* has a message file
842 * @return array Language code => language name (sorted by key)
843 * @since 1.20
844 */
845 public static function fetchLanguageNames( $inLanguage = self::AS_AUTONYMS, $include = 'mw' ) {
846 $cacheKey = $inLanguage === self::AS_AUTONYMS ? 'null' : $inLanguage;
847 $cacheKey .= ":$include";
848 if ( self::$languageNameCache === null ) {
849 self::$languageNameCache = new HashBagOStuff( [ 'maxKeys' => 20 ] );
850 }
851
852 $ret = self::$languageNameCache->get( $cacheKey );
853 if ( !$ret ) {
854 $ret = self::fetchLanguageNamesUncached( $inLanguage, $include );
855 self::$languageNameCache->set( $cacheKey, $ret );
856 }
857 return $ret;
858 }
859
860 /**
861 * Uncached helper for fetchLanguageNames
862 * @param null|string $inLanguage Code of language in which to return the names
863 * Use self::AS_AUTONYMS for autonyms (native names)
864 * @param string $include One of:
865 * self::ALL all available languages
866 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
867 * self::SUPPORTED only if the language is in 'mw' *and* has a message file
868 * @return array Language code => language name (sorted by key)
869 */
870 private static function fetchLanguageNamesUncached(
871 $inLanguage = self::AS_AUTONYMS,
872 $include = 'mw'
873 ) {
874 global $wgExtraLanguageNames, $wgUsePigLatinVariant;
875
876 // If passed an invalid language code to use, fallback to en
877 if ( $inLanguage !== self::AS_AUTONYMS && !self::isValidCode( $inLanguage ) ) {
878 $inLanguage = 'en';
879 }
880
881 $names = [];
882
883 if ( $inLanguage ) {
884 # TODO: also include when $inLanguage is null, when this code is more efficient
885 Hooks::run( 'LanguageGetTranslatedLanguageNames', [ &$names, $inLanguage ] );
886 }
887
888 $mwNames = $wgExtraLanguageNames + MediaWiki\Languages\Data\Names::$names;
889 if ( $wgUsePigLatinVariant ) {
890 // Pig Latin (for variant development)
891 $mwNames['en-x-piglatin'] = 'Igpay Atinlay';
892 }
893
894 foreach ( $mwNames as $mwCode => $mwName ) {
895 # - Prefer own MediaWiki native name when not using the hook
896 # - For other names just add if not added through the hook
897 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
898 $names[$mwCode] = $mwName;
899 }
900 }
901
902 if ( $include === self::ALL ) {
903 ksort( $names );
904 return $names;
905 }
906
907 $returnMw = [];
908 $coreCodes = array_keys( $mwNames );
909 foreach ( $coreCodes as $coreCode ) {
910 $returnMw[$coreCode] = $names[$coreCode];
911 }
912
913 if ( $include === self::SUPPORTED ) {
914 $namesMwFile = [];
915 # We do this using a foreach over the codes instead of a directory
916 # loop so that messages files in extensions will work correctly.
917 foreach ( $returnMw as $code => $value ) {
918 if ( is_readable( self::getMessagesFileName( $code ) )
919 || is_readable( self::getJsonMessagesFileName( $code ) )
920 ) {
921 $namesMwFile[$code] = $names[$code];
922 }
923 }
924
925 ksort( $namesMwFile );
926 return $namesMwFile;
927 }
928
929 ksort( $returnMw );
930 # 'mw' option; default if it's not one of the other two options (all/mwfile)
931 return $returnMw;
932 }
933
934 /**
935 * @param string $code The code of the language for which to get the name
936 * @param null|string $inLanguage Code of language in which to return the name
937 * (SELF::AS_AUTONYMS for autonyms)
938 * @param string $include See fetchLanguageNames()
939 * @return string Language name or empty
940 * @since 1.20
941 */
942 public static function fetchLanguageName(
943 $code,
944 $inLanguage = self::AS_AUTONYMS,
945 $include = self::ALL
946 ) {
947 $code = strtolower( $code );
948 $array = self::fetchLanguageNames( $inLanguage, $include );
949 return !array_key_exists( $code, $array ) ? '' : $array[$code];
950 }
951
952 /**
953 * Get a message from the MediaWiki namespace.
954 *
955 * @param string $msg Message name
956 * @return string
957 */
958 public function getMessageFromDB( $msg ) {
959 return $this->msg( $msg )->text();
960 }
961
962 /**
963 * Get message object in this language. Only for use inside this class.
964 *
965 * @param string $msg Message name
966 * @return Message
967 */
968 protected function msg( $msg ) {
969 return wfMessage( $msg )->inLanguage( $this );
970 }
971
972 /**
973 * @param string $key
974 * @return string
975 */
976 public function getMonthName( $key ) {
977 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
978 }
979
980 /**
981 * @return array
982 */
983 public function getMonthNamesArray() {
984 $monthNames = [ '' ];
985 for ( $i = 1; $i < 13; $i++ ) {
986 $monthNames[] = $this->getMonthName( $i );
987 }
988 return $monthNames;
989 }
990
991 /**
992 * @param string $key
993 * @return string
994 */
995 public function getMonthNameGen( $key ) {
996 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
997 }
998
999 /**
1000 * @param string $key
1001 * @return string
1002 */
1003 public function getMonthAbbreviation( $key ) {
1004 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
1005 }
1006
1007 /**
1008 * @return array
1009 */
1010 public function getMonthAbbreviationsArray() {
1011 $monthNames = [ '' ];
1012 for ( $i = 1; $i < 13; $i++ ) {
1013 $monthNames[] = $this->getMonthAbbreviation( $i );
1014 }
1015 return $monthNames;
1016 }
1017
1018 /**
1019 * @param string $key
1020 * @return string
1021 */
1022 public function getWeekdayName( $key ) {
1023 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
1024 }
1025
1026 /**
1027 * @param string $key
1028 * @return string
1029 */
1030 function getWeekdayAbbreviation( $key ) {
1031 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
1032 }
1033
1034 /**
1035 * @param string $key
1036 * @return string
1037 */
1038 function getIranianCalendarMonthName( $key ) {
1039 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
1040 }
1041
1042 /**
1043 * @param string $key
1044 * @return string
1045 */
1046 function getHebrewCalendarMonthName( $key ) {
1047 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1048 }
1049
1050 /**
1051 * @param string $key
1052 * @return string
1053 */
1054 function getHebrewCalendarMonthNameGen( $key ) {
1055 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1056 }
1057
1058 /**
1059 * @param string $key
1060 * @return string
1061 */
1062 function getHijriCalendarMonthName( $key ) {
1063 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1064 }
1065
1066 /**
1067 * Pass through result from $dateTimeObj->format()
1068 * @param DateTime|bool|null &$dateTimeObj
1069 * @param string $ts
1070 * @param DateTimeZone|bool|null $zone
1071 * @param string $code
1072 * @return string
1073 */
1074 private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
1075 if ( !$dateTimeObj ) {
1076 $dateTimeObj = DateTime::createFromFormat(
1077 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1078 );
1079 }
1080 return $dateTimeObj->format( $code );
1081 }
1082
1083 /**
1084 * This is a workalike of PHP's date() function, but with better
1085 * internationalisation, a reduced set of format characters, and a better
1086 * escaping format.
1087 *
1088 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1089 * the PHP manual for definitions. There are a number of extensions, which
1090 * start with "x":
1091 *
1092 * xn Do not translate digits of the next numeric format character
1093 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1094 * xr Use roman numerals for the next numeric format character
1095 * xh Use hebrew numerals for the next numeric format character
1096 * xx Literal x
1097 * xg Genitive month name
1098 *
1099 * xij j (day number) in Iranian calendar
1100 * xiF F (month name) in Iranian calendar
1101 * xin n (month number) in Iranian calendar
1102 * xiy y (two digit year) in Iranian calendar
1103 * xiY Y (full year) in Iranian calendar
1104 * xit t (days in month) in Iranian calendar
1105 * xiz z (day of the year) in Iranian calendar
1106 *
1107 * xjj j (day number) in Hebrew calendar
1108 * xjF F (month name) in Hebrew calendar
1109 * xjt t (days in month) in Hebrew calendar
1110 * xjx xg (genitive month name) in Hebrew calendar
1111 * xjn n (month number) in Hebrew calendar
1112 * xjY Y (full year) in Hebrew calendar
1113 *
1114 * xmj j (day number) in Hijri calendar
1115 * xmF F (month name) in Hijri calendar
1116 * xmn n (month number) in Hijri calendar
1117 * xmY Y (full year) in Hijri calendar
1118 *
1119 * xkY Y (full year) in Thai solar calendar. Months and days are
1120 * identical to the Gregorian calendar
1121 * xoY Y (full year) in Minguo calendar or Juche year.
1122 * Months and days are identical to the
1123 * Gregorian calendar
1124 * xtY Y (full year) in Japanese nengo. Months and days are
1125 * identical to the Gregorian calendar
1126 *
1127 * Characters enclosed in double quotes will be considered literal (with
1128 * the quotes themselves removed). Unmatched quotes will be considered
1129 * literal quotes. Example:
1130 *
1131 * "The month is" F => The month is January
1132 * i's" => 20'11"
1133 *
1134 * Backslash escaping is also supported.
1135 *
1136 * Input timestamp is assumed to be pre-normalized to the desired local
1137 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1138 * $ts is UTC if $zone is not given.
1139 *
1140 * @param string $format
1141 * @param string $ts 14-character timestamp
1142 * YYYYMMDDHHMMSS
1143 * 01234567890123
1144 * @param DateTimeZone|null $zone Timezone of $ts
1145 * @param int &$ttl The amount of time (in seconds) the output may be cached for.
1146 * Only makes sense if $ts is the current time.
1147 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1148 *
1149 * @throws MWException
1150 * @return string
1151 */
1152 public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
1153 $s = '';
1154 $raw = false;
1155 $roman = false;
1156 $hebrewNum = false;
1157 $dateTimeObj = false;
1158 $rawToggle = false;
1159 $iranian = false;
1160 $hebrew = false;
1161 $hijri = false;
1162 $thai = false;
1163 $minguo = false;
1164 $tenno = false;
1165
1166 $usedSecond = false;
1167 $usedMinute = false;
1168 $usedHour = false;
1169 $usedAMPM = false;
1170 $usedDay = false;
1171 $usedWeek = false;
1172 $usedMonth = false;
1173 $usedYear = false;
1174 $usedISOYear = false;
1175 $usedIsLeapYear = false;
1176
1177 $usedHebrewMonth = false;
1178 $usedIranianMonth = false;
1179 $usedHijriMonth = false;
1180 $usedHebrewYear = false;
1181 $usedIranianYear = false;
1182 $usedHijriYear = false;
1183 $usedTennoYear = false;
1184
1185 if ( strlen( $ts ) !== 14 ) {
1186 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1187 }
1188
1189 if ( !ctype_digit( $ts ) ) {
1190 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1191 }
1192
1193 $formatLength = strlen( $format );
1194 for ( $p = 0; $p < $formatLength; $p++ ) {
1195 $num = false;
1196 $code = $format[$p];
1197 if ( $code == 'x' && $p < $formatLength - 1 ) {
1198 $code .= $format[++$p];
1199 }
1200
1201 if ( ( $code === 'xi'
1202 || $code === 'xj'
1203 || $code === 'xk'
1204 || $code === 'xm'
1205 || $code === 'xo'
1206 || $code === 'xt' )
1207 && $p < $formatLength - 1 ) {
1208 $code .= $format[++$p];
1209 }
1210
1211 switch ( $code ) {
1212 case 'xx':
1213 $s .= 'x';
1214 break;
1215 case 'xn':
1216 $raw = true;
1217 break;
1218 case 'xN':
1219 $rawToggle = !$rawToggle;
1220 break;
1221 case 'xr':
1222 $roman = true;
1223 break;
1224 case 'xh':
1225 $hebrewNum = true;
1226 break;
1227 case 'xg':
1228 $usedMonth = true;
1229 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1230 break;
1231 case 'xjx':
1232 $usedHebrewMonth = true;
1233 if ( !$hebrew ) {
1234 $hebrew = self::tsToHebrew( $ts );
1235 }
1236 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1237 break;
1238 case 'd':
1239 $usedDay = true;
1240 $num = substr( $ts, 6, 2 );
1241 break;
1242 case 'D':
1243 $usedDay = true;
1244 $s .= $this->getWeekdayAbbreviation(
1245 self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1246 );
1247 break;
1248 case 'j':
1249 $usedDay = true;
1250 $num = intval( substr( $ts, 6, 2 ) );
1251 break;
1252 case 'xij':
1253 $usedDay = true;
1254 if ( !$iranian ) {
1255 $iranian = self::tsToIranian( $ts );
1256 }
1257 $num = $iranian[2];
1258 break;
1259 case 'xmj':
1260 $usedDay = true;
1261 if ( !$hijri ) {
1262 $hijri = self::tsToHijri( $ts );
1263 }
1264 $num = $hijri[2];
1265 break;
1266 case 'xjj':
1267 $usedDay = true;
1268 if ( !$hebrew ) {
1269 $hebrew = self::tsToHebrew( $ts );
1270 }
1271 $num = $hebrew[2];
1272 break;
1273 case 'l':
1274 $usedDay = true;
1275 $s .= $this->getWeekdayName(
1276 self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
1277 );
1278 break;
1279 case 'F':
1280 $usedMonth = true;
1281 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1282 break;
1283 case 'xiF':
1284 $usedIranianMonth = true;
1285 if ( !$iranian ) {
1286 $iranian = self::tsToIranian( $ts );
1287 }
1288 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1289 break;
1290 case 'xmF':
1291 $usedHijriMonth = true;
1292 if ( !$hijri ) {
1293 $hijri = self::tsToHijri( $ts );
1294 }
1295 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1296 break;
1297 case 'xjF':
1298 $usedHebrewMonth = true;
1299 if ( !$hebrew ) {
1300 $hebrew = self::tsToHebrew( $ts );
1301 }
1302 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1303 break;
1304 case 'm':
1305 $usedMonth = true;
1306 $num = substr( $ts, 4, 2 );
1307 break;
1308 case 'M':
1309 $usedMonth = true;
1310 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1311 break;
1312 case 'n':
1313 $usedMonth = true;
1314 $num = intval( substr( $ts, 4, 2 ) );
1315 break;
1316 case 'xin':
1317 $usedIranianMonth = true;
1318 if ( !$iranian ) {
1319 $iranian = self::tsToIranian( $ts );
1320 }
1321 $num = $iranian[1];
1322 break;
1323 case 'xmn':
1324 $usedHijriMonth = true;
1325 if ( !$hijri ) {
1326 $hijri = self::tsToHijri( $ts );
1327 }
1328 $num = $hijri[1];
1329 break;
1330 case 'xjn':
1331 $usedHebrewMonth = true;
1332 if ( !$hebrew ) {
1333 $hebrew = self::tsToHebrew( $ts );
1334 }
1335 $num = $hebrew[1];
1336 break;
1337 case 'xjt':
1338 $usedHebrewMonth = true;
1339 if ( !$hebrew ) {
1340 $hebrew = self::tsToHebrew( $ts );
1341 }
1342 $num = $hebrew[3];
1343 break;
1344 case 'Y':
1345 $usedYear = true;
1346 $num = substr( $ts, 0, 4 );
1347 break;
1348 case 'xiY':
1349 $usedIranianYear = true;
1350 if ( !$iranian ) {
1351 $iranian = self::tsToIranian( $ts );
1352 }
1353 $num = $iranian[0];
1354 break;
1355 case 'xmY':
1356 $usedHijriYear = true;
1357 if ( !$hijri ) {
1358 $hijri = self::tsToHijri( $ts );
1359 }
1360 $num = $hijri[0];
1361 break;
1362 case 'xjY':
1363 $usedHebrewYear = true;
1364 if ( !$hebrew ) {
1365 $hebrew = self::tsToHebrew( $ts );
1366 }
1367 $num = $hebrew[0];
1368 break;
1369 case 'xkY':
1370 $usedYear = true;
1371 if ( !$thai ) {
1372 $thai = self::tsToYear( $ts, 'thai' );
1373 }
1374 $num = $thai[0];
1375 break;
1376 case 'xoY':
1377 $usedYear = true;
1378 if ( !$minguo ) {
1379 $minguo = self::tsToYear( $ts, 'minguo' );
1380 }
1381 $num = $minguo[0];
1382 break;
1383 case 'xtY':
1384 $usedTennoYear = true;
1385 if ( !$tenno ) {
1386 $tenno = self::tsToYear( $ts, 'tenno' );
1387 }
1388 $num = $tenno[0];
1389 break;
1390 case 'y':
1391 $usedYear = true;
1392 $num = substr( $ts, 2, 2 );
1393 break;
1394 case 'xiy':
1395 $usedIranianYear = true;
1396 if ( !$iranian ) {
1397 $iranian = self::tsToIranian( $ts );
1398 }
1399 $num = substr( $iranian[0], -2 );
1400 break;
1401 case 'xit':
1402 $usedIranianYear = true;
1403 if ( !$iranian ) {
1404 $iranian = self::tsToIranian( $ts );
1405 }
1406 $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
1407 break;
1408 case 'xiz':
1409 $usedIranianYear = true;
1410 if ( !$iranian ) {
1411 $iranian = self::tsToIranian( $ts );
1412 }
1413 $num = $iranian[3];
1414 break;
1415 case 'a':
1416 $usedAMPM = true;
1417 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1418 break;
1419 case 'A':
1420 $usedAMPM = true;
1421 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1422 break;
1423 case 'g':
1424 $usedHour = true;
1425 $h = substr( $ts, 8, 2 );
1426 $num = $h % 12 ?: 12;
1427 break;
1428 case 'G':
1429 $usedHour = true;
1430 $num = intval( substr( $ts, 8, 2 ) );
1431 break;
1432 case 'h':
1433 $usedHour = true;
1434 $h = substr( $ts, 8, 2 );
1435 $num = sprintf( '%02d', $h % 12 ?: 12 );
1436 break;
1437 case 'H':
1438 $usedHour = true;
1439 $num = substr( $ts, 8, 2 );
1440 break;
1441 case 'i':
1442 $usedMinute = true;
1443 $num = substr( $ts, 10, 2 );
1444 break;
1445 case 's':
1446 $usedSecond = true;
1447 $num = substr( $ts, 12, 2 );
1448 break;
1449 case 'c':
1450 case 'r':
1451 $usedSecond = true;
1452 // fall through
1453 case 'e':
1454 case 'O':
1455 case 'P':
1456 case 'T':
1457 $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1458 break;
1459 case 'w':
1460 case 'N':
1461 case 'z':
1462 $usedDay = true;
1463 $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1464 break;
1465 case 'W':
1466 $usedWeek = true;
1467 $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1468 break;
1469 case 't':
1470 $usedMonth = true;
1471 $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1472 break;
1473 case 'L':
1474 $usedIsLeapYear = true;
1475 $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1476 break;
1477 case 'o':
1478 $usedISOYear = true;
1479 $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1480 break;
1481 case 'U':
1482 $usedSecond = true;
1483 // fall through
1484 case 'I':
1485 case 'Z':
1486 $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
1487 break;
1488 case '\\':
1489 # Backslash escaping
1490 if ( $p < $formatLength - 1 ) {
1491 $s .= $format[++$p];
1492 } else {
1493 $s .= '\\';
1494 }
1495 break;
1496 case '"':
1497 # Quoted literal
1498 if ( $p < $formatLength - 1 ) {
1499 $endQuote = strpos( $format, '"', $p + 1 );
1500 if ( $endQuote === false ) {
1501 # No terminating quote, assume literal "
1502 $s .= '"';
1503 } else {
1504 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1505 $p = $endQuote;
1506 }
1507 } else {
1508 # Quote at end of string, assume literal "
1509 $s .= '"';
1510 }
1511 break;
1512 default:
1513 $s .= $format[$p];
1514 }
1515 if ( $num !== false ) {
1516 if ( $rawToggle || $raw ) {
1517 $s .= $num;
1518 $raw = false;
1519 } elseif ( $roman ) {
1520 $s .= self::romanNumeral( $num );
1521 $roman = false;
1522 } elseif ( $hebrewNum ) {
1523 $s .= self::hebrewNumeral( $num );
1524 $hebrewNum = false;
1525 } else {
1526 $s .= $this->formatNum( $num, true );
1527 }
1528 }
1529 }
1530
1531 if ( $ttl === 'unused' ) {
1532 // No need to calculate the TTL, the caller wont use it anyway.
1533 } elseif ( $usedSecond ) {
1534 $ttl = 1;
1535 } elseif ( $usedMinute ) {
1536 $ttl = 60 - substr( $ts, 12, 2 );
1537 } elseif ( $usedHour ) {
1538 $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1539 } elseif ( $usedAMPM ) {
1540 $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
1541 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1542 } elseif (
1543 $usedDay ||
1544 $usedHebrewMonth ||
1545 $usedIranianMonth ||
1546 $usedHijriMonth ||
1547 $usedHebrewYear ||
1548 $usedIranianYear ||
1549 $usedHijriYear ||
1550 $usedTennoYear
1551 ) {
1552 // @todo Someone who understands the non-Gregorian calendars
1553 // should write proper logic for them so that they don't need purged every day.
1554 $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
1555 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1556 } else {
1557 $possibleTtls = [];
1558 $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
1559 substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
1560 if ( $usedWeek ) {
1561 $possibleTtls[] =
1562 ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
1563 $timeRemainingInDay;
1564 } elseif ( $usedISOYear ) {
1565 // December 28th falls on the last ISO week of the year, every year.
1566 // The last ISO week of a year can be 52 or 53.
1567 $lastWeekOfISOYear = DateTime::createFromFormat(
1568 'Ymd',
1569 substr( $ts, 0, 4 ) . '1228',
1570 $zone ?: new DateTimeZone( 'UTC' )
1571 )->format( 'W' );
1572 $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
1573 $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
1574 $timeRemainingInWeek =
1575 ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
1576 + $timeRemainingInDay;
1577 $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
1578 }
1579
1580 if ( $usedMonth ) {
1581 $possibleTtls[] =
1582 ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
1583 substr( $ts, 6, 2 ) ) * 86400
1584 + $timeRemainingInDay;
1585 } elseif ( $usedYear ) {
1586 $possibleTtls[] =
1587 ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1588 self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1589 + $timeRemainingInDay;
1590 } elseif ( $usedIsLeapYear ) {
1591 $year = substr( $ts, 0, 4 );
1592 $timeRemainingInYear =
1593 ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
1594 self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
1595 + $timeRemainingInDay;
1596 $mod = $year % 4;
1597 if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
1598 // this isn't a leap year. see when the next one starts
1599 $nextCandidate = $year - $mod + 4;
1600 if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
1601 $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
1602 $timeRemainingInYear;
1603 } else {
1604 $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
1605 $timeRemainingInYear;
1606 }
1607 } else {
1608 // this is a leap year, so the next year isn't
1609 $possibleTtls[] = $timeRemainingInYear;
1610 }
1611 }
1612
1613 if ( $possibleTtls ) {
1614 $ttl = min( $possibleTtls );
1615 }
1616 }
1617
1618 return $s;
1619 }
1620
1621 private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
1622 private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
1623
1624 /**
1625 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1626 * Gregorian dates to Iranian dates. Originally written in C, it
1627 * is released under the terms of GNU Lesser General Public
1628 * License. Conversion to PHP was performed by Niklas Laxström.
1629 *
1630 * Link: http://www.farsiweb.info/jalali/jalali.c
1631 *
1632 * @param string $ts
1633 *
1634 * @return int[]
1635 */
1636 private static function tsToIranian( $ts ) {
1637 $gy = substr( $ts, 0, 4 ) - 1600;
1638 $gm = substr( $ts, 4, 2 ) - 1;
1639 $gd = substr( $ts, 6, 2 ) - 1;
1640
1641 # Days passed from the beginning (including leap years)
1642 $gDayNo = 365 * $gy
1643 + floor( ( $gy + 3 ) / 4 )
1644 - floor( ( $gy + 99 ) / 100 )
1645 + floor( ( $gy + 399 ) / 400 );
1646
1647 // Add days of the past months of this year
1648 for ( $i = 0; $i < $gm; $i++ ) {
1649 $gDayNo += self::$GREG_DAYS[$i];
1650 }
1651
1652 // Leap years
1653 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1654 $gDayNo++;
1655 }
1656
1657 // Days passed in current month
1658 $gDayNo += (int)$gd;
1659
1660 $jDayNo = $gDayNo - 79;
1661
1662 $jNp = floor( $jDayNo / 12053 );
1663 $jDayNo %= 12053;
1664
1665 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1666 $jDayNo %= 1461;
1667
1668 if ( $jDayNo >= 366 ) {
1669 $jy += floor( ( $jDayNo - 1 ) / 365 );
1670 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1671 }
1672
1673 $jz = $jDayNo;
1674
1675 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1676 $jDayNo -= self::$IRANIAN_DAYS[$i];
1677 }
1678
1679 $jm = $i + 1;
1680 $jd = $jDayNo + 1;
1681
1682 return [ $jy, $jm, $jd, $jz ];
1683 }
1684
1685 /**
1686 * Converting Gregorian dates to Hijri dates.
1687 *
1688 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1689 *
1690 * @see https://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1691 *
1692 * @param string $ts
1693 *
1694 * @return int[]
1695 */
1696 private static function tsToHijri( $ts ) {
1697 $year = substr( $ts, 0, 4 );
1698 $month = substr( $ts, 4, 2 );
1699 $day = substr( $ts, 6, 2 );
1700
1701 $zyr = $year;
1702 $zd = $day;
1703 $zm = $month;
1704 $zy = $zyr;
1705
1706 if (
1707 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1708 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1709 ) {
1710 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1711 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1712 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1713 $zd - 32075;
1714 } else {
1715 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1716 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1717 }
1718
1719 $zl = $zjd - 1948440 + 10632;
1720 $zn = (int)( ( $zl - 1 ) / 10631 );
1721 $zl = $zl - 10631 * $zn + 354;
1722 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
1723 ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1724 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
1725 ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1726 $zm = (int)( ( 24 * $zl ) / 709 );
1727 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1728 $zy = 30 * $zn + $zj - 30;
1729
1730 return [ $zy, $zm, $zd ];
1731 }
1732
1733 /**
1734 * Converting Gregorian dates to Hebrew dates.
1735 *
1736 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1737 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1738 * to translate the relevant functions into PHP and release them under
1739 * GNU GPL.
1740 *
1741 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1742 * and Adar II is 14. In a non-leap year, Adar is 6.
1743 *
1744 * @param string $ts
1745 *
1746 * @return int[]
1747 */
1748 private static function tsToHebrew( $ts ) {
1749 # Parse date
1750 $year = substr( $ts, 0, 4 );
1751 $month = substr( $ts, 4, 2 );
1752 $day = substr( $ts, 6, 2 );
1753
1754 # Calculate Hebrew year
1755 $hebrewYear = $year + 3760;
1756
1757 # Month number when September = 1, August = 12
1758 $month += 4;
1759 if ( $month > 12 ) {
1760 # Next year
1761 $month -= 12;
1762 $year++;
1763 $hebrewYear++;
1764 }
1765
1766 # Calculate day of year from 1 September
1767 $dayOfYear = $day;
1768 for ( $i = 1; $i < $month; $i++ ) {
1769 if ( $i == 6 ) {
1770 # February
1771 $dayOfYear += 28;
1772 # Check if the year is leap
1773 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1774 $dayOfYear++;
1775 }
1776 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1777 $dayOfYear += 30;
1778 } else {
1779 $dayOfYear += 31;
1780 }
1781 }
1782
1783 # Calculate the start of the Hebrew year
1784 $start = self::hebrewYearStart( $hebrewYear );
1785
1786 # Calculate next year's start
1787 if ( $dayOfYear <= $start ) {
1788 # Day is before the start of the year - it is the previous year
1789 # Next year's start
1790 $nextStart = $start;
1791 # Previous year
1792 $year--;
1793 $hebrewYear--;
1794 # Add days since previous year's 1 September
1795 $dayOfYear += 365;
1796 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1797 # Leap year
1798 $dayOfYear++;
1799 }
1800 # Start of the new (previous) year
1801 $start = self::hebrewYearStart( $hebrewYear );
1802 } else {
1803 # Next year's start
1804 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1805 }
1806
1807 # Calculate Hebrew day of year
1808 $hebrewDayOfYear = $dayOfYear - $start;
1809
1810 # Difference between year's days
1811 $diff = $nextStart - $start;
1812 # Add 12 (or 13 for leap years) days to ignore the difference between
1813 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1814 # difference is only about the year type
1815 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1816 $diff += 13;
1817 } else {
1818 $diff += 12;
1819 }
1820
1821 # Check the year pattern, and is leap year
1822 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1823 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1824 # and non-leap years
1825 $yearPattern = $diff % 30;
1826 # Check if leap year
1827 $isLeap = $diff >= 30;
1828
1829 # Calculate day in the month from number of day in the Hebrew year
1830 # Don't check Adar - if the day is not in Adar, we will stop before;
1831 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1832 $hebrewDay = $hebrewDayOfYear;
1833 $hebrewMonth = 1;
1834 $days = 0;
1835 while ( $hebrewMonth <= 12 ) {
1836 # Calculate days in this month
1837 if ( $isLeap && $hebrewMonth == 6 ) {
1838 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1839 $days = 30;
1840 if ( $hebrewDay <= $days ) {
1841 # Day in Adar I
1842 $hebrewMonth = 13;
1843 } else {
1844 # Subtract the days of Adar I
1845 $hebrewDay -= $days;
1846 # Try Adar II
1847 $days = 29;
1848 if ( $hebrewDay <= $days ) {
1849 # Day in Adar II
1850 $hebrewMonth = 14;
1851 }
1852 }
1853 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1854 # Cheshvan in a complete year (otherwise as the rule below)
1855 $days = 30;
1856 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1857 # Kislev in an incomplete year (otherwise as the rule below)
1858 $days = 29;
1859 } else {
1860 # Odd months have 30 days, even have 29
1861 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1862 }
1863 if ( $hebrewDay <= $days ) {
1864 # In the current month
1865 break;
1866 } else {
1867 # Subtract the days of the current month
1868 $hebrewDay -= $days;
1869 # Try in the next month
1870 $hebrewMonth++;
1871 }
1872 }
1873
1874 return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
1875 }
1876
1877 /**
1878 * This calculates the Hebrew year start, as days since 1 September.
1879 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1880 * Used for Hebrew date.
1881 *
1882 * @param int $year
1883 *
1884 * @return string
1885 */
1886 private static function hebrewYearStart( $year ) {
1887 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1888 $b = intval( ( $year - 1 ) % 4 );
1889 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1890 if ( $m < 0 ) {
1891 $m--;
1892 }
1893 $Mar = intval( $m );
1894 if ( $m < 0 ) {
1895 $m++;
1896 }
1897 $m -= $Mar;
1898
1899 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1900 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1901 $Mar++;
1902 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1903 $Mar += 2;
1904 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1905 $Mar++;
1906 }
1907
1908 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1909 return $Mar;
1910 }
1911
1912 /**
1913 * Algorithm to convert Gregorian dates to Thai solar dates,
1914 * Minguo dates or Minguo dates.
1915 *
1916 * Link: https://en.wikipedia.org/wiki/Thai_solar_calendar
1917 * https://en.wikipedia.org/wiki/Minguo_calendar
1918 * https://en.wikipedia.org/wiki/Japanese_era_name
1919 *
1920 * @param string $ts 14-character timestamp
1921 * @param string $cName Calender name
1922 * @return array Converted year, month, day
1923 */
1924 private static function tsToYear( $ts, $cName ) {
1925 $gy = substr( $ts, 0, 4 );
1926 $gm = substr( $ts, 4, 2 );
1927 $gd = substr( $ts, 6, 2 );
1928
1929 if ( !strcmp( $cName, 'thai' ) ) {
1930 # Thai solar dates
1931 # Add 543 years to the Gregorian calendar
1932 # Months and days are identical
1933 $gy_offset = $gy + 543;
1934 # fix for dates between 1912 and 1941
1935 # https://en.wikipedia.org/?oldid=836596673#New_year
1936 if ( $gy >= 1912 && $gy <= 1940 ) {
1937 if ( $gm <= 3 ) {
1938 $gy_offset--;
1939 }
1940 $gm = ( $gm - 3 ) % 12;
1941 }
1942 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1943 # Minguo dates
1944 # Deduct 1911 years from the Gregorian calendar
1945 # Months and days are identical
1946 $gy_offset = $gy - 1911;
1947 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1948 # Nengō dates up to Meiji period
1949 # Deduct years from the Gregorian calendar
1950 # depending on the nengo periods
1951 # Months and days are identical
1952 if ( ( $gy < 1912 )
1953 || ( ( $gy == 1912 ) && ( $gm < 7 ) )
1954 || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
1955 ) {
1956 # Meiji period
1957 $gy_gannen = $gy - 1868 + 1;
1958 $gy_offset = $gy_gannen;
1959 if ( $gy_gannen == 1 ) {
1960 $gy_offset = '元';
1961 }
1962 $gy_offset = '明治' . $gy_offset;
1963 } elseif (
1964 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1965 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1966 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1967 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1968 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1969 ) {
1970 # Taishō period
1971 $gy_gannen = $gy - 1912 + 1;
1972 $gy_offset = $gy_gannen;
1973 if ( $gy_gannen == 1 ) {
1974 $gy_offset = '元';
1975 }
1976 $gy_offset = '大正' . $gy_offset;
1977 } elseif (
1978 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1979 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1980 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1981 ) {
1982 # Shōwa period
1983 $gy_gannen = $gy - 1926 + 1;
1984 $gy_offset = $gy_gannen;
1985 if ( $gy_gannen == 1 ) {
1986 $gy_offset = '元';
1987 }
1988 $gy_offset = '昭和' . $gy_offset;
1989 } elseif (
1990 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd >= 8 ) ) ||
1991 ( ( $gy > 1989 ) && ( $gy < 2019 ) ) ||
1992 ( ( $gy == 2019 ) && ( $gm < 5 ) )
1993 ) {
1994 # Heisei period
1995 $gy_gannen = $gy - 1989 + 1;
1996 $gy_offset = $gy_gannen;
1997 if ( $gy_gannen == 1 ) {
1998 $gy_offset = '元';
1999 }
2000 $gy_offset = '平成' . $gy_offset;
2001 } else {
2002 # Reiwa period
2003 $gy_gannen = $gy - 2019 + 1;
2004 $gy_offset = $gy_gannen;
2005 if ( $gy_gannen == 1 ) {
2006 $gy_offset = '元';
2007 }
2008 $gy_offset = '令和' . $gy_offset;
2009 }
2010 } else {
2011 $gy_offset = $gy;
2012 }
2013
2014 return [ $gy_offset, $gm, $gd ];
2015 }
2016
2017 /**
2018 * Gets directionality of the first strongly directional codepoint, for embedBidi()
2019 *
2020 * This is the rule the BIDI algorithm uses to determine the directionality of
2021 * paragraphs ( https://www.unicode.org/reports/tr9/#The_Paragraph_Level ) and
2022 * FSI isolates ( https://www.unicode.org/reports/tr9/#Explicit_Directional_Isolates ).
2023 *
2024 * TODO: Does not handle BIDI control characters inside the text.
2025 * TODO: Does not handle unallocated characters.
2026 *
2027 * @param string $text Text to test
2028 * @return null|string Directionality ('ltr' or 'rtl') or null
2029 */
2030 private static function strongDirFromContent( $text = '' ) {
2031 if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
2032 return null;
2033 }
2034 if ( $matches[1] === '' ) {
2035 return 'rtl';
2036 }
2037 return 'ltr';
2038 }
2039
2040 /**
2041 * Roman number formatting up to 10000
2042 *
2043 * @param int $num
2044 *
2045 * @return string
2046 */
2047 static function romanNumeral( $num ) {
2048 static $table = [
2049 [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
2050 [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
2051 [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
2052 [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
2053 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
2054 ];
2055
2056 $num = intval( $num );
2057 if ( $num > 10000 || $num <= 0 ) {
2058 return $num;
2059 }
2060
2061 $s = '';
2062 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2063 if ( $num >= $pow10 ) {
2064 $s .= $table[$i][(int)floor( $num / $pow10 )];
2065 }
2066 $num = $num % $pow10;
2067 }
2068 return $s;
2069 }
2070
2071 /**
2072 * Hebrew Gematria number formatting up to 9999
2073 *
2074 * @param int $num
2075 *
2076 * @return string
2077 */
2078 static function hebrewNumeral( $num ) {
2079 static $table = [
2080 [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
2081 [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
2082 [ '',
2083 [ 'ק' ],
2084 [ 'ר' ],
2085 [ 'ש' ],
2086 [ 'ת' ],
2087 [ 'ת', 'ק' ],
2088 [ 'ת', 'ר' ],
2089 [ 'ת', 'ש' ],
2090 [ 'ת', 'ת' ],
2091 [ 'ת', 'ת', 'ק' ],
2092 [ 'ת', 'ת', 'ר' ],
2093 ],
2094 [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
2095 ];
2096
2097 $num = intval( $num );
2098 if ( $num > 9999 || $num <= 0 ) {
2099 return $num;
2100 }
2101
2102 // Round thousands have special notations
2103 if ( $num === 1000 ) {
2104 return "א' אלף";
2105 } elseif ( $num % 1000 === 0 ) {
2106 return $table[0][$num / 1000] . "' אלפים";
2107 }
2108
2109 $letters = [];
2110
2111 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
2112 if ( $num >= $pow10 ) {
2113 if ( $num === 15 || $num === 16 ) {
2114 $letters[] = $table[0][9];
2115 $letters[] = $table[0][$num - 9];
2116 $num = 0;
2117 } else {
2118 $letters = array_merge(
2119 $letters,
2120 (array)$table[$i][intval( $num / $pow10 )]
2121 );
2122
2123 if ( $pow10 === 1000 ) {
2124 $letters[] = "'";
2125 }
2126 }
2127 }
2128
2129 $num = $num % $pow10;
2130 }
2131
2132 $preTransformLength = count( $letters );
2133 if ( $preTransformLength === 1 ) {
2134 // Add geresh (single quote) to one-letter numbers
2135 $letters[] = "'";
2136 } else {
2137 $lastIndex = $preTransformLength - 1;
2138 $letters[$lastIndex] = str_replace(
2139 [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
2140 [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
2141 $letters[$lastIndex]
2142 );
2143
2144 // Add gershayim (double quote) to multiple-letter numbers,
2145 // but exclude numbers with only one letter after the thousands
2146 // (1001-1009, 1020, 1030, 2001-2009, etc.)
2147 if ( $letters[1] === "'" && $preTransformLength === 3 ) {
2148 $letters[] = "'";
2149 } else {
2150 array_splice( $letters, -1, 0, '"' );
2151 }
2152 }
2153
2154 return implode( $letters );
2155 }
2156
2157 /**
2158 * Used by date() and time() to adjust the time output.
2159 *
2160 * @param string $ts The time in date('YmdHis') format
2161 * @param mixed $tz Adjust the time by this amount (default false, mean we
2162 * get user timecorrection setting)
2163 * @return int
2164 */
2165 public function userAdjust( $ts, $tz = false ) {
2166 global $wgUser, $wgLocalTZoffset;
2167
2168 if ( $tz === false ) {
2169 $tz = $wgUser->getOption( 'timecorrection' );
2170 }
2171
2172 $data = explode( '|', $tz, 3 );
2173
2174 if ( $data[0] == 'ZoneInfo' ) {
2175 try {
2176 $userTZ = new DateTimeZone( $data[2] );
2177 $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
2178 $date->setTimezone( $userTZ );
2179 return $date->format( 'YmdHis' );
2180 } catch ( Exception $e ) {
2181 // Unrecognized timezone, default to 'Offset' with the stored offset.
2182 $data[0] = 'Offset';
2183 }
2184 }
2185
2186 if ( $data[0] == 'System' || $tz == '' ) {
2187 # Global offset in minutes.
2188 $minDiff = $wgLocalTZoffset;
2189 } elseif ( $data[0] == 'Offset' ) {
2190 $minDiff = intval( $data[1] );
2191 } else {
2192 $data = explode( ':', $tz );
2193 if ( count( $data ) == 2 ) {
2194 $data[0] = intval( $data[0] );
2195 $data[1] = intval( $data[1] );
2196 $minDiff = abs( $data[0] ) * 60 + $data[1];
2197 if ( $data[0] < 0 ) {
2198 $minDiff = -$minDiff;
2199 }
2200 } else {
2201 $minDiff = intval( $data[0] ) * 60;
2202 }
2203 }
2204
2205 # No difference ? Return time unchanged
2206 if ( $minDiff == 0 ) {
2207 return $ts;
2208 }
2209
2210 Wikimedia\suppressWarnings(); // E_STRICT system time bitching
2211 # Generate an adjusted date; take advantage of the fact that mktime
2212 # will normalize out-of-range values so we don't have to split $minDiff
2213 # into hours and minutes.
2214 $t = mktime( (
2215 (int)substr( $ts, 8, 2 ) ), # Hours
2216 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
2217 (int)substr( $ts, 12, 2 ), # Seconds
2218 (int)substr( $ts, 4, 2 ), # Month
2219 (int)substr( $ts, 6, 2 ), # Day
2220 (int)substr( $ts, 0, 4 ) ); # Year
2221
2222 $date = date( 'YmdHis', $t );
2223 Wikimedia\restoreWarnings();
2224
2225 return $date;
2226 }
2227
2228 /**
2229 * This is meant to be used by time(), date(), and timeanddate() to get
2230 * the date preference they're supposed to use, it should be used in
2231 * all children.
2232 *
2233 * function timeanddate([...], $format = true) {
2234 * $datePreference = $this->dateFormat($format);
2235 * [...]
2236 * }
2237 *
2238 * @param int|string|bool $usePrefs If true, the user's preference is used
2239 * if false, the site/language default is used
2240 * if int/string, assumed to be a format.
2241 * @return string
2242 */
2243 function dateFormat( $usePrefs = true ) {
2244 global $wgUser;
2245
2246 if ( is_bool( $usePrefs ) ) {
2247 if ( $usePrefs ) {
2248 $datePreference = $wgUser->getDatePreference();
2249 } else {
2250 $datePreference = (string)User::getDefaultOption( 'date' );
2251 }
2252 } else {
2253 $datePreference = (string)$usePrefs;
2254 }
2255
2256 // return int
2257 if ( $datePreference == '' ) {
2258 return 'default';
2259 }
2260
2261 return $datePreference;
2262 }
2263
2264 /**
2265 * Get a format string for a given type and preference
2266 * @param string $type May be 'date', 'time', 'both', or 'pretty'.
2267 * @param string $pref The format name as it appears in Messages*.php under
2268 * $datePreferences.
2269 *
2270 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
2271 *
2272 * @return string
2273 */
2274 function getDateFormatString( $type, $pref ) {
2275 $wasDefault = false;
2276 if ( $pref == 'default' ) {
2277 $wasDefault = true;
2278 $pref = $this->getDefaultDateFormat();
2279 }
2280
2281 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2282 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2283
2284 if ( $type === 'pretty' && $df === null ) {
2285 $df = $this->getDateFormatString( 'date', $pref );
2286 }
2287
2288 if ( !$wasDefault && $df === null ) {
2289 $pref = $this->getDefaultDateFormat();
2290 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2291 }
2292
2293 $this->dateFormatStrings[$type][$pref] = $df;
2294 }
2295 return $this->dateFormatStrings[$type][$pref];
2296 }
2297
2298 /**
2299 * @param string $ts The time format which needs to be turned into a
2300 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2301 * @param bool $adj Whether to adjust the time output according to the
2302 * user configured offset ($timecorrection)
2303 * @param mixed $format True to use user's date format preference
2304 * @param string|bool $timecorrection The time offset as returned by
2305 * validateTimeZone() in Special:Preferences
2306 * @return string
2307 */
2308 public function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2309 $ts = wfTimestamp( TS_MW, $ts );
2310 if ( $adj ) {
2311 $ts = $this->userAdjust( $ts, $timecorrection );
2312 }
2313 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2314 return $this->sprintfDate( $df, $ts );
2315 }
2316
2317 /**
2318 * @param string $ts The time format which needs to be turned into a
2319 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2320 * @param bool $adj Whether to adjust the time output according to the
2321 * user configured offset ($timecorrection)
2322 * @param mixed $format True to use user's date format preference
2323 * @param string|bool $timecorrection The time offset as returned by
2324 * validateTimeZone() in Special:Preferences
2325 * @return string
2326 */
2327 public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2328 $ts = wfTimestamp( TS_MW, $ts );
2329 if ( $adj ) {
2330 $ts = $this->userAdjust( $ts, $timecorrection );
2331 }
2332 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2333 return $this->sprintfDate( $df, $ts );
2334 }
2335
2336 /**
2337 * @param string $ts The time format which needs to be turned into a
2338 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2339 * @param bool $adj Whether to adjust the time output according to the
2340 * user configured offset ($timecorrection)
2341 * @param mixed $format What format to return, if it's false output the
2342 * default one (default true)
2343 * @param string|bool $timecorrection The time offset as returned by
2344 * validateTimeZone() in Special:Preferences
2345 * @return string
2346 */
2347 public function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2348 $ts = wfTimestamp( TS_MW, $ts );
2349 if ( $adj ) {
2350 $ts = $this->userAdjust( $ts, $timecorrection );
2351 }
2352 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2353 return $this->sprintfDate( $df, $ts );
2354 }
2355
2356 /**
2357 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2358 *
2359 * @since 1.20
2360 *
2361 * @param int $seconds The amount of seconds.
2362 * @param array $chosenIntervals The intervals to enable.
2363 *
2364 * @return string
2365 */
2366 public function formatDuration( $seconds, array $chosenIntervals = [] ) {
2367 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2368
2369 $segments = [];
2370
2371 foreach ( $intervals as $intervalName => $intervalValue ) {
2372 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2373 // duration-years, duration-decades, duration-centuries, duration-millennia
2374 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2375 $segments[] = $message->inLanguage( $this )->escaped();
2376 }
2377
2378 return $this->listToText( $segments );
2379 }
2380
2381 /**
2382 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2383 * For example 65 will be turned into [ minutes => 1, seconds => 5 ].
2384 *
2385 * @since 1.20
2386 *
2387 * @param int $seconds The amount of seconds.
2388 * @param array $chosenIntervals The intervals to enable.
2389 *
2390 * @return array
2391 */
2392 public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
2393 if ( empty( $chosenIntervals ) ) {
2394 $chosenIntervals = [
2395 'millennia',
2396 'centuries',
2397 'decades',
2398 'years',
2399 'days',
2400 'hours',
2401 'minutes',
2402 'seconds'
2403 ];
2404 }
2405
2406 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2407 $sortedNames = array_keys( $intervals );
2408 $smallestInterval = array_pop( $sortedNames );
2409
2410 $segments = [];
2411
2412 foreach ( $intervals as $name => $length ) {
2413 $value = floor( $seconds / $length );
2414
2415 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2416 $seconds -= $value * $length;
2417 $segments[$name] = $value;
2418 }
2419 }
2420
2421 return $segments;
2422 }
2423
2424 /**
2425 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2426 *
2427 * @param string $type Can be 'date', 'time' or 'both'
2428 * @param string $ts The time format which needs to be turned into a
2429 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2430 * @param User $user User object used to get preferences for timezone and format
2431 * @param array $options Array, can contain the following keys:
2432 * - 'timecorrection': time correction, can have the following values:
2433 * - true: use user's preference
2434 * - false: don't use time correction
2435 * - int: value of time correction in minutes
2436 * - 'format': format to use, can have the following values:
2437 * - true: use user's preference
2438 * - false: use default preference
2439 * - string: format to use
2440 * @since 1.19
2441 * @return string
2442 */
2443 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2444 $ts = wfTimestamp( TS_MW, $ts );
2445 $options += [ 'timecorrection' => true, 'format' => true ];
2446 if ( $options['timecorrection'] !== false ) {
2447 if ( $options['timecorrection'] === true ) {
2448 $offset = $user->getOption( 'timecorrection' );
2449 } else {
2450 $offset = $options['timecorrection'];
2451 }
2452 $ts = $this->userAdjust( $ts, $offset );
2453 }
2454 if ( $options['format'] === true ) {
2455 $format = $user->getDatePreference();
2456 } else {
2457 $format = $options['format'];
2458 }
2459 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2460 return $this->sprintfDate( $df, $ts );
2461 }
2462
2463 /**
2464 * Get the formatted date for the given timestamp and formatted for
2465 * the given user.
2466 *
2467 * @param mixed $ts Mixed: the time format which needs to be turned into a
2468 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2469 * @param User $user User object used to get preferences for timezone and format
2470 * @param array $options Array, can contain the following keys:
2471 * - 'timecorrection': time correction, can have the following values:
2472 * - true: use user's preference
2473 * - false: don't use time correction
2474 * - int: value of time correction in minutes
2475 * - 'format': format to use, can have the following values:
2476 * - true: use user's preference
2477 * - false: use default preference
2478 * - string: format to use
2479 * @since 1.19
2480 * @return string
2481 */
2482 public function userDate( $ts, User $user, array $options = [] ) {
2483 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2484 }
2485
2486 /**
2487 * Get the formatted time for the given timestamp and formatted for
2488 * the given user.
2489 *
2490 * @param mixed $ts The time format which needs to be turned into a
2491 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2492 * @param User $user User object used to get preferences for timezone and format
2493 * @param array $options Array, can contain the following keys:
2494 * - 'timecorrection': time correction, can have the following values:
2495 * - true: use user's preference
2496 * - false: don't use time correction
2497 * - int: value of time correction in minutes
2498 * - 'format': format to use, can have the following values:
2499 * - true: use user's preference
2500 * - false: use default preference
2501 * - string: format to use
2502 * @since 1.19
2503 * @return string
2504 */
2505 public function userTime( $ts, User $user, array $options = [] ) {
2506 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2507 }
2508
2509 /**
2510 * Get the formatted date and time for the given timestamp and formatted for
2511 * the given user.
2512 *
2513 * @param mixed $ts The time format which needs to be turned into a
2514 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2515 * @param User $user User object used to get preferences for timezone and format
2516 * @param array $options Array, can contain the following keys:
2517 * - 'timecorrection': time correction, can have the following values:
2518 * - true: use user's preference
2519 * - false: don't use time correction
2520 * - int: value of time correction in minutes
2521 * - 'format': format to use, can have the following values:
2522 * - true: use user's preference
2523 * - false: use default preference
2524 * - string: format to use
2525 * @since 1.19
2526 * @return string
2527 */
2528 public function userTimeAndDate( $ts, User $user, array $options = [] ) {
2529 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2530 }
2531
2532 /**
2533 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
2534 *
2535 * Determine the difference between the timestamp and the current time, and
2536 * generate a readable timestamp by returning "<N> <units> ago", where the
2537 * largest possible unit is used.
2538 *
2539 * @since 1.26 (Prior to 1.26 method existed but was not meant to be used directly)
2540 *
2541 * @param MWTimestamp $time
2542 * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
2543 * @param User|null $user User the timestamp is being generated for
2544 * (or null to use main context's user)
2545 * @return string Formatted timestamp
2546 */
2547 public function getHumanTimestamp(
2548 MWTimestamp $time, MWTimestamp $relativeTo = null, User $user = null
2549 ) {
2550 if ( $relativeTo === null ) {
2551 $relativeTo = new MWTimestamp();
2552 }
2553 if ( $user === null ) {
2554 $user = RequestContext::getMain()->getUser();
2555 }
2556
2557 // Adjust for the user's timezone.
2558 $offsetThis = $time->offsetForUser( $user );
2559 $offsetRel = $relativeTo->offsetForUser( $user );
2560
2561 $ts = '';
2562 if ( Hooks::run( 'GetHumanTimestamp', [ &$ts, $time, $relativeTo, $user, $this ] ) ) {
2563 $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
2564 }
2565
2566 // Reset the timezone on the objects.
2567 $time->timestamp->sub( $offsetThis );
2568 $relativeTo->timestamp->sub( $offsetRel );
2569
2570 return $ts;
2571 }
2572
2573 /**
2574 * Convert an MWTimestamp into a pretty human-readable timestamp using
2575 * the given user preferences and relative base time.
2576 *
2577 * @see Language::getHumanTimestamp
2578 * @param MWTimestamp $ts Timestamp to prettify
2579 * @param MWTimestamp $relativeTo Base timestamp
2580 * @param User $user User preferences to use
2581 * @return string Human timestamp
2582 * @since 1.26
2583 */
2584 private function getHumanTimestampInternal(
2585 MWTimestamp $ts, MWTimestamp $relativeTo, User $user
2586 ) {
2587 $diff = $ts->diff( $relativeTo );
2588 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2589 (int)$relativeTo->timestamp->format( 'w' ) );
2590 $days = $diff->days ?: (int)$diffDay;
2591 if ( $diff->invert || $days > 5
2592 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2593 ) {
2594 // Timestamps are in different years: use full timestamp
2595 // Also do full timestamp for future dates
2596 /**
2597 * @todo FIXME: Add better handling of future timestamps.
2598 */
2599 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2600 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2601 } elseif ( $days > 5 ) {
2602 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2603 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2604 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2605 } elseif ( $days > 1 ) {
2606 // Timestamp within the past week: show the day of the week and time
2607 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2608 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2609 // Messages:
2610 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2611 $ts = wfMessage( "$weekday-at" )
2612 ->inLanguage( $this )
2613 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2614 ->text();
2615 } elseif ( $days == 1 ) {
2616 // Timestamp was yesterday: say 'yesterday' and the time.
2617 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2618 $ts = wfMessage( 'yesterday-at' )
2619 ->inLanguage( $this )
2620 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2621 ->text();
2622 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2623 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2624 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2625 $ts = wfMessage( 'today-at' )
2626 ->inLanguage( $this )
2627 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2628 ->text();
2629
2630 // From here on in, the timestamp was soon enough ago so that we can simply say
2631 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2632 } elseif ( $diff->h == 1 ) {
2633 // Less than 90 minutes, but more than an hour ago.
2634 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2635 } elseif ( $diff->i >= 1 ) {
2636 // A few minutes ago.
2637 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2638 } elseif ( $diff->s >= 30 ) {
2639 // Less than a minute, but more than 30 sec ago.
2640 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2641 } else {
2642 // Less than 30 seconds ago.
2643 $ts = wfMessage( 'just-now' )->text();
2644 }
2645
2646 return $ts;
2647 }
2648
2649 /**
2650 * @param string $key
2651 * @return string|null
2652 */
2653 public function getMessage( $key ) {
2654 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2655 }
2656
2657 /**
2658 * @return array
2659 */
2660 function getAllMessages() {
2661 return self::$dataCache->getItem( $this->mCode, 'messages' );
2662 }
2663
2664 /**
2665 * @param string $in
2666 * @param string $out
2667 * @param string $string
2668 * @return string
2669 */
2670 public function iconv( $in, $out, $string ) {
2671 # Even with //IGNORE iconv can whine about illegal characters in
2672 # *input* string. We just ignore those too.
2673 # REF: https://bugs.php.net/bug.php?id=37166
2674 # REF: https://phabricator.wikimedia.org/T18885
2675 Wikimedia\suppressWarnings();
2676 $text = iconv( $in, $out . '//IGNORE', $string );
2677 Wikimedia\restoreWarnings();
2678 return $text;
2679 }
2680
2681 // callback functions for ucwords(), ucwordbreaks()
2682
2683 /**
2684 * @param array $matches
2685 * @return mixed|string
2686 */
2687 function ucwordbreaksCallbackAscii( $matches ) {
2688 return $this->ucfirst( $matches[1] );
2689 }
2690
2691 /**
2692 * @param array $matches
2693 * @return string
2694 */
2695 function ucwordbreaksCallbackMB( $matches ) {
2696 return mb_strtoupper( $matches[0] );
2697 }
2698
2699 /**
2700 * @param array $matches
2701 * @return string
2702 */
2703 function ucwordsCallbackMB( $matches ) {
2704 return mb_strtoupper( $matches[0] );
2705 }
2706
2707 /**
2708 * Make a string's first character uppercase
2709 *
2710 * @param string $str
2711 *
2712 * @return string
2713 */
2714 public function ucfirst( $str ) {
2715 $o = ord( $str );
2716 if ( $o < 96 ) { // if already uppercase...
2717 return $str;
2718 } elseif ( $o < 128 ) {
2719 return ucfirst( $str ); // use PHP's ucfirst()
2720 } else {
2721 // fall back to more complex logic in case of multibyte strings
2722 return $this->uc( $str, true );
2723 }
2724 }
2725
2726 /**
2727 * Convert a string to uppercase
2728 *
2729 * @param string $str
2730 * @param bool $first
2731 *
2732 * @return string
2733 */
2734 public function uc( $str, $first = false ) {
2735 if ( $first ) {
2736 if ( $this->isMultibyte( $str ) ) {
2737 return $this->mbUpperChar( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2738 } else {
2739 return ucfirst( $str );
2740 }
2741 } else {
2742 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2743 }
2744 }
2745
2746 /**
2747 * Convert character to uppercase, allowing overrides of the default mb_upper
2748 * behaviour, which is buggy in many ways. Having a conversion table can be
2749 * useful during transitions between PHP versions where unicode changes happen.
2750 * This can make some resources unreachable on-wiki, see discussion at T219279.
2751 * Providing such a conversion table can allow to manage the transition period.
2752 *
2753 * @since 1.34
2754 *
2755 * @param string $char
2756 *
2757 * @return string
2758 */
2759 protected function mbUpperChar( $char ) {
2760 global $wgOverrideUcfirstCharacters;
2761 if ( array_key_exists( $char, $wgOverrideUcfirstCharacters ) ) {
2762 return $wgOverrideUcfirstCharacters[$char];
2763 } else {
2764 return mb_strtoupper( $char );
2765 }
2766 }
2767
2768 /**
2769 * @param string $str
2770 * @return mixed|string
2771 */
2772 function lcfirst( $str ) {
2773 $o = ord( $str );
2774 if ( !$o ) {
2775 return strval( $str );
2776 } elseif ( $o >= 128 ) {
2777 return $this->lc( $str, true );
2778 } elseif ( $o > 96 ) {
2779 return $str;
2780 } else {
2781 $str[0] = strtolower( $str[0] );
2782 return $str;
2783 }
2784 }
2785
2786 /**
2787 * @param string $str
2788 * @param bool $first
2789 * @return mixed|string
2790 */
2791 function lc( $str, $first = false ) {
2792 if ( $first ) {
2793 if ( $this->isMultibyte( $str ) ) {
2794 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2795 } else {
2796 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2797 }
2798 } else {
2799 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2800 }
2801 }
2802
2803 /**
2804 * @param string $str
2805 * @return bool
2806 */
2807 function isMultibyte( $str ) {
2808 return strlen( $str ) !== mb_strlen( $str );
2809 }
2810
2811 /**
2812 * @param string $str
2813 * @return mixed|string
2814 */
2815 function ucwords( $str ) {
2816 if ( $this->isMultibyte( $str ) ) {
2817 $str = $this->lc( $str );
2818
2819 // regexp to find first letter in each word (i.e. after each space)
2820 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2821
2822 // function to use to capitalize a single char
2823 return preg_replace_callback(
2824 $replaceRegexp,
2825 [ $this, 'ucwordsCallbackMB' ],
2826 $str
2827 );
2828 } else {
2829 return ucwords( strtolower( $str ) );
2830 }
2831 }
2832
2833 /**
2834 * capitalize words at word breaks
2835 *
2836 * @param string $str
2837 * @return mixed
2838 */
2839 function ucwordbreaks( $str ) {
2840 if ( $this->isMultibyte( $str ) ) {
2841 $str = $this->lc( $str );
2842
2843 // since \b doesn't work for UTF-8, we explicitely define word break chars
2844 $breaks = "[ \-\(\)\}\{\.,\?!]";
2845
2846 // find first letter after word break
2847 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2848 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2849
2850 return preg_replace_callback(
2851 $replaceRegexp,
2852 [ $this, 'ucwordbreaksCallbackMB' ],
2853 $str
2854 );
2855 } else {
2856 return preg_replace_callback(
2857 '/\b([\w\x80-\xff]+)\b/',
2858 [ $this, 'ucwordbreaksCallbackAscii' ],
2859 $str
2860 );
2861 }
2862 }
2863
2864 /**
2865 * Return a case-folded representation of $s
2866 *
2867 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2868 * and $s2 are the same except for the case of their characters. It is not
2869 * necessary for the value returned to make sense when displayed.
2870 *
2871 * Do *not* perform any other normalisation in this function. If a caller
2872 * uses this function when it should be using a more general normalisation
2873 * function, then fix the caller.
2874 *
2875 * @param string $s
2876 *
2877 * @return string
2878 */
2879 function caseFold( $s ) {
2880 return $this->uc( $s );
2881 }
2882
2883 /**
2884 * TODO: $s is not always a string per T218883
2885 * @param string $s
2886 * @return string
2887 */
2888 function checkTitleEncoding( $s ) {
2889 if ( is_array( $s ) ) {
2890 throw new MWException( 'Given array to checkTitleEncoding.' );
2891 }
2892 if ( StringUtils::isUtf8( $s ) ) {
2893 return $s;
2894 }
2895
2896 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2897 }
2898
2899 /**
2900 * @return string
2901 */
2902 function fallback8bitEncoding() {
2903 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2904 }
2905
2906 /**
2907 * Most writing systems use whitespace to break up words.
2908 * Some languages such as Chinese don't conventionally do this,
2909 * which requires special handling when breaking up words for
2910 * searching etc.
2911 *
2912 * @return bool
2913 */
2914 function hasWordBreaks() {
2915 return true;
2916 }
2917
2918 /**
2919 * Some languages such as Chinese require word segmentation,
2920 * Specify such segmentation when overridden in derived class.
2921 *
2922 * @param string $string
2923 * @return string
2924 */
2925 function segmentByWord( $string ) {
2926 return $string;
2927 }
2928
2929 /**
2930 * Some languages have special punctuation need to be normalized.
2931 * Make such changes here.
2932 *
2933 * @param string $string
2934 * @return string
2935 */
2936 function normalizeForSearch( $string ) {
2937 return self::convertDoubleWidth( $string );
2938 }
2939
2940 /**
2941 * convert double-width roman characters to single-width.
2942 * range: ff00-ff5f ~= 0020-007f
2943 *
2944 * @param string $string
2945 *
2946 * @return string
2947 */
2948 protected static function convertDoubleWidth( $string ) {
2949 static $full = null;
2950 static $half = null;
2951
2952 if ( $full === null ) {
2953 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2954 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2955 $full = str_split( $fullWidth, 3 );
2956 $half = str_split( $halfWidth );
2957 }
2958
2959 $string = str_replace( $full, $half, $string );
2960 return $string;
2961 }
2962
2963 /**
2964 * @param string $string
2965 * @param string $pattern
2966 * @return string
2967 */
2968 protected static function insertSpace( $string, $pattern ) {
2969 $string = preg_replace( $pattern, " $1 ", $string );
2970 $string = preg_replace( '/ +/', ' ', $string );
2971 return $string;
2972 }
2973
2974 /**
2975 * @param string[] $termsArray
2976 * @return string[]
2977 */
2978 function convertForSearchResult( $termsArray ) {
2979 # some languages, e.g. Chinese, need to do a conversion
2980 # in order for search results to be displayed correctly
2981 return $termsArray;
2982 }
2983
2984 /**
2985 * Get the first character of a string.
2986 *
2987 * @param string $s
2988 * @return string
2989 */
2990 function firstChar( $s ) {
2991 $matches = [];
2992 preg_match(
2993 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2994 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2995 $s,
2996 $matches
2997 );
2998
2999 if ( isset( $matches[1] ) ) {
3000 if ( strlen( $matches[1] ) != 3 ) {
3001 return $matches[1];
3002 }
3003
3004 // Break down Hangul syllables to grab the first jamo
3005 $code = UtfNormal\Utils::utf8ToCodepoint( $matches[1] );
3006 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
3007 return $matches[1];
3008 } elseif ( $code < 0xb098 ) {
3009 return "\u{3131}";
3010 } elseif ( $code < 0xb2e4 ) {
3011 return "\u{3134}";
3012 } elseif ( $code < 0xb77c ) {
3013 return "\u{3137}";
3014 } elseif ( $code < 0xb9c8 ) {
3015 return "\u{3139}";
3016 } elseif ( $code < 0xbc14 ) {
3017 return "\u{3141}";
3018 } elseif ( $code < 0xc0ac ) {
3019 return "\u{3142}";
3020 } elseif ( $code < 0xc544 ) {
3021 return "\u{3145}";
3022 } elseif ( $code < 0xc790 ) {
3023 return "\u{3147}";
3024 } elseif ( $code < 0xcc28 ) {
3025 return "\u{3148}";
3026 } elseif ( $code < 0xce74 ) {
3027 return "\u{314A}";
3028 } elseif ( $code < 0xd0c0 ) {
3029 return "\u{314B}";
3030 } elseif ( $code < 0xd30c ) {
3031 return "\u{314C}";
3032 } elseif ( $code < 0xd558 ) {
3033 return "\u{314D}";
3034 } else {
3035 return "\u{314E}";
3036 }
3037 } else {
3038 return '';
3039 }
3040 }
3041
3042 /**
3043 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
3044 * also cleans up certain backwards-compatible sequences, converting them
3045 * to the modern Unicode equivalent.
3046 *
3047 * This is language-specific for performance reasons only.
3048 *
3049 * @param string $s
3050 *
3051 * @return string
3052 */
3053 public function normalize( $s ) {
3054 global $wgAllUnicodeFixes;
3055 $s = UtfNormal\Validator::cleanUp( $s );
3056 if ( $wgAllUnicodeFixes ) {
3057 $s = $this->transformUsingPairFile( 'normalize-ar.php', $s );
3058 $s = $this->transformUsingPairFile( 'normalize-ml.php', $s );
3059 }
3060
3061 return $s;
3062 }
3063
3064 /**
3065 * Transform a string using serialized data stored in the given file (which
3066 * must be in the serialized subdirectory of $IP). The file contains pairs
3067 * mapping source characters to destination characters.
3068 *
3069 * The data is cached in process memory. This will go faster if you have the
3070 * FastStringSearch extension.
3071 *
3072 * @param string $file
3073 * @param string $string
3074 *
3075 * @throws MWException
3076 * @return string
3077 */
3078 protected function transformUsingPairFile( $file, $string ) {
3079 if ( !isset( $this->transformData[$file] ) ) {
3080 global $IP;
3081 $data = require "$IP/languages/data/{$file}";
3082 $this->transformData[$file] = new ReplacementArray( $data );
3083 }
3084 return $this->transformData[$file]->replace( $string );
3085 }
3086
3087 /**
3088 * For right-to-left language support
3089 *
3090 * @return bool
3091 */
3092 function isRTL() {
3093 return self::$dataCache->getItem( $this->mCode, 'rtl' );
3094 }
3095
3096 /**
3097 * Return the correct HTML 'dir' attribute value for this language.
3098 * @return string
3099 */
3100 function getDir() {
3101 return $this->isRTL() ? 'rtl' : 'ltr';
3102 }
3103
3104 /**
3105 * Return 'left' or 'right' as appropriate alignment for line-start
3106 * for this language's text direction.
3107 *
3108 * Should be equivalent to CSS3 'start' text-align value....
3109 *
3110 * @return string
3111 */
3112 function alignStart() {
3113 return $this->isRTL() ? 'right' : 'left';
3114 }
3115
3116 /**
3117 * Return 'right' or 'left' as appropriate alignment for line-end
3118 * for this language's text direction.
3119 *
3120 * Should be equivalent to CSS3 'end' text-align value....
3121 *
3122 * @return string
3123 */
3124 function alignEnd() {
3125 return $this->isRTL() ? 'left' : 'right';
3126 }
3127
3128 /**
3129 * A hidden direction mark (LRM or RLM), depending on the language direction.
3130 * Unlike getDirMark(), this function returns the character as an HTML entity.
3131 * This function should be used when the output is guaranteed to be HTML,
3132 * because it makes the output HTML source code more readable. When
3133 * the output is plain text or can be escaped, getDirMark() should be used.
3134 *
3135 * @param bool $opposite Get the direction mark opposite to your language
3136 * @return string
3137 * @since 1.20
3138 */
3139 function getDirMarkEntity( $opposite = false ) {
3140 if ( $opposite ) {
3141 return $this->isRTL() ? '&lrm;' : '&rlm;';
3142 }
3143 return $this->isRTL() ? '&rlm;' : '&lrm;';
3144 }
3145
3146 /**
3147 * A hidden direction mark (LRM or RLM), depending on the language direction.
3148 * This function produces them as invisible Unicode characters and
3149 * the output may be hard to read and debug, so it should only be used
3150 * when the output is plain text or can be escaped. When the output is
3151 * HTML, use getDirMarkEntity() instead.
3152 *
3153 * @param bool $opposite Get the direction mark opposite to your language
3154 * @return string
3155 */
3156 function getDirMark( $opposite = false ) {
3157 $lrm = "\u{200E}"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
3158 $rlm = "\u{200F}"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
3159 if ( $opposite ) {
3160 return $this->isRTL() ? $lrm : $rlm;
3161 }
3162 return $this->isRTL() ? $rlm : $lrm;
3163 }
3164
3165 /**
3166 * @return array
3167 */
3168 function capitalizeAllNouns() {
3169 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
3170 }
3171
3172 /**
3173 * An arrow, depending on the language direction.
3174 *
3175 * @param string $direction The direction of the arrow: forwards (default),
3176 * backwards, left, right, up, down.
3177 * @return string
3178 */
3179 function getArrow( $direction = 'forwards' ) {
3180 switch ( $direction ) {
3181 case 'forwards':
3182 return $this->isRTL() ? '←' : '→';
3183 case 'backwards':
3184 return $this->isRTL() ? '→' : '←';
3185 case 'left':
3186 return '←';
3187 case 'right':
3188 return '→';
3189 case 'up':
3190 return '↑';
3191 case 'down':
3192 return '↓';
3193 }
3194 }
3195
3196 /**
3197 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
3198 *
3199 * @return bool
3200 */
3201 function linkPrefixExtension() {
3202 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
3203 }
3204
3205 /**
3206 * Get all magic words from cache.
3207 * @return array
3208 */
3209 function getMagicWords() {
3210 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
3211 }
3212
3213 /**
3214 * Fill a MagicWord object with data from here
3215 *
3216 * @param MagicWord $mw
3217 */
3218 function getMagic( $mw ) {
3219 $rawEntry = $this->mMagicExtensions[$mw->mId] ??
3220 self::$dataCache->getSubitem( $this->mCode, 'magicWords', $mw->mId );
3221
3222 if ( !is_array( $rawEntry ) ) {
3223 wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3224 } else {
3225 $mw->mCaseSensitive = $rawEntry[0];
3226 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3227 }
3228 }
3229
3230 /**
3231 * Add magic words to the extension array
3232 *
3233 * @param array $newWords
3234 */
3235 function addMagicWordsByLang( $newWords ) {
3236 $fallbackChain = $this->getFallbackLanguages();
3237 $fallbackChain = array_reverse( $fallbackChain );
3238 foreach ( $fallbackChain as $code ) {
3239 if ( isset( $newWords[$code] ) ) {
3240 // @phan-suppress-next-line PhanTypeMismatchProperty
3241 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3242 }
3243 }
3244 }
3245
3246 /**
3247 * Get special page names, as an associative array
3248 * canonical name => array of valid names, including aliases
3249 * @return array
3250 */
3251 function getSpecialPageAliases() {
3252 // Cache aliases because it may be slow to load them
3253 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3254 // Initialise array
3255 $this->mExtendedSpecialPageAliases =
3256 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3257 }
3258
3259 return $this->mExtendedSpecialPageAliases;
3260 }
3261
3262 /**
3263 * Italic is unsuitable for some languages
3264 *
3265 * @param string $text The text to be emphasized.
3266 * @return string
3267 */
3268 function emphasize( $text ) {
3269 return "<em>$text</em>";
3270 }
3271
3272 /**
3273 * Normally we output all numbers in plain en_US style, that is
3274 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3275 * point twohundredthirtyfive. However this is not suitable for all
3276 * languages, some such as Bengali (bn) want ২,৯৩,২৯১.২৩৫ and others such as
3277 * Icelandic just want to use commas instead of dots, and dots instead
3278 * of commas like "293.291,235".
3279 *
3280 * An example of this function being called:
3281 * <code>
3282 * wfMessage( 'message' )->numParams( $num )->text()
3283 * </code>
3284 *
3285 * See $separatorTransformTable on MessageIs.php for
3286 * the , => . and . => , implementation.
3287 *
3288 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3289 * @param int|float $number The string to be formatted, should be an integer
3290 * or a floating point number.
3291 * @param bool $nocommafy Set to true for special numbers like dates
3292 * @return string
3293 */
3294 public function formatNum( $number, $nocommafy = false ) {
3295 global $wgTranslateNumerals;
3296 if ( !$nocommafy ) {
3297 $number = $this->commafy( $number );
3298 $s = $this->separatorTransformTable();
3299 if ( $s ) {
3300 $number = strtr( $number, $s );
3301 }
3302 }
3303
3304 if ( $wgTranslateNumerals ) {
3305 $s = $this->digitTransformTable();
3306 if ( $s ) {
3307 $number = strtr( $number, $s );
3308 }
3309 }
3310
3311 return (string)$number;
3312 }
3313
3314 /**
3315 * Front-end for non-commafied formatNum
3316 *
3317 * @param int|float $number The string to be formatted, should be an integer
3318 * or a floating point number.
3319 * @since 1.21
3320 * @return string
3321 */
3322 public function formatNumNoSeparators( $number ) {
3323 return $this->formatNum( $number, true );
3324 }
3325
3326 /**
3327 * @param string $number
3328 * @return string
3329 */
3330 public function parseFormattedNumber( $number ) {
3331 $s = $this->digitTransformTable();
3332 if ( $s ) {
3333 // eliminate empty array values such as ''. (T66347)
3334 $s = array_filter( $s );
3335 $number = strtr( $number, array_flip( $s ) );
3336 }
3337
3338 $s = $this->separatorTransformTable();
3339 if ( $s ) {
3340 // eliminate empty array values such as ''. (T66347)
3341 $s = array_filter( $s );
3342 $number = strtr( $number, array_flip( $s ) );
3343 }
3344
3345 $number = strtr( $number, [ ',' => '' ] );
3346 return $number;
3347 }
3348
3349 /**
3350 * Adds commas to a given number
3351 * @since 1.19
3352 * @param mixed $number
3353 * @return string
3354 */
3355 function commafy( $number ) {
3356 $digitGroupingPattern = $this->digitGroupingPattern();
3357 $minimumGroupingDigits = $this->minimumGroupingDigits();
3358 if ( $number === null ) {
3359 return '';
3360 }
3361
3362 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3363 // Default grouping is at thousands, use the same for ###,###,### pattern too.
3364 // In some languages it's conventional not to insert a thousands separator
3365 // in numbers that are four digits long (1000-9999).
3366 if ( $minimumGroupingDigits ) {
3367 // Number of '#' characters after last comma in the grouping pattern.
3368 // The pattern is hardcoded here, but this would vary for different patterns.
3369 $primaryGroupingSize = 3;
3370 // Maximum length of a number to suppress digit grouping for.
3371 $maximumLength = $minimumGroupingDigits + $primaryGroupingSize - 1;
3372 if ( preg_match( '/^\-?\d{1,' . $maximumLength . '}(\.\d+)?$/', $number ) ) {
3373 return $number;
3374 }
3375 }
3376 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3377 } else {
3378 // Ref: http://cldr.unicode.org/translation/number-patterns
3379 $sign = "";
3380 if ( intval( $number ) < 0 ) {
3381 // For negative numbers apply the algorithm like positive number and add sign.
3382 $sign = "-";
3383 $number = substr( $number, 1 );
3384 }
3385 $integerPart = [];
3386 $decimalPart = [];
3387 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3388 preg_match( "/\d+/", $number, $integerPart );
3389 preg_match( "/\.\d*/", $number, $decimalPart );
3390 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3391 if ( $groupedNumber === $number ) {
3392 // the string does not have any number part. Eg: .12345
3393 return $sign . $groupedNumber;
3394 }
3395 $start = $end = ( $integerPart ) ? strlen( $integerPart[0] ) : 0;
3396 while ( $start > 0 ) {
3397 $match = $matches[0][$numMatches - 1];
3398 $matchLen = strlen( $match );
3399 $start = $end - $matchLen;
3400 if ( $start < 0 ) {
3401 $start = 0;
3402 }
3403 $groupedNumber = substr( $number, $start, $end - $start ) . $groupedNumber;
3404 $end = $start;
3405 if ( $numMatches > 1 ) {
3406 // use the last pattern for the rest of the number
3407 $numMatches--;
3408 }
3409 if ( $start > 0 ) {
3410 $groupedNumber = "," . $groupedNumber;
3411 }
3412 }
3413 return $sign . $groupedNumber;
3414 }
3415 }
3416
3417 /**
3418 * @return string
3419 */
3420 function digitGroupingPattern() {
3421 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3422 }
3423
3424 /**
3425 * @return array
3426 */
3427 function digitTransformTable() {
3428 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3429 }
3430
3431 /**
3432 * @return array
3433 */
3434 function separatorTransformTable() {
3435 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3436 }
3437
3438 /**
3439 * @return int|null
3440 */
3441 function minimumGroupingDigits() {
3442 return self::$dataCache->getItem( $this->mCode, 'minimumGroupingDigits' );
3443 }
3444
3445 /**
3446 * Take a list of strings and build a locale-friendly comma-separated
3447 * list, using the local comma-separator message.
3448 * The last two strings are chained with an "and".
3449 *
3450 * @param string[] $list
3451 * @return string
3452 */
3453 public function listToText( array $list ) {
3454 $itemCount = count( $list );
3455 if ( $itemCount < 1 ) {
3456 return '';
3457 }
3458 $text = array_pop( $list );
3459 if ( $itemCount > 1 ) {
3460 $and = $this->msg( 'and' )->escaped();
3461 $space = $this->msg( 'word-separator' )->escaped();
3462 $comma = '';
3463 if ( $itemCount > 2 ) {
3464 $comma = $this->msg( 'comma-separator' )->escaped();
3465 }
3466 $text = implode( $comma, $list ) . $and . $space . $text;
3467 }
3468 return $text;
3469 }
3470
3471 /**
3472 * Take a list of strings and build a locale-friendly comma-separated
3473 * list, using the local comma-separator message.
3474 * @param string[] $list Array of strings to put in a comma list
3475 * @return string
3476 */
3477 function commaList( array $list ) {
3478 return implode(
3479 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3480 $list
3481 );
3482 }
3483
3484 /**
3485 * Take a list of strings and build a locale-friendly semicolon-separated
3486 * list, using the local semicolon-separator message.
3487 * @param string[] $list Array of strings to put in a semicolon list
3488 * @return string
3489 */
3490 function semicolonList( array $list ) {
3491 return implode(
3492 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3493 $list
3494 );
3495 }
3496
3497 /**
3498 * Same as commaList, but separate it with the pipe instead.
3499 * @param string[] $list Array of strings to put in a pipe list
3500 * @return string
3501 */
3502 function pipeList( array $list ) {
3503 return implode(
3504 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3505 $list
3506 );
3507 }
3508
3509 /**
3510 * Truncate a string to a specified length in bytes, appending an optional
3511 * string (e.g. for ellipsis)
3512 *
3513 * If $length is negative, the string will be truncated from the beginning
3514 *
3515 * @since 1.31
3516 *
3517 * @param string $string String to truncate
3518 * @param int $length Maximum length in bytes
3519 * @param string $ellipsis String to append to the end of truncated text
3520 * @param bool $adjustLength Subtract length of ellipsis from $length
3521 *
3522 * @return string
3523 */
3524 function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3525 return $this->truncateInternal(
3526 $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
3527 );
3528 }
3529
3530 /**
3531 * Truncate a string to a specified number of characters, appending an optional
3532 * string (e.g. for ellipsis).
3533 *
3534 * This provides multibyte version of truncateForDatabase() method of this class,
3535 * suitable for truncation based on number of characters, instead of number of bytes.
3536 *
3537 * If $length is negative, the string will be truncated from the beginning.
3538 *
3539 * @since 1.31
3540 *
3541 * @param string $string String to truncate
3542 * @param int $length Maximum number of characters
3543 * @param string $ellipsis String to append to the end of truncated text
3544 * @param bool $adjustLength Subtract length of ellipsis from $length
3545 *
3546 * @return string
3547 */
3548 function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3549 // Passing encoding to mb_strlen and mb_substr is optional.
3550 // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
3551 // explicit specification of encoding is skipped.
3552 // Note: Both multibyte methods are callables invoked in truncateInternal.
3553 return $this->truncateInternal(
3554 $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
3555 );
3556 }
3557
3558 /**
3559 * Internal method used for truncation. This method abstracts text truncation into
3560 * one common method, allowing users to provide length measurement function and
3561 * function for finding substring.
3562 *
3563 * For usages, see truncateForDatabase and truncateForVisual.
3564 *
3565 * @param string $string String to truncate
3566 * @param int $length Maximum length of final text
3567 * @param string $ellipsis String to append to the end of truncated text
3568 * @param bool $adjustLength Subtract length of ellipsis from $length
3569 * @param callable $measureLength Callable function used for determining the length of text
3570 * @param callable $getSubstring Callable function used for getting the substrings
3571 *
3572 * @return string
3573 */
3574 private function truncateInternal(
3575 $string, $length, $ellipsis, $adjustLength, callable $measureLength, callable $getSubstring
3576 ) {
3577 # Check if there is no need to truncate
3578 if ( $measureLength( $string ) <= abs( $length ) ) {
3579 return $string; // no need to truncate
3580 }
3581
3582 # Use the localized ellipsis character
3583 if ( $ellipsis == '...' ) {
3584 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3585 }
3586 if ( $length == 0 ) {
3587 return $ellipsis; // convention
3588 }
3589
3590 $stringOriginal = $string;
3591 # If ellipsis length is >= $length then we can't apply $adjustLength
3592 if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
3593 $string = $ellipsis; // this can be slightly unexpected
3594 # Otherwise, truncate and add ellipsis...
3595 } else {
3596 $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
3597 if ( $length > 0 ) {
3598 $length -= $ellipsisLength;
3599 $string = $getSubstring( $string, 0, $length ); // xyz...
3600 $string = $this->removeBadCharLast( $string );
3601 $string = rtrim( $string ) . $ellipsis;
3602 } else {
3603 $length += $ellipsisLength;
3604 $string = $getSubstring( $string, $length ); // ...xyz
3605 $string = $this->removeBadCharFirst( $string );
3606 $string = $ellipsis . ltrim( $string );
3607 }
3608 }
3609
3610 # Do not truncate if the ellipsis makes the string longer/equal (T24181).
3611 # This check is *not* redundant if $adjustLength, due to the single case where
3612 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3613 if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
3614 return $string;
3615 } else {
3616 return $stringOriginal;
3617 }
3618 }
3619
3620 /**
3621 * Remove bytes that represent an incomplete Unicode character
3622 * at the end of string (e.g. bytes of the char are missing)
3623 *
3624 * @param string $string
3625 * @return string
3626 */
3627 protected function removeBadCharLast( $string ) {
3628 if ( $string != '' ) {
3629 $char = ord( $string[strlen( $string ) - 1] );
3630 $m = [];
3631 if ( $char >= 0xc0 ) {
3632 # We got the first byte only of a multibyte char; remove it.
3633 $string = substr( $string, 0, -1 );
3634 } elseif ( $char >= 0x80 &&
3635 // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
3636 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3637 '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
3638 ) {
3639 # We chopped in the middle of a character; remove it
3640 $string = $m[1];
3641 }
3642 }
3643 return $string;
3644 }
3645
3646 /**
3647 * Remove bytes that represent an incomplete Unicode character
3648 * at the start of string (e.g. bytes of the char are missing)
3649 *
3650 * @param string $string
3651 * @return string
3652 */
3653 protected function removeBadCharFirst( $string ) {
3654 if ( $string != '' ) {
3655 $char = ord( $string[0] );
3656 if ( $char >= 0x80 && $char < 0xc0 ) {
3657 # We chopped in the middle of a character; remove the whole thing
3658 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3659 }
3660 }
3661 return $string;
3662 }
3663
3664 /**
3665 * Truncate a string of valid HTML to a specified length in bytes,
3666 * appending an optional string (e.g. for ellipses), and return valid HTML
3667 *
3668 * This is only intended for styled/linked text, such as HTML with
3669 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3670 * Also, this will not detect things like "display:none" CSS.
3671 *
3672 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3673 *
3674 * @param string $text HTML string to truncate
3675 * @param int $length (zero/positive) Maximum length (including ellipses)
3676 * @param string $ellipsis String to append to the truncated text
3677 * @return string
3678 */
3679 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3680 # Use the localized ellipsis character
3681 if ( $ellipsis == '...' ) {
3682 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3683 }
3684 # Check if there is clearly no need to truncate
3685 if ( $length <= 0 ) {
3686 return $ellipsis; // no text shown, nothing to format (convention)
3687 } elseif ( strlen( $text ) <= $length ) {
3688 return $text; // string short enough even *with* HTML (short-circuit)
3689 }
3690
3691 $dispLen = 0; // innerHTML legth so far
3692 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3693 $tagType = 0; // 0-open, 1-close
3694 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3695 $entityState = 0; // 0-not entity, 1-entity
3696 $tag = $ret = ''; // accumulated tag name, accumulated result string
3697 $openTags = []; // open tag stack
3698 $maybeState = null; // possible truncation state
3699
3700 $textLen = strlen( $text );
3701 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3702 for ( $pos = 0; true; ++$pos ) {
3703 # Consider truncation once the display length has reached the maximim.
3704 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3705 # Check that we're not in the middle of a bracket/entity...
3706 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3707 if ( !$testingEllipsis ) {
3708 $testingEllipsis = true;
3709 # Save where we are; we will truncate here unless there turn out to
3710 # be so few remaining characters that truncation is not necessary.
3711 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3712 $maybeState = [ $ret, $openTags ]; // save state
3713 }
3714 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3715 # String in fact does need truncation, the truncation point was OK.
3716 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
3717 list( $ret, $openTags ) = $maybeState; // reload state
3718 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3719 $ret .= $ellipsis; // add ellipsis
3720 break;
3721 }
3722 }
3723 if ( $pos >= $textLen ) {
3724 break; // extra iteration just for above checks
3725 }
3726
3727 # Read the next char...
3728 $ch = $text[$pos];
3729 $lastCh = $pos ? $text[$pos - 1] : '';
3730 $ret .= $ch; // add to result string
3731 if ( $ch == '<' ) {
3732 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3733 $entityState = 0; // for bad HTML
3734 $bracketState = 1; // tag started (checking for backslash)
3735 } elseif ( $ch == '>' ) {
3736 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3737 $entityState = 0; // for bad HTML
3738 $bracketState = 0; // out of brackets
3739 } elseif ( $bracketState == 1 ) {
3740 if ( $ch == '/' ) {
3741 $tagType = 1; // close tag (e.g. "</span>")
3742 } else {
3743 $tagType = 0; // open tag (e.g. "<span>")
3744 $tag .= $ch;
3745 }
3746 $bracketState = 2; // building tag name
3747 } elseif ( $bracketState == 2 ) {
3748 if ( $ch != ' ' ) {
3749 $tag .= $ch;
3750 } else {
3751 // Name found (e.g. "<a href=..."), add on tag attributes...
3752 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3753 }
3754 } elseif ( $bracketState == 0 ) {
3755 if ( $entityState ) {
3756 if ( $ch == ';' ) {
3757 $entityState = 0;
3758 $dispLen++; // entity is one displayed char
3759 }
3760 } else {
3761 if ( $neLength == 0 && !$maybeState ) {
3762 // Save state without $ch. We want to *hit* the first
3763 // display char (to get tags) but not *use* it if truncating.
3764 $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
3765 }
3766 if ( $ch == '&' ) {
3767 $entityState = 1; // entity found, (e.g. "&#160;")
3768 } else {
3769 $dispLen++; // this char is displayed
3770 // Add the next $max display text chars after this in one swoop...
3771 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3772 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3773 $dispLen += $skipped;
3774 $pos += $skipped;
3775 }
3776 }
3777 }
3778 }
3779 // Close the last tag if left unclosed by bad HTML
3780 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3781 while ( count( $openTags ) > 0 ) {
3782 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3783 }
3784 return $ret;
3785 }
3786
3787 /**
3788 * truncateHtml() helper function
3789 * like strcspn() but adds the skipped chars to $ret
3790 *
3791 * @param string $ret
3792 * @param string $text
3793 * @param string $search
3794 * @param int $start
3795 * @param null|int $len
3796 * @return int
3797 */
3798 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3799 if ( $len === null ) {
3800 $len = -1; // -1 means "no limit" for strcspn
3801 } elseif ( $len < 0 ) {
3802 $len = 0; // sanity
3803 }
3804 $skipCount = 0;
3805 if ( $start < strlen( $text ) ) {
3806 $skipCount = strcspn( $text, $search, $start, $len );
3807 $ret .= substr( $text, $start, $skipCount );
3808 }
3809 return $skipCount;
3810 }
3811
3812 /**
3813 * truncateHtml() helper function
3814 * (a) push or pop $tag from $openTags as needed
3815 * (b) clear $tag value
3816 * @param string &$tag Current HTML tag name we are looking at
3817 * @param int $tagType (0-open tag, 1-close tag)
3818 * @param string $lastCh Character before the '>' that ended this tag
3819 * @param array &$openTags Open tag stack (not accounting for $tag)
3820 */
3821 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3822 $tag = ltrim( $tag );
3823 if ( $tag != '' ) {
3824 if ( $tagType == 0 && $lastCh != '/' ) {
3825 $openTags[] = $tag; // tag opened (didn't close itself)
3826 } elseif ( $tagType == 1 ) {
3827 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3828 array_pop( $openTags ); // tag closed
3829 }
3830 }
3831 $tag = '';
3832 }
3833 }
3834
3835 /**
3836 * Grammatical transformations, needed for inflected languages
3837 * Invoked by putting {{grammar:case|word}} in a message
3838 *
3839 * @param string $word
3840 * @param string $case
3841 * @return string
3842 */
3843 function convertGrammar( $word, $case ) {
3844 global $wgGrammarForms;
3845 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3846 return $wgGrammarForms[$this->getCode()][$case][$word];
3847 }
3848
3849 $grammarTransformations = $this->getGrammarTransformations();
3850
3851 if ( isset( $grammarTransformations[$case] ) ) {
3852 $forms = $grammarTransformations[$case];
3853
3854 // Some names of grammar rules are aliases for other rules.
3855 // In such cases the value is a string rather than object,
3856 // so load the actual rules.
3857 if ( is_string( $forms ) ) {
3858 $forms = $grammarTransformations[$forms];
3859 }
3860
3861 foreach ( array_values( $forms ) as $rule ) {
3862 $form = $rule[0];
3863
3864 if ( $form === '@metadata' ) {
3865 continue;
3866 }
3867
3868 $replacement = $rule[1];
3869
3870 $regex = '/' . addcslashes( $form, '/' ) . '/u';
3871 $patternMatches = preg_match( $regex, $word );
3872
3873 if ( $patternMatches === false ) {
3874 wfLogWarning(
3875 'An error occurred while processing grammar. ' .
3876 "Word: '$word'. Regex: /$form/."
3877 );
3878 } elseif ( $patternMatches === 1 ) {
3879 $word = preg_replace( $regex, $replacement, $word );
3880
3881 break;
3882 }
3883 }
3884 }
3885
3886 return $word;
3887 }
3888
3889 /**
3890 * Get the grammar forms for the content language
3891 * @return array Array of grammar forms
3892 * @since 1.20
3893 */
3894 function getGrammarForms() {
3895 global $wgGrammarForms;
3896 if ( isset( $wgGrammarForms[$this->getCode()] )
3897 && is_array( $wgGrammarForms[$this->getCode()] )
3898 ) {
3899 return $wgGrammarForms[$this->getCode()];
3900 }
3901
3902 return [];
3903 }
3904
3905 /**
3906 * Get the grammar transformations data for the language.
3907 * Used like grammar forms, with {{GRAMMAR}} and cases,
3908 * but uses pairs of regexes and replacements instead of code.
3909 *
3910 * @return array[] Array of grammar transformations.
3911 * @throws MWException
3912 * @since 1.28
3913 */
3914 public function getGrammarTransformations() {
3915 $languageCode = $this->getCode();
3916
3917 if ( self::$grammarTransformations === null ) {
3918 self::$grammarTransformations = new MapCacheLRU( 10 );
3919 }
3920
3921 if ( self::$grammarTransformations->has( $languageCode ) ) {
3922 return self::$grammarTransformations->get( $languageCode );
3923 }
3924
3925 $data = [];
3926
3927 $grammarDataFile = __DIR__ . "/data/grammarTransformations/$languageCode.json";
3928 if ( is_readable( $grammarDataFile ) ) {
3929 $data = FormatJson::decode(
3930 file_get_contents( $grammarDataFile ),
3931 true
3932 );
3933
3934 if ( $data === null ) {
3935 throw new MWException( "Invalid grammar data for \"$languageCode\"." );
3936 }
3937
3938 self::$grammarTransformations->set( $languageCode, $data );
3939 }
3940
3941 return $data;
3942 }
3943
3944 /**
3945 * Provides an alternative text depending on specified gender.
3946 * Usage {{gender:username|masculine|feminine|unknown}}.
3947 * username is optional, in which case the gender of current user is used,
3948 * but only in (some) interface messages; otherwise default gender is used.
3949 *
3950 * If no forms are given, an empty string is returned. If only one form is
3951 * given, it will be returned unconditionally. These details are implied by
3952 * the caller and cannot be overridden in subclasses.
3953 *
3954 * If three forms are given, the default is to use the third (unknown) form.
3955 * If fewer than three forms are given, the default is to use the first (masculine) form.
3956 * These details can be overridden in subclasses.
3957 *
3958 * @param string $gender
3959 * @param array $forms
3960 *
3961 * @return string
3962 */
3963 function gender( $gender, $forms ) {
3964 if ( !count( $forms ) ) {
3965 return '';
3966 }
3967 $forms = $this->preConvertPlural( $forms, 2 );
3968 if ( $gender === 'male' ) {
3969 return $forms[0];
3970 }
3971 if ( $gender === 'female' ) {
3972 return $forms[1];
3973 }
3974 return $forms[2] ?? $forms[0];
3975 }
3976
3977 /**
3978 * Plural form transformations, needed for some languages.
3979 * For example, there are 3 form of plural in Russian and Polish,
3980 * depending on "count mod 10". See [[w:Plural]]
3981 * For English it is pretty simple.
3982 *
3983 * Invoked by putting {{plural:count|wordform1|wordform2}}
3984 * or {{plural:count|wordform1|wordform2|wordform3}}
3985 *
3986 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3987 *
3988 * @param int $count Non-localized number
3989 * @param array $forms Different plural forms
3990 * @return string Correct form of plural for $count in this language
3991 */
3992 function convertPlural( $count, $forms ) {
3993 // Handle explicit n=pluralform cases
3994 $forms = $this->handleExplicitPluralForms( $count, $forms );
3995 if ( is_string( $forms ) ) {
3996 return $forms;
3997 }
3998 if ( !count( $forms ) ) {
3999 return '';
4000 }
4001
4002 $pluralForm = $this->getPluralRuleIndexNumber( $count );
4003 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
4004 return $forms[$pluralForm];
4005 }
4006
4007 /**
4008 * Handles explicit plural forms for Language::convertPlural()
4009 *
4010 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
4011 * If an explicitly defined plural form matches the $count, then
4012 * string value returned, otherwise array returned for further consideration
4013 * by CLDR rules or overridden convertPlural().
4014 *
4015 * @since 1.23
4016 *
4017 * @param int $count Non-localized number
4018 * @param array $forms Different plural forms
4019 *
4020 * @return array|string
4021 */
4022 protected function handleExplicitPluralForms( $count, array $forms ) {
4023 foreach ( $forms as $index => $form ) {
4024 if ( preg_match( '/\d+=/i', $form ) ) {
4025 $pos = strpos( $form, '=' );
4026 if ( substr( $form, 0, $pos ) === (string)$count ) {
4027 return substr( $form, $pos + 1 );
4028 }
4029 unset( $forms[$index] );
4030 }
4031 }
4032 return array_values( $forms );
4033 }
4034
4035 /**
4036 * Checks that convertPlural was given an array and pads it to requested
4037 * amount of forms by copying the last one.
4038 *
4039 * @param array $forms
4040 * @param int $count How many forms should there be at least
4041 * @return array Padded array of forms
4042 */
4043 protected function preConvertPlural( /* Array */ $forms, $count ) {
4044 return array_pad( $forms, $count, end( $forms ) );
4045 }
4046
4047 /**
4048 * Wraps argument with unicode control characters for directionality safety
4049 *
4050 * This solves the problem where directionality-neutral characters at the edge of
4051 * the argument string get interpreted with the wrong directionality from the
4052 * enclosing context, giving renderings that look corrupted like "(Ben_(WMF".
4053 *
4054 * The wrapping is LRE...PDF or RLE...PDF, depending on the detected
4055 * directionality of the argument string, using the BIDI algorithm's own "First
4056 * strong directional codepoint" rule. Essentially, this works round the fact that
4057 * there is no embedding equivalent of U+2068 FSI (isolation with heuristic
4058 * direction inference). The latter is cleaner but still not widely supported.
4059 *
4060 * @param string $text Text to wrap
4061 * @return string Text, wrapped in LRE...PDF or RLE...PDF or nothing
4062 */
4063 public function embedBidi( $text = '' ) {
4064 $dir = self::strongDirFromContent( $text );
4065 if ( $dir === 'ltr' ) {
4066 // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
4067 return self::$lre . $text . self::$pdf;
4068 }
4069 if ( $dir === 'rtl' ) {
4070 // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
4071 return self::$rle . $text . self::$pdf;
4072 }
4073 // No strong directionality: do not wrap
4074 return $text;
4075 }
4076
4077 /**
4078 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
4079 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
4080 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
4081 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
4082 * match up with it.
4083 *
4084 * @param string $str The validated block duration in English
4085 * @param User|null $user User object to use timezone from or null for $wgUser
4086 * @param int $now Current timestamp, for formatting relative block durations
4087 * @return string Somehow translated block duration
4088 * @see LanguageFi.php for example implementation
4089 */
4090 function translateBlockExpiry( $str, User $user = null, $now = 0 ) {
4091 $duration = SpecialBlock::getSuggestedDurations( $this );
4092 foreach ( $duration as $show => $value ) {
4093 if ( strcmp( $str, $value ) == 0 ) {
4094 return htmlspecialchars( trim( $show ) );
4095 }
4096 }
4097
4098 if ( wfIsInfinity( $str ) ) {
4099 foreach ( $duration as $show => $value ) {
4100 if ( wfIsInfinity( $value ) ) {
4101 return htmlspecialchars( trim( $show ) );
4102 }
4103 }
4104 }
4105
4106 // If all else fails, return a standard duration or timestamp description.
4107 $time = strtotime( $str, $now );
4108 if ( $time === false ) { // Unknown format. Return it as-is in case.
4109 return $str;
4110 } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
4111 // The result differs based on current time, so the difference
4112 // is a fixed duration length.
4113 return $this->formatDuration( $time - $now );
4114 } else { // It's an absolute timestamp.
4115 if ( $time === 0 ) {
4116 // wfTimestamp() handles 0 as current time instead of epoch.
4117 $time = '19700101000000';
4118 }
4119 if ( $user ) {
4120 return $this->userTimeAndDate( $time, $user );
4121 }
4122 return $this->timeanddate( $time );
4123 }
4124 }
4125
4126 /**
4127 * languages like Chinese need to be segmented in order for the diff
4128 * to be of any use
4129 *
4130 * @param string $text
4131 * @return string
4132 */
4133 public function segmentForDiff( $text ) {
4134 return $text;
4135 }
4136
4137 /**
4138 * and unsegment to show the result
4139 *
4140 * @param string $text
4141 * @return string
4142 */
4143 public function unsegmentForDiff( $text ) {
4144 return $text;
4145 }
4146
4147 /**
4148 * Return the LanguageConverter used in the Language
4149 *
4150 * @since 1.19
4151 * @return LanguageConverter
4152 */
4153 public function getConverter() {
4154 return $this->mConverter;
4155 }
4156
4157 /**
4158 * convert text to a variant
4159 *
4160 * @param string $text text to convert
4161 * @param string|bool $variant variant to convert to, or false to use the user's preferred
4162 * variant (if logged in), or the project default variant
4163 * @return string the converted string
4164 */
4165 public function autoConvert( $text, $variant = false ) {
4166 return $this->mConverter->autoConvert( $text, $variant );
4167 }
4168
4169 /**
4170 * convert text to all supported variants
4171 *
4172 * @param string $text
4173 * @return array
4174 */
4175 public function autoConvertToAllVariants( $text ) {
4176 return $this->mConverter->autoConvertToAllVariants( $text );
4177 }
4178
4179 /**
4180 * convert text to different variants of a language.
4181 *
4182 * @warning Glossary state is maintained between calls. This means
4183 * if you pass unescaped text to this method it can cause an XSS
4184 * in later calls to this method, even if the later calls have properly
4185 * escaped the input. Never feed this method user controlled text that
4186 * is not properly escaped!
4187 * @param string $text Content that has been already escaped for use in HTML
4188 * @return string HTML
4189 */
4190 public function convert( $text ) {
4191 return $this->mConverter->convert( $text );
4192 }
4193
4194 /**
4195 * Convert a Title object to a string in the preferred variant
4196 *
4197 * @param Title $title
4198 * @return string
4199 */
4200 public function convertTitle( $title ) {
4201 return $this->mConverter->convertTitle( $title );
4202 }
4203
4204 /**
4205 * Convert a namespace index to a string in the preferred variant
4206 *
4207 * @param int $ns namespace index (https://www.mediawiki.org/wiki/Manual:Namespace)
4208 * @param string|null $variant variant to convert to, or null to use the user's preferred
4209 * variant (if logged in), or the project default variant
4210 * @return string a string representation of the namespace
4211 */
4212 public function convertNamespace( $ns, $variant = null ) {
4213 return $this->mConverter->convertNamespace( $ns, $variant );
4214 }
4215
4216 /**
4217 * Check if this is a language with variants
4218 *
4219 * @return bool
4220 */
4221 public function hasVariants() {
4222 return count( $this->getVariants() ) > 1;
4223 }
4224
4225 /**
4226 * Strict check if the language has the specific variant.
4227 *
4228 * Compare to LanguageConverter::validateVariant() which does a more
4229 * lenient check and attempts to coerce the given code to a valid one.
4230 *
4231 * @since 1.19
4232 * @param string $variant
4233 * @return bool
4234 */
4235 public function hasVariant( $variant ) {
4236 return $variant && ( $variant === $this->mConverter->validateVariant( $variant ) );
4237 }
4238
4239 /**
4240 * Perform output conversion on a string, and encode for safe HTML output.
4241 * @param string $text Text to be converted
4242 * @return string
4243 * @todo this should get integrated somewhere sane
4244 */
4245 public function convertHtml( $text ) {
4246 return htmlspecialchars( $this->convert( $text ) );
4247 }
4248
4249 /**
4250 * @param string $key
4251 * @return string
4252 */
4253 public function convertCategoryKey( $key ) {
4254 return $this->mConverter->convertCategoryKey( $key );
4255 }
4256
4257 /**
4258 * Get the list of variants supported by this language
4259 * see sample implementation in LanguageZh.php
4260 *
4261 * @return string[] An array of language codes
4262 */
4263 public function getVariants() {
4264 return $this->mConverter->getVariants();
4265 }
4266
4267 /**
4268 * @return string
4269 */
4270 public function getPreferredVariant() {
4271 return $this->mConverter->getPreferredVariant();
4272 }
4273
4274 /**
4275 * @return string
4276 */
4277 public function getDefaultVariant() {
4278 return $this->mConverter->getDefaultVariant();
4279 }
4280
4281 /**
4282 * @return string
4283 */
4284 public function getURLVariant() {
4285 return $this->mConverter->getURLVariant();
4286 }
4287
4288 /**
4289 * If a language supports multiple variants, it is
4290 * possible that non-existing link in one variant
4291 * actually exists in another variant. this function
4292 * tries to find it. See e.g. LanguageZh.php
4293 * The input parameters may be modified upon return
4294 *
4295 * @param string &$link The name of the link
4296 * @param Title &$nt The title object of the link
4297 * @param bool $ignoreOtherCond To disable other conditions when
4298 * we need to transclude a template or update a category's link
4299 */
4300 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
4301 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
4302 }
4303
4304 /**
4305 * returns language specific options used by User::getPageRenderHash()
4306 * for example, the preferred language variant
4307 *
4308 * @return string
4309 */
4310 function getExtraHashOptions() {
4311 return $this->mConverter->getExtraHashOptions();
4312 }
4313
4314 /**
4315 * For languages that support multiple variants, the title of an
4316 * article may be displayed differently in different variants. this
4317 * function returns the apporiate title defined in the body of the article.
4318 *
4319 * @return string
4320 */
4321 public function getParsedTitle() {
4322 return $this->mConverter->getParsedTitle();
4323 }
4324
4325 /**
4326 * Refresh the cache of conversion tables when
4327 * MediaWiki:Conversiontable* is updated.
4328 *
4329 * @param Title $title The Title of the page being updated
4330 */
4331 public function updateConversionTable( Title $title ) {
4332 $this->mConverter->updateConversionTable( $title );
4333 }
4334
4335 /**
4336 * A regular expression to match legal word-trailing characters
4337 * which should be merged onto a link of the form [[foo]]bar.
4338 *
4339 * @return string
4340 */
4341 public function linkTrail() {
4342 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
4343 }
4344
4345 /**
4346 * A regular expression character set to match legal word-prefixing
4347 * characters which should be merged onto a link of the form foo[[bar]].
4348 *
4349 * @return string
4350 */
4351 public function linkPrefixCharset() {
4352 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
4353 }
4354
4355 /**
4356 * Get the "parent" language which has a converter to convert a "compatible" language
4357 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
4358 *
4359 * @return Language|null
4360 * @since 1.22
4361 */
4362 public function getParentLanguage() {
4363 if ( $this->mParentLanguage !== false ) {
4364 return $this->mParentLanguage;
4365 }
4366
4367 $code = explode( '-', $this->getCode() )[0];
4368 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4369 $this->mParentLanguage = null;
4370 return null;
4371 }
4372 $lang = self::factory( $code );
4373 if ( !$lang->hasVariant( $this->getCode() ) ) {
4374 $this->mParentLanguage = null;
4375 return null;
4376 }
4377
4378 $this->mParentLanguage = $lang;
4379 return $lang;
4380 }
4381
4382 /**
4383 * Compare with an other language object
4384 *
4385 * @since 1.28
4386 * @param Language $lang
4387 * @return bool
4388 */
4389 public function equals( Language $lang ) {
4390 return $lang === $this || $lang->getCode() === $this->mCode;
4391 }
4392
4393 /**
4394 * Get the internal language code for this language object
4395 *
4396 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4397 * htmlspecialchars() or similar
4398 *
4399 * @return string
4400 */
4401 public function getCode() {
4402 return $this->mCode;
4403 }
4404
4405 /**
4406 * Get the code in BCP 47 format which we can use
4407 * inside of html lang="" tags.
4408 *
4409 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4410 * htmlspecialchars() or similar.
4411 *
4412 * @since 1.19
4413 * @return string
4414 */
4415 public function getHtmlCode() {
4416 if ( is_null( $this->mHtmlCode ) ) {
4417 $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
4418 }
4419 return $this->mHtmlCode;
4420 }
4421
4422 /**
4423 * Get the language code from a file name. Inverse of getFileName()
4424 * @param string $filename $prefix . $languageCode . $suffix
4425 * @param string $prefix Prefix before the language code
4426 * @param string $suffix Suffix after the language code
4427 * @return string Language code, or false if $prefix or $suffix isn't found
4428 */
4429 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4430 $m = null;
4431 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4432 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4433 if ( !count( $m ) ) {
4434 return false;
4435 }
4436 return str_replace( '_', '-', strtolower( $m[1] ) );
4437 }
4438
4439 /**
4440 * @param string $code
4441 * @param bool $fallback Whether we're going through language fallback chain
4442 * @return string Name of the language class
4443 */
4444 public static function classFromCode( $code, $fallback = true ) {
4445 if ( $fallback && $code == 'en' ) {
4446 return 'Language';
4447 } else {
4448 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
4449 }
4450 }
4451
4452 /**
4453 * Get the name of a file for a certain language code
4454 * @param string $prefix Prepend this to the filename
4455 * @param string $code Language code
4456 * @param string $suffix Append this to the filename
4457 * @throws MWException
4458 * @return string $prefix . $mangledCode . $suffix
4459 */
4460 public static function getFileName( $prefix, $code, $suffix = '.php' ) {
4461 if ( !self::isValidBuiltInCode( $code ) ) {
4462 throw new MWException( "Invalid language code \"$code\"" );
4463 }
4464
4465 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4466 }
4467
4468 /**
4469 * @param string $code
4470 * @return string
4471 */
4472 public static function getMessagesFileName( $code ) {
4473 global $IP;
4474 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4475 Hooks::run( 'Language::getMessagesFileName', [ $code, &$file ] );
4476 return $file;
4477 }
4478
4479 /**
4480 * @param string $code
4481 * @return string
4482 * @throws MWException
4483 * @since 1.23
4484 */
4485 public static function getJsonMessagesFileName( $code ) {
4486 global $IP;
4487
4488 if ( !self::isValidBuiltInCode( $code ) ) {
4489 throw new MWException( "Invalid language code \"$code\"" );
4490 }
4491
4492 return "$IP/languages/i18n/$code.json";
4493 }
4494
4495 /**
4496 * Get the first fallback for a given language.
4497 *
4498 * @param string $code
4499 *
4500 * @return bool|string
4501 */
4502 public static function getFallbackFor( $code ) {
4503 $fallbacks = self::getFallbacksFor( $code );
4504 if ( $fallbacks ) {
4505 return $fallbacks[0];
4506 }
4507 return false;
4508 }
4509
4510 /**
4511 * Get the ordered list of fallback languages.
4512 *
4513 * @since 1.19
4514 * @param string $code Language code
4515 * @param int $mode Fallback mode, either MESSAGES_FALLBACKS (which always falls back to 'en'),
4516 * or STRICT_FALLBACKS (whic honly falls back to 'en' when explicitly defined)
4517 * @throws MWException
4518 * @return array List of language codes
4519 */
4520 public static function getFallbacksFor( $code, $mode = self::MESSAGES_FALLBACKS ) {
4521 if ( $code === 'en' || !self::isValidBuiltInCode( $code ) ) {
4522 return [];
4523 }
4524 switch ( $mode ) {
4525 case self::MESSAGES_FALLBACKS:
4526 // For unknown languages, fallbackSequence returns an empty array,
4527 // hardcode fallback to 'en' in that case as English messages are
4528 // always defined.
4529 return self::getLocalisationCache()->getItem( $code, 'fallbackSequence' ) ?: [ 'en' ];
4530 case self::STRICT_FALLBACKS:
4531 // Use this mode when you don't want to fallback to English unless
4532 // explicitly defined, for example when you have language-variant icons
4533 // and an international language-independent fallback.
4534 return self::getLocalisationCache()->getItem( $code, 'originalFallbackSequence' );
4535 default:
4536 throw new MWException( "Invalid fallback mode \"$mode\"" );
4537 }
4538 }
4539
4540 /**
4541 * Get the ordered list of fallback languages, ending with the fallback
4542 * language chain for the site language.
4543 *
4544 * @since 1.22
4545 * @param string $code Language code
4546 * @return array [ fallbacks, site fallbacks ]
4547 */
4548 public static function getFallbacksIncludingSiteLanguage( $code ) {
4549 global $wgLanguageCode;
4550
4551 // Usually, we will only store a tiny number of fallback chains, so we
4552 // keep them in static memory.
4553 $cacheKey = "{$code}-{$wgLanguageCode}";
4554
4555 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4556 $fallbacks = self::getFallbacksFor( $code );
4557
4558 // Append the site's fallback chain, including the site language itself
4559 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4560 array_unshift( $siteFallbacks, $wgLanguageCode );
4561
4562 // Eliminate any languages already included in the chain
4563 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4564
4565 self::$fallbackLanguageCache[$cacheKey] = [ $fallbacks, $siteFallbacks ];
4566 }
4567 return self::$fallbackLanguageCache[$cacheKey];
4568 }
4569
4570 /**
4571 * Get all messages for a given language
4572 * WARNING: this may take a long time. If you just need all message *keys*
4573 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4574 *
4575 * @param string $code
4576 *
4577 * @return array
4578 */
4579 public static function getMessagesFor( $code ) {
4580 return self::getLocalisationCache()->getItem( $code, 'messages' );
4581 }
4582
4583 /**
4584 * Get a message for a given language
4585 *
4586 * @param string $key
4587 * @param string $code
4588 *
4589 * @return string
4590 */
4591 public static function getMessageFor( $key, $code ) {
4592 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4593 }
4594
4595 /**
4596 * Get all message keys for a given language. This is a faster alternative to
4597 * array_keys( Language::getMessagesFor( $code ) )
4598 *
4599 * @since 1.19
4600 * @param string $code Language code
4601 * @return array Array of message keys (strings)
4602 */
4603 public static function getMessageKeysFor( $code ) {
4604 return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
4605 }
4606
4607 /**
4608 * @param string $talk
4609 * @return string
4610 */
4611 function fixVariableInNamespace( $talk ) {
4612 if ( strpos( $talk, '$1' ) === false ) {
4613 return $talk;
4614 }
4615
4616 global $wgMetaNamespace;
4617 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4618
4619 # Allow grammar transformations
4620 # Allowing full message-style parsing would make simple requests
4621 # such as action=raw much more expensive than they need to be.
4622 # This will hopefully cover most cases.
4623 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4624 [ $this, 'replaceGrammarInNamespace' ], $talk );
4625 return str_replace( ' ', '_', $talk );
4626 }
4627
4628 /**
4629 * @param string $m
4630 * @return string
4631 */
4632 function replaceGrammarInNamespace( $m ) {
4633 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4634 }
4635
4636 /**
4637 * Decode an expiry (block, protection, etc) which has come from the DB
4638 *
4639 * @param string $expiry Database expiry String
4640 * @param bool|int $format True to process using language functions, or TS_ constant
4641 * to return the expiry in a given timestamp
4642 * @param string $infinity If $format is not true, use this string for infinite expiry
4643 * @return string
4644 * @since 1.18
4645 */
4646 public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
4647 static $dbInfinity;
4648 if ( $dbInfinity === null ) {
4649 $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
4650 }
4651
4652 if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
4653 return $format === true
4654 ? $this->getMessageFromDB( 'infiniteblock' )
4655 : $infinity;
4656 } else {
4657 return $format === true
4658 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4659 : wfTimestamp( $format, $expiry );
4660 }
4661 }
4662
4663 /**
4664 * Formats a time given in seconds into a string representation of that time.
4665 *
4666 * @param int|float $seconds
4667 * @param array $format An optional argument that formats the returned string in different ways:
4668 * If $format['avoid'] === 'avoidhours': don't show hours, just show days
4669 * If $format['avoid'] === 'avoidseconds': don't show seconds if $seconds >= 1 hour,
4670 * If $format['avoid'] === 'avoidminutes': don't show seconds/minutes if $seconds > 48 hours,
4671 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4672 * and friends.
4673 * @note For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4674 * or 'avoidminutes'.
4675 * @return string
4676 */
4677 function formatTimePeriod( $seconds, $format = [] ) {
4678 if ( !is_array( $format ) ) {
4679 $format = [ 'avoid' => $format ]; // For backwards compatibility
4680 }
4681 if ( !isset( $format['avoid'] ) ) {
4682 $format['avoid'] = false;
4683 }
4684 if ( !isset( $format['noabbrevs'] ) ) {
4685 $format['noabbrevs'] = false;
4686 }
4687 $secondsMsg = wfMessage(
4688 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4689 $minutesMsg = wfMessage(
4690 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4691 $hoursMsg = wfMessage(
4692 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4693 $daysMsg = wfMessage(
4694 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4695
4696 if ( round( $seconds * 10 ) < 100 ) {
4697 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4698 $s = $secondsMsg->params( $s )->text();
4699 } elseif ( round( $seconds ) < 60 ) {
4700 $s = $this->formatNum( round( $seconds ) );
4701 $s = $secondsMsg->params( $s )->text();
4702 } elseif ( round( $seconds ) < 3600 ) {
4703 $minutes = floor( $seconds / 60 );
4704 $secondsPart = round( fmod( $seconds, 60 ) );
4705 if ( $secondsPart == 60 ) {
4706 $secondsPart = 0;
4707 $minutes++;
4708 }
4709 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4710 $s .= ' ';
4711 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4712 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4713 $hours = floor( $seconds / 3600 );
4714 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4715 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4716 if ( $secondsPart == 60 ) {
4717 $secondsPart = 0;
4718 $minutes++;
4719 }
4720 if ( $minutes == 60 ) {
4721 $minutes = 0;
4722 $hours++;
4723 }
4724 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4725 $s .= ' ';
4726 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4727 if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes', 'avoidhours' ] ) ) {
4728 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4729 }
4730 } else {
4731 $days = floor( $seconds / 86400 );
4732 if ( $format['avoid'] === 'avoidhours' ) {
4733 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4734 if ( $hours == 24 ) {
4735 $hours = 0;
4736 $days++;
4737 }
4738 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4739 } elseif ( $format['avoid'] === 'avoidminutes' ) {
4740 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4741 if ( $hours == 24 ) {
4742 $hours = 0;
4743 $days++;
4744 }
4745 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4746 $s .= ' ';
4747 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4748 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4749 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4750 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4751 if ( $minutes == 60 ) {
4752 $minutes = 0;
4753 $hours++;
4754 }
4755 if ( $hours == 24 ) {
4756 $hours = 0;
4757 $days++;
4758 }
4759 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4760 $s .= ' ';
4761 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4762 $s .= ' ';
4763 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4764 } else {
4765 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4766 $s .= ' ';
4767 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4768 }
4769 }
4770 return $s;
4771 }
4772
4773 /**
4774 * Format a bitrate for output, using an appropriate
4775 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4776 * the magnitude in question.
4777 *
4778 * This use base 1000. For base 1024 use formatSize(), for another base
4779 * see formatComputingNumbers().
4780 *
4781 * @param int $bps
4782 * @return string
4783 */
4784 function formatBitrate( $bps ) {
4785 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4786 }
4787
4788 /**
4789 * @param int $size Size of the unit
4790 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4791 * @param string $messageKey Message key to be uesd
4792 * @return string
4793 */
4794 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4795 if ( $size <= 0 ) {
4796 return str_replace( '$1', $this->formatNum( $size ),
4797 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4798 );
4799 }
4800 $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' ];
4801 $index = 0;
4802
4803 $maxIndex = count( $sizes ) - 1;
4804 while ( $size >= $boundary && $index < $maxIndex ) {
4805 $index++;
4806 $size /= $boundary;
4807 }
4808
4809 // For small sizes no decimal places necessary
4810 $round = 0;
4811 if ( $index > 1 ) {
4812 // For MB and bigger two decimal places are smarter
4813 $round = 2;
4814 }
4815 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4816
4817 $size = round( $size, $round );
4818 $text = $this->getMessageFromDB( $msg );
4819 return str_replace( '$1', $this->formatNum( $size ), $text );
4820 }
4821
4822 /**
4823 * Format a size in bytes for output, using an appropriate
4824 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4825 *
4826 * This method use base 1024. For base 1000 use formatBitrate(), for
4827 * another base see formatComputingNumbers()
4828 *
4829 * @param int $size Size to format
4830 * @return string Plain text (not HTML)
4831 */
4832 function formatSize( $size ) {
4833 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4834 }
4835
4836 /**
4837 * Make a list item, used by various special pages
4838 *
4839 * @param string $page Page link
4840 * @param string $details HTML safe text between brackets
4841 * @param bool $oppositedm Add the direction mark opposite to your
4842 * language, to display text properly
4843 * @return string HTML escaped
4844 */
4845 function specialList( $page, $details, $oppositedm = true ) {
4846 if ( !$details ) {
4847 return $page;
4848 }
4849
4850 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
4851 return $page .
4852 $dirmark .
4853 $this->msg( 'word-separator' )->escaped() .
4854 $this->msg( 'parentheses' )->rawParams( $details )->escaped();
4855 }
4856
4857 /**
4858 * Generate (prev x| next x) (20|50|100...) type links for paging
4859 *
4860 * @param Title $title Title object to link
4861 * @param int $offset
4862 * @param int $limit
4863 * @param array $query Optional URL query parameter string
4864 * @param bool $atend Optional param for specified if this is the last page
4865 * @return string
4866 * @deprecated since 1.34, use PrevNextNavigationRenderer::buildPrevNextNavigation()
4867 * instead.
4868 */
4869 public function viewPrevNext( Title $title, $offset, $limit,
4870 array $query = [], $atend = false
4871 ) {
4872 wfDeprecated( __METHOD__, '1.34' );
4873 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4874
4875 # Make 'previous' link
4876 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4877 if ( $offset > 0 ) {
4878 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4879 $query, $prev, 'prevn-title', 'mw-prevlink' );
4880 } else {
4881 $plink = htmlspecialchars( $prev );
4882 }
4883
4884 # Make 'next' link
4885 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4886 if ( $atend ) {
4887 $nlink = htmlspecialchars( $next );
4888 } else {
4889 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4890 $query, $next, 'nextn-title', 'mw-nextlink' );
4891 }
4892
4893 # Make links to set number of items per page
4894 $numLinks = [];
4895 foreach ( [ 20, 50, 100, 250, 500 ] as $num ) {
4896 $numLinks[] = $this->numLink( $title, $offset, $num,
4897 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4898 }
4899
4900 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4901 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4902 }
4903
4904 /**
4905 * Helper function for viewPrevNext() that generates links
4906 *
4907 * @param Title $title Title object to link
4908 * @param int $offset
4909 * @param int $limit
4910 * @param array $query Extra query parameters
4911 * @param string $link Text to use for the link; will be escaped
4912 * @param string $tooltipMsg Name of the message to use as tooltip
4913 * @param string $class Value of the "class" attribute of the link
4914 * @return string HTML fragment
4915 */
4916 private function numLink( Title $title, $offset, $limit, array $query, $link,
4917 $tooltipMsg, $class
4918 ) {
4919 $query = [ 'limit' => $limit, 'offset' => $offset ] + $query;
4920 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4921 ->numParams( $limit )->text();
4922
4923 return Html::element( 'a', [ 'href' => $title->getLocalURL( $query ),
4924 'title' => $tooltip, 'class' => $class ], $link );
4925 }
4926
4927 /**
4928 * Get the conversion rule title, if any.
4929 *
4930 * @return string
4931 */
4932 public function getConvRuleTitle() {
4933 return $this->mConverter->getConvRuleTitle();
4934 }
4935
4936 /**
4937 * Get the compiled plural rules for the language
4938 * @since 1.20
4939 * @return array Associative array with plural form, and plural rule as key-value pairs
4940 */
4941 public function getCompiledPluralRules() {
4942 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4943 $fallbacks = self::getFallbacksFor( $this->mCode );
4944 if ( !$pluralRules ) {
4945 foreach ( $fallbacks as $fallbackCode ) {
4946 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4947 if ( $pluralRules ) {
4948 break;
4949 }
4950 }
4951 }
4952 return $pluralRules;
4953 }
4954
4955 /**
4956 * Get the plural rules for the language
4957 * @since 1.20
4958 * @return array Associative array with plural form number and plural rule as key-value pairs
4959 */
4960 public function getPluralRules() {
4961 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4962 $fallbacks = self::getFallbacksFor( $this->mCode );
4963 if ( !$pluralRules ) {
4964 foreach ( $fallbacks as $fallbackCode ) {
4965 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4966 if ( $pluralRules ) {
4967 break;
4968 }
4969 }
4970 }
4971 return $pluralRules;
4972 }
4973
4974 /**
4975 * Get the plural rule types for the language
4976 * @since 1.22
4977 * @return array Associative array with plural form number and plural rule type as key-value pairs
4978 */
4979 public function getPluralRuleTypes() {
4980 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4981 $fallbacks = self::getFallbacksFor( $this->mCode );
4982 if ( !$pluralRuleTypes ) {
4983 foreach ( $fallbacks as $fallbackCode ) {
4984 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4985 if ( $pluralRuleTypes ) {
4986 break;
4987 }
4988 }
4989 }
4990 return $pluralRuleTypes;
4991 }
4992
4993 /**
4994 * Find the index number of the plural rule appropriate for the given number
4995 * @param int $number
4996 * @return int The index number of the plural rule
4997 */
4998 public function getPluralRuleIndexNumber( $number ) {
4999 $pluralRules = $this->getCompiledPluralRules();
5000 $form = Evaluator::evaluateCompiled( $number, $pluralRules );
5001 return $form;
5002 }
5003
5004 /**
5005 * Find the plural rule type appropriate for the given number
5006 * For example, if the language is set to Arabic, getPluralType(5) should
5007 * return 'few'.
5008 * @since 1.22
5009 * @param int $number
5010 * @return string The name of the plural rule type, e.g. one, two, few, many
5011 */
5012 public function getPluralRuleType( $number ) {
5013 $index = $this->getPluralRuleIndexNumber( $number );
5014 $pluralRuleTypes = $this->getPluralRuleTypes();
5015 return $pluralRuleTypes[$index] ?? 'other';
5016 }
5017 }