Debian Codegraph @

includes/language/Language.php

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