Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
62.18% covered (warning)
62.18%
240 / 386
42.19% covered (danger)
42.19%
27 / 64
CRAP
0.00% covered (danger)
0.00%
0 / 1
WebRequest
62.34% covered (warning)
62.34%
240 / 385
42.19% covered (danger)
42.19%
27 / 64
2097.29
0.00% covered (danger)
0.00%
0 / 1
 __construct
n/a
0 / 0
n/a
0 / 0
1
 getServerInfo
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getPathInfo
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
156
 getRequestPathSuffix
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 detectServer
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
9
 detectProtocol
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 getElapsedTime
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRequestId
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 overrideRequestId
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getProtocol
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 interpolateTitle
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 extractTitle
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 normalizeUnicode
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 getGPCVal
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
6.56
 getRawVal
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getVal
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getText
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setVal
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 unsetVal
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 getArray
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getIntArray
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getInt
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getIntOrNull
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 getFloat
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getBool
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFuzzyBool
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 getCheck
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getValues
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 getValueNames
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getQueryValues
n/a
0 / 0
n/a
0 / 0
1
 getQueryValuesOnly
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPostValues
n/a
0 / 0
n/a
0 / 0
1
 getRawQueryString
n/a
0 / 0
n/a
0 / 0
1
 getRawPostString
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getRawInput
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getMethod
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 wasPosted
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSession
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
7.39
 setSessionId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSessionId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCookie
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
4.02
 getCrossSiteCookie
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getGlobalRequestURL
30.00% covered (danger)
30.00%
6 / 20
0.00% covered (danger)
0.00%
0 / 1
44.30
 getRequestURL
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFullRequestURL
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 appendQueryValue
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 appendQueryArray
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 getLimitOffsetForUser
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
56
 getFileTempname
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUploadError
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getFileName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUpload
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 response
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 initHeaders
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getAllHeaders
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getHeader
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 getSessionData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 setSessionData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAcceptLang
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
5
 getRawIP
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 getIP
92.50% covered (success)
92.50%
37 / 40
0.00% covered (danger)
0.00%
0 / 1
16.11
 canonicalizeIPv6LoopbackAddress
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 setIP
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 hasSafeMethod
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 isSafeRequest
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 markAsSafeRequest
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 matchURLForCDN
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
8
 getSecurityLogContext
92.86% covered (success)
92.86%
26 / 28
0.00% covered (danger)
0.00%
0 / 1
7.02
1<?php
2/**
3 * Deal with importing all those nasty globals and things
4 *
5 * Copyright Â© 2003 Brooke Vibber <bvibber@wikimedia.org>
6 * https://www.mediawiki.org/
7 *
8 * @license GPL-2.0-or-later
9 * @file
10 */
11
12namespace MediaWiki\Request;
13
14use MediaWiki\Exception\FatalError;
15use MediaWiki\Exception\MWException;
16use MediaWiki\Hook\GetSecurityLogContextHook;
17use MediaWiki\HookContainer\HookRunner;
18use MediaWiki\Http\Telemetry;
19use MediaWiki\MainConfigNames;
20use MediaWiki\MediaWikiServices;
21use MediaWiki\Session\Session;
22use MediaWiki\Session\SessionId;
23use MediaWiki\User\UserIdentity;
24use Wikimedia\IPUtils;
25use Wikimedia\ObjectCache\HashBagOStuff;
26
27// The point of this class is to be a wrapper around super globals
28// phpcs:disable MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
29
30/**
31 * The WebRequest class encapsulates getting at data passed in the
32 * URL or via a POSTed form, stripping illegal input characters, and
33 * normalizing Unicode sequences. This class should be used instead
34 * of accessing globals such as $_GET, $_POST, and $_COOKIE.
35 *
36 * @ingroup HTTP
37 */
38class WebRequest {
39    /**
40     * The parameters from $_GET, $_POST and the path router
41     * @var array
42     */
43    protected $data;
44
45    /**
46     * The parameters from $_GET. The parameters from the path router are
47     * added by interpolateTitle() during Setup.php.
48     * @var (string|string[])[]
49     */
50    protected $queryAndPathParams;
51
52    /**
53     * The parameters from $_GET only.
54     * @var (string|string[])[]
55     */
56    protected $queryParams;
57
58    /**
59     * The values from $_POST only.
60     * @var (string|string[])[]
61     */
62    protected $postParams;
63
64    /**
65     * Lazy-initialized request headers indexed by upper-case header name
66     * @var string[]
67     */
68    protected $headers = [];
69
70    /**
71     * Flag to make WebRequest::getHeader return an array of values.
72     * @since 1.26
73     */
74    public const GETHEADER_LIST = 1;
75
76    /**
77     * Lazy-init response object
78     * @var WebResponse|null
79     */
80    protected ?WebResponse $response = null;
81
82    /**
83     * Cached client IP address
84     * @var string
85     */
86    private $ip;
87
88    /**
89     * The timestamp of the start of the request, with microsecond precision.
90     * @var float
91     */
92    protected $requestTime;
93
94    /**
95     * Cached URL protocol
96     * @var string
97     */
98    protected $protocol;
99
100    /**
101     * @var SessionId|null Session ID to use for this request.
102     */
103    protected ?SessionId $sessionId = null;
104    /**
105     * @var Session|null Session to use for this request.
106     */
107    protected ?Session $session = null;
108
109    /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
110    protected $markedAsSafe = false;
111
112    /** Cache variable for getSecurityLogContext(). */
113    private ?HashBagOStuff $securityLogContext;
114
115    /**
116     * @codeCoverageIgnore
117     */
118    public function __construct() {
119        $this->requestTime = $_SERVER['REQUEST_TIME_FLOAT'];
120
121        // POST overrides GET data
122        // We don't use $_REQUEST here to avoid interference from cookies...
123        $this->data = $_POST + $_GET;
124
125        $this->postParams = $_POST;
126        $this->queryAndPathParams = $this->queryParams = $_GET;
127    }
128
129    /**
130     * Returns an entry from the $_SERVER array.
131     * This exists mainly to allow us to inject fake values for testing.
132     *
133     * @param string $name A well known key for $_SERVER,
134     *        see <https://www.php.net/manual/en/reserved.variables.server.php>.
135     *        Only fields that contain string values are supported,
136     *        so 'argv' and 'argc' are not safe to use.
137     * @param ?string $default The value to return if no value is known for the
138     *        key $name.
139     *
140     * @return ?string
141     */
142    protected function getServerInfo( string $name, ?string $default = null ): ?string {
143        return isset( $_SERVER[$name] ) ? (string)$_SERVER[$name] : $default;
144    }
145
146    /**
147     * Extract relevant query arguments from the http request uri's path
148     * to be merged with the normal php provided query arguments.
149     * Tries to use the REQUEST_URI data if available and parses it
150     * according to the wiki's configuration looking for any known pattern.
151     *
152     * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
153     * provided by the server if any and use that to set a 'title' parameter.
154     *
155     * This internal method handles many odd cases and is tailored specifically for
156     * used by WebRequest::interpolateTitle, for index.php requests.
157     * Consider using WebRequest::getRequestPathSuffix for other path-related use cases.
158     *
159     * @param string $want If this is not 'all', then the function
160     * will return an empty array if it determines that the URL is
161     * inside a rewrite path.
162     *
163     * @return string[] Any query arguments found in path matches.
164     * @throws FatalError If invalid routes are configured (T48998)
165     */
166    protected function getPathInfo( $want = 'all' ) {
167        // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
168        // And also by Apache 2.x, double slashes are converted to single slashes.
169        // So we will use REQUEST_URI if possible.
170        $url = $this->getServerInfo( 'REQUEST_URI' );
171        if ( $url !== null ) {
172            // Slurp out the path portion to examine...
173            if ( !preg_match( '!^https?://!', $url ) ) {
174                $url = 'http://unused' . $url;
175            }
176            $a = parse_url( $url );
177            if ( !$a ) {
178                return [];
179            }
180            $path = $a['path'] ?? '';
181
182            global $wgScript;
183            if ( $path == $wgScript && $want !== 'all' ) {
184                // Script inside a rewrite path?
185                // Abort to keep from breaking...
186                return [];
187            }
188
189            $router = new PathRouter;
190
191            // Raw PATH_INFO style
192            $router->add( "$wgScript/$1" );
193
194            global $wgArticlePath;
195            if ( $wgArticlePath ) {
196                $router->validateRoute( $wgArticlePath, 'wgArticlePath' );
197                $router->add( $wgArticlePath );
198            }
199
200            global $wgActionPaths;
201            $articlePaths = PathRouter::getActionPaths( $wgActionPaths, $wgArticlePath );
202            if ( $articlePaths ) {
203                $router->add( $articlePaths, [ 'action' => '$key' ] );
204            }
205
206            $services = MediaWikiServices::getInstance();
207            global $wgVariantArticlePath;
208            if ( $wgVariantArticlePath ) {
209                $router->validateRoute( $wgVariantArticlePath, 'wgVariantArticlePath' );
210                $router->add( $wgVariantArticlePath,
211                    [ 'variant' => '$2' ],
212                    [ '$2' => $services->getLanguageConverterFactory()
213                        ->getLanguageConverter( $services->getContentLanguage() )
214                        ->getVariants() ]
215                );
216            }
217
218            ( new HookRunner( $services->getHookContainer() ) )->onWebRequestPathInfoRouter( $router );
219
220            $matches = $router->parse( $path );
221        } else {
222            global $wgUsePathInfo;
223            $matches = [];
224            if ( $wgUsePathInfo ) {
225                $origPathInfo = $this->getServerInfo( 'ORIG_PATH_INFO' ) ?? '';
226                $pathInfo = $this->getServerInfo( 'PATH_INFO' ) ?? '';
227                if ( $origPathInfo !== '' ) {
228                    // Mangled PATH_INFO
229                    // https://bugs.php.net/bug.php?id=31892
230                    // Also reported when ini_get('cgi.fix_pathinfo')==false
231                    $matches['title'] = substr( $origPathInfo, 1 );
232                } elseif ( $pathInfo !== '' ) {
233                    // Regular old PATH_INFO yay
234                    $matches['title'] = substr( $pathInfo, 1 );
235                }
236            }
237        }
238
239        return $matches;
240    }
241
242    /**
243     * If the request URL matches a given base path, extract the path part of
244     * the request URL after that base, and decode escape sequences in it.
245     *
246     * If the request URL does not match, false is returned.
247     *
248     * @since 1.35
249     * @param string $basePath The base URL path. Trailing slashes will be
250     *   stripped.
251     * @param ?string $requestUrl The request URL to examine. If not given, the
252     *   URL returned by getGlobalRequestURL() will be used.
253     * @return string|false
254     */
255    public static function getRequestPathSuffix( string $basePath, ?string $requestUrl = null ) {
256        $basePath = rtrim( $basePath, '/' ) . '/';
257        $requestUrl ??= self::getGlobalRequestURL();
258        $qpos = strpos( $requestUrl, '?' );
259        if ( $qpos !== false ) {
260            $requestPath = substr( $requestUrl, 0, $qpos );
261        } else {
262            $requestPath = $requestUrl;
263        }
264        if ( !str_starts_with( $requestPath, $basePath ) ) {
265            return false;
266        }
267        return rawurldecode( substr( $requestPath, strlen( $basePath ) ) );
268    }
269
270    /**
271     * Work out an appropriate URL prefix containing scheme and host, based on
272     * information detected from $_SERVER
273     *
274     * @param bool|null $assumeProxiesUseDefaultProtocolPorts When the wiki is running behind a proxy
275     * and this is set to true, assumes that the proxy exposes the wiki on the standard ports
276     * (443 for https and 80 for http). Added in 1.38. Calls without this argument are
277     * supported for backwards compatibility but deprecated.
278     *
279     * @return string
280     */
281    public static function detectServer( $assumeProxiesUseDefaultProtocolPorts = null ) {
282        $assumeProxiesUseDefaultProtocolPorts ??= $GLOBALS['wgAssumeProxiesUseDefaultProtocolPorts'];
283
284        $proto = self::detectProtocol();
285        $stdPort = $proto === 'https' ? 443 : 80;
286
287        $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
288        $host = 'localhost';
289        $port = $stdPort;
290        foreach ( $varNames as $varName ) {
291            if ( !isset( $_SERVER[$varName] ) ) {
292                continue;
293            }
294
295            $parts = IPUtils::splitHostAndPort( $_SERVER[$varName] );
296            if ( !$parts ) {
297                // Invalid, do not use
298                continue;
299            }
300
301            $host = $parts[0];
302            if ( $assumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
303                // T72021: Assume that upstream proxy is running on the default
304                // port based on the protocol. We have no reliable way to determine
305                // the actual port in use upstream.
306                $port = $stdPort;
307            } elseif ( $parts[1] === false ) {
308                if ( isset( $_SERVER['SERVER_PORT'] ) ) {
309                    $port = intval( $_SERVER['SERVER_PORT'] );
310                } // else leave it as $stdPort
311            } else {
312                $port = $parts[1];
313            }
314            break;
315        }
316
317        return $proto . '://' . IPUtils::combineHostAndPort( $host, $port, $stdPort );
318    }
319
320    /**
321     * Detect the protocol from $_SERVER.
322     * This is for use prior to Setup.php, when no WebRequest object is available.
323     * At other times, use the non-static function getProtocol().
324     *
325     * @return string
326     */
327    public static function detectProtocol() {
328        if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
329            ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
330            $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
331            return 'https';
332        } else {
333            return 'http';
334        }
335    }
336
337    /**
338     * Get the number of seconds to have elapsed since request start,
339     * in fractional seconds, with microsecond resolution.
340     *
341     * @return float
342     * @since 1.25
343     */
344    public function getElapsedTime() {
345        return microtime( true ) - $this->requestTime;
346    }
347
348    /**
349     * Get the current request ID.
350     *
351     * This is usually based on the `X-Request-Id` header, or the `UNIQUE_ID`
352     * environment variable, falling back to (process cached) randomly-generated string.
353     *
354     * @return string
355     * @since 1.27
356     */
357    public static function getRequestId() {
358        return Telemetry::getInstance()->getRequestId();
359    }
360
361    /**
362     * Override the unique request ID. This is for sub-requests, such as jobs,
363     * that wish to use the same id but are not part of the same execution context.
364     *
365     * @param string|null $newId
366     * @since 1.27
367     */
368    public static function overrideRequestId( $newId ) {
369        $telemetry = Telemetry::getInstance();
370        if ( $newId === null ) {
371            $telemetry->regenerateRequestId();
372        } else {
373            $telemetry->overrideRequestId( $newId );
374        }
375    }
376
377    /**
378     * Get the current URL protocol (http or https)
379     * @return string
380     */
381    public function getProtocol() {
382        $this->protocol ??= self::detectProtocol();
383        return $this->protocol;
384    }
385
386    /**
387     * Check for title, action, and/or variant data in the URL
388     * and interpolate it into the GET variables.
389     * This should only be run after the content language is available,
390     * as we may need the list of language variants to determine
391     * available variant URLs.
392     */
393    public function interpolateTitle() {
394        $matches = $this->getPathInfo( 'title' );
395        foreach ( $matches as $key => $val ) {
396            $this->data[$key] = $this->queryAndPathParams[$key] = $val;
397        }
398    }
399
400    /**
401     * URL rewriting function; tries to extract page title and,
402     * optionally, one other fixed parameter value from a URL path.
403     *
404     * @param string $path The URL path given from the client
405     * @param array $bases One or more URLs, optionally with $1 at the end
406     * @param string|false $key If provided, the matching key in $bases will be
407     *    passed on as the value of this URL parameter
408     * @return array Array of URL variables to interpolate; empty if no match
409     */
410    public static function extractTitle( $path, $bases, $key = false ) {
411        foreach ( (array)$bases as $keyValue => $base ) {
412            // Find the part after $wgArticlePath
413            $base = str_replace( '$1', '', $base );
414            if ( str_starts_with( $path, $base ) ) {
415                $raw = substr( $path, strlen( $base ) );
416                if ( $raw !== '' ) {
417                    $matches = [ 'title' => rawurldecode( $raw ) ];
418                    if ( $key ) {
419                        $matches[$key] = $keyValue;
420                    }
421                    return $matches;
422                }
423            }
424        }
425        return [];
426    }
427
428    /**
429     * Recursively normalizes UTF-8 strings in the given array.
430     *
431     * @param string|array $data
432     * @return array|string Cleaned-up version of the given
433     * @internal
434     */
435    public function normalizeUnicode( $data ) {
436        if ( is_array( $data ) ) {
437            foreach ( $data as $key => $val ) {
438                $data[$key] = $this->normalizeUnicode( $val );
439            }
440        } else {
441            $contLang = MediaWikiServices::getInstance()->getContentLanguage();
442            $data = $contLang->normalize( $data );
443        }
444        return $data;
445    }
446
447    /**
448     * Fetch a value from the given array or return $default if it's not set.
449     *
450     * @param array $arr
451     * @param string $name
452     * @param mixed $default
453     * @return mixed
454     * @return-taint tainted
455     */
456    private function getGPCVal( $arr, $name, $default ) {
457        # PHP is so nice to not touch input data, except sometimes:
458        # https://www.php.net/variables.external#language.variables.external.dot-in-names
459        # Work around PHP *feature* to avoid *bugs* elsewhere.
460        $name = strtr( $name, '.', '_' );
461
462        if ( !isset( $arr[$name] ) ) {
463            return $default;
464        }
465
466        $data = $arr[$name];
467        # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
468        $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
469        if ( !$isAsciiStr ) {
470            if ( isset( $_GET[$name] ) && is_string( $data ) ) {
471                # Check for alternate/legacy character encoding.
472                $data = MediaWikiServices::getInstance()
473                    ->getContentLanguage()
474                    ->checkTitleEncoding( $data );
475            }
476            $data = $this->normalizeUnicode( $data );
477        }
478
479        return $data;
480    }
481
482    /**
483     * Fetch a string from this web request's $_GET, $_POST or path router vars WITHOUT any
484     * Unicode or line break normalization. This is a fast alternative for values that are known
485     * to be simple, e.g. pure ASCII. When reading user input, use {@see getText} instead.
486     *
487     * Array values are discarded for security reasons. Use {@see getArray} or {@see getIntArray}.
488     *
489     * @since 1.28
490     * @param string $name
491     * @return string|null The value, or null if none set
492     * @return-taint tainted
493     */
494    public function getRawVal( $name ): ?string {
495        $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
496        if ( !isset( $this->data[$name] ) || is_array( $this->data[$name] ) ) {
497            return null;
498        }
499        return (string)$this->data[$name];
500    }
501
502    /**
503     * Fetch a text string from this web request's $_GET, $_POST or path router vars and partially
504     * normalize it.
505     *
506     * Use of this method is discouraged. It doesn't normalize line breaks and defaults to null
507     * instead of the empty string. Instead:
508     * - Use {@see getText} when reading user input or form fields that are expected to contain
509     *   non-ASCII characters.
510     * - Use {@see getRawVal} when reading ASCII strings, such as parameters used to select
511     *   predefined behaviour in the software.
512     *
513     * Array values are discarded for security reasons. Use {@see getArray} or {@see getIntArray}.
514     *
515     * @param string $name
516     * @param string|null $default
517     * @return string|null The input value, or $default if none set
518     * @return-taint tainted
519     */
520    public function getVal( $name, $default = null ) {
521        $val = $this->getGPCVal( $this->data, $name, $default );
522        if ( is_array( $val ) ) {
523            $val = $default;
524        }
525
526        return $val === null ? null : (string)$val;
527    }
528
529    /**
530     * Fetch a text string from this web request's $_GET, $_POST or path router vars and return it
531     * in normalized form.
532     *
533     * This normalizes Unicode sequences (via {@see getGPCVal}) and line breaks.
534     *
535     * This should be used for all user input and form fields that are expected to contain non-ASCII
536     * characters, especially if the value will be stored or compared against stored values. Without
537     * normalization, logically identically values might not match when they are typed on different
538     * OS' or keyboards.
539     *
540     * Array values are discarded for security reasons. Use {@see getArray} or {@see getIntArray}.
541     *
542     * @param string $name
543     * @param string $default
544     * @return string The normalized input value, or $default if none set
545     * @return-taint tainted
546     */
547    public function getText( $name, $default = '' ) {
548        $val = $this->getVal( $name, $default );
549        return str_replace( "\r\n", "\n", $val );
550    }
551
552    /**
553     * Set an arbitrary value into our get/post data. Values set using this
554     * method will be available vis getVal() and getValues() but not
555     * getQueryValues() or getPostValues().
556     *
557     * @param string $key Key name to use
558     * @param mixed $value Value to set
559     * @return mixed Old value if one was present, null otherwise
560     */
561    public function setVal( $key, $value ) {
562        $ret = $this->data[$key] ?? null;
563        $this->data[$key] = $value;
564        return $ret;
565    }
566
567    /**
568     * Unset an arbitrary value from our get/post data.
569     *
570     * @param string $key Key name to use
571     * @return mixed Old value if one was present, null otherwise
572     */
573    public function unsetVal( $key ) {
574        if ( !isset( $this->data[$key] ) ) {
575            $ret = null;
576        } else {
577            $ret = $this->data[$key];
578            unset( $this->data[$key] );
579        }
580        return $ret;
581    }
582
583    /**
584     * Fetch an array from this web request's $_GET, $_POST or path router vars,
585     * or return $default if it's not set. If source was scalar, will return an
586     * array with a single element. If no source and no default, returns null.
587     *
588     * @param string $name
589     * @param array|null $default Optional default (or null)
590     * @return array|null
591     * @return-taint tainted
592     */
593    public function getArray( $name, $default = null ) {
594        $val = $this->getGPCVal( $this->data, $name, $default );
595        if ( $val === null ) {
596            return null;
597        } else {
598            return (array)$val;
599        }
600    }
601
602    /**
603     * Fetch an array of integers from this web request's $_GET, $_POST or
604     * path router vars, or return $default if it's not set. If source was
605     * scalar, will return an array with a single element. If no source and
606     * no default, returns null. If an array is returned, contents are
607     * guaranteed to be integers.
608     *
609     * @param string $name
610     * @param array|null $default Option default (or null)
611     * @return int[]|null
612     * @return-taint none
613     */
614    public function getIntArray( $name, $default = null ) {
615        $val = $this->getArray( $name, $default );
616        if ( is_array( $val ) ) {
617            // Drop multi-dimensional array elements
618            $val = array_map( intval( ... ), array_filter( $val, is_string( ... ) ) );
619        }
620        return $val;
621    }
622
623    /**
624     * Fetch an integer value from this web request's $_GET, $_POST or
625     * path router vars, or return $default if not set. Guaranteed to return
626     * an integer; non-numeric input will typically return 0.
627     *
628     * @param string $name
629     * @param int $default
630     * @return int
631     */
632    public function getInt( $name, $default = 0 ): int {
633        return intval( $this->getRawVal( $name ) ?? $default );
634    }
635
636    /**
637     * Fetch an integer value from this web request's $_GET, $_POST or
638     * path router vars, or return null if empty. Guaranteed to return an
639     * integer or null; non-numeric input will typically return null.
640     *
641     * @param string $name
642     * @return int|null
643     */
644    public function getIntOrNull( $name ): ?int {
645        $val = $this->getRawVal( $name );
646        return is_numeric( $val ) ? intval( $val ) : null;
647    }
648
649    /**
650     * Fetch a floating point value from this web request's $_GET, $_POST
651     * or path router vars, or return $default if not set. Guaranteed to
652     * return a float; non-numeric input will typically return 0.
653     *
654     * @since 1.23
655     * @param string $name
656     * @param float $default
657     * @return float
658     */
659    public function getFloat( $name, $default = 0.0 ): float {
660        return floatval( $this->getRawVal( $name ) ?? $default );
661    }
662
663    /**
664     * Fetch a boolean value from this web request's $_GET, $_POST or path
665     * router vars or return $default if not set. Guaranteed to return true
666     * or false, with normal PHP semantics for boolean interpretation of strings.
667     *
668     * @param string $name
669     * @param bool $default
670     * @return bool
671     */
672    public function getBool( $name, $default = false ): bool {
673        return (bool)( $this->getRawVal( $name ) ?? $default );
674    }
675
676    /**
677     * Fetch a boolean value from this web request's $_GET, $_POST or path router
678     * vars or return $default if not set. Unlike getBool, the string "false" will
679     * result in boolean false, which is useful when interpreting information sent
680     * from JavaScript.
681     *
682     * @param string $name
683     * @param bool $default
684     * @return bool
685     */
686    public function getFuzzyBool( $name, $default = false ): bool {
687        $value = $this->getRawVal( $name );
688        if ( $value === null ) {
689            return (bool)$default;
690        }
691
692        return $value && strcasecmp( $value, 'false' ) !== 0;
693    }
694
695    /**
696     * Return true if the named value is set in this web request's $_GET,
697     * $_POST or path router vars, whatever that value is (even "0").
698     * Return false if the named value is not set. Example use is checking
699     * for the presence of check boxes in forms.
700     *
701     * @param string $name
702     * @return bool
703     */
704    public function getCheck( $name ): bool {
705        # Checkboxes and buttons are only present when clicked
706        # Presence connotes truth, absence false
707        return $this->getRawVal( $name ) !== null;
708    }
709
710    /**
711     * Extracts the (given) named values from this web request's $_GET, $_POST or path
712     * router vars into an array. No transformation is performed on the values.
713     *
714     * @param string ...$names If no arguments are given, returns all input values
715     * @return array
716     * @return-taint tainted
717     */
718    public function getValues( ...$names ) {
719        if ( $names === [] ) {
720            $names = array_keys( $this->data );
721        }
722
723        $retVal = [];
724        foreach ( $names as $name ) {
725            $value = $this->getGPCVal( $this->data, $name, null );
726            if ( $value !== null ) {
727                $retVal[$name] = $value;
728            }
729        }
730        return $retVal;
731    }
732
733    /**
734     * Returns the names of this web request's $_GET, $_POST or path router vars,
735     * excluding those in $exclude.
736     *
737     * @param array $exclude
738     * @return array
739     * @return-taint tainted
740     */
741    public function getValueNames( $exclude = [] ) {
742        return array_diff( array_keys( $this->getValues() ), $exclude );
743    }
744
745    /**
746     * Get the values passed in $_GET and the path router parameters.
747     * No transformation is performed on the values.
748     *
749     * @codeCoverageIgnore
750     * @return (string|string[])[] Might contain arrays in case there was a `&param[]=…` parameter
751     * @return-taint tainted
752     */
753    public function getQueryValues() {
754        return $this->queryAndPathParams;
755    }
756
757    /**
758     * Get the values passed in $_GET only, not including the path
759     * router parameters. This is less suitable for self-links to index.php but
760     * useful for other entry points. No transformation is performed on the
761     * values.
762     *
763     * @since 1.34
764     * @return (string|string[])[] Might contain arrays in case there was a `&param[]=…` parameter
765     */
766    public function getQueryValuesOnly() {
767        return $this->queryParams;
768    }
769
770    /**
771     * Get the values passed via POST.
772     * No transformation is performed on the values.
773     *
774     * @since 1.32
775     * @codeCoverageIgnore
776     * @return (string|string[])[] Might contain arrays in case there was a `&param[]=…` parameter
777     */
778    public function getPostValues() {
779        return $this->postParams;
780    }
781
782    /**
783     * Return the contents of the URL query string with no decoding. Use when you need to
784     * know exactly what was sent, e.g. for an OAuth signature over the elements.
785     *
786     * @codeCoverageIgnore
787     * @return string
788     * @return-taint tainted
789     */
790    public function getRawQueryString() {
791        return $this->getServerInfo( 'QUERY_STRING' ) ?? '';
792    }
793
794    /**
795     * Return the contents of the POST with no decoding. Use when you need to
796     * know exactly what was sent, e.g. for an OAuth signature over the elements.
797     *
798     * @return string
799     * @return-taint tainted
800     */
801    public function getRawPostString() {
802        if ( !$this->wasPosted() ) {
803            return '';
804        }
805        return $this->getRawInput();
806    }
807
808    /**
809     * Return the raw request body, with no processing. Cached since some methods
810     * disallow reading the stream more than once. As stated in the php docs, this
811     * does not work with enctype="multipart/form-data".
812     *
813     * @return string
814     * @return-taint tainted
815     */
816    public function getRawInput() {
817        static $input = null;
818        $input ??= file_get_contents( 'php://input' );
819        return $input;
820    }
821
822    /**
823     * Get the HTTP method used for this request.
824     *
825     * @return string
826     */
827    public function getMethod() {
828        return $this->getServerInfo( 'REQUEST_METHOD' ) ?: 'GET';
829    }
830
831    /**
832     * Returns true if the present request was reached by a POST operation,
833     * false otherwise (GET, HEAD, or command-line).
834     *
835     * Note that values retrieved by the object may come from the
836     * GET URL etc even on a POST request.
837     *
838     * @return bool
839     */
840    public function wasPosted() {
841        return $this->getMethod() == 'POST';
842    }
843
844    /**
845     * Return the session for this request
846     *
847     * This might unpersist an existing session if it was invalid.
848     *
849     * @since 1.27
850     * @return Session
851     */
852    public function getSession(): Session {
853        $sessionId = $this->getSessionId();
854        $sessionManager = MediaWikiServices::getInstance()->getSessionManager();
855
856        // Destroy the old session if someone has set a new session ID
857        if ( $this->session && $sessionId && $this->session->getId() !== $sessionId->getId() ) {
858            $this->session = null;
859        }
860
861        // Look up session by ID if provided
862        if ( !$this->session && $sessionId ) {
863            $this->session = $sessionManager->getSessionById( $sessionId->getId(), true, $this );
864        }
865
866        // If it was not provided, or a session with that ID doesn't exist, create a new one
867        if ( !$this->session ) {
868            $this->session = $sessionManager->getSessionForRequest( $this );
869            $this->sessionId = $this->session->getSessionId();
870        }
871        return $this->session;
872    }
873
874    /**
875     * Set the session for this request
876     * @since 1.27
877     * @internal For use by MediaWiki\Session classes only
878     * @param SessionId $sessionId
879     */
880    public function setSessionId( SessionId $sessionId ) {
881        $this->sessionId = $sessionId;
882    }
883
884    /**
885     * Get the session id for this request, if any
886     * @since 1.27
887     * @internal For use by MediaWiki\Session classes only
888     * @return SessionId|null
889     */
890    public function getSessionId() {
891        return $this->sessionId;
892    }
893
894    /**
895     * Get a cookie from the $_COOKIE jar
896     *
897     * @param string $key The name of the cookie
898     * @param string|null $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
899     * @param mixed|null $default What to return if the value isn't found
900     * @return mixed Cookie value or $default if the cookie not set
901     * @return-taint tainted
902     */
903    public function getCookie( $key, $prefix = null, $default = null ) {
904        if ( $prefix === null ) {
905            global $wgCookiePrefix;
906            $prefix = $wgCookiePrefix;
907        }
908        $name = $prefix . $key;
909        // Work around mangling of $_COOKIE
910        $name = strtr( $name, '.', '_' );
911        if ( isset( $_COOKIE[$name] ) ) {
912            // For duplicate cookies in the format of name[]=value;name[]=value2,
913            // PHP will assign an array value for the 'name' cookie in $_COOKIE.
914            // Neither RFC 6265 nor its preceding RFCs define such behavior,
915            // and MediaWiki does not rely on it either, so treat the cookie as absent if so (T363980).
916            if ( is_array( $_COOKIE[$name] ) ) {
917                return $default;
918            }
919            return $_COOKIE[$name];
920        } else {
921            return $default;
922        }
923    }
924
925    /**
926     * Get a cookie set with SameSite=None.
927     *
928     * @deprecated since 1.42 use getCookie(), but note the different $prefix default
929     *
930     * @param string $key The name of the cookie
931     * @param string $prefix A prefix to use, empty by default
932     * @param mixed|null $default What to return if the value isn't found
933     * @return mixed Cookie value or $default if the cookie is not set
934     */
935    public function getCrossSiteCookie( $key, $prefix = '', $default = null ) {
936        wfDeprecated( __METHOD__, '1.42' );
937        return $this->getCookie( $key, $prefix, $default );
938    }
939
940    /**
941     * Return the path and query string portion of the main request URI.
942     * This will be suitable for use as a relative link in HTML output.
943     *
944     * @throws MWException
945     * @return string
946     * @return-taint tainted
947     */
948    public static function getGlobalRequestURL() {
949        // This method is called on fatal errors; it should not depend on anything complex.
950
951        if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
952            $base = $_SERVER['REQUEST_URI'];
953        } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
954            && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
955        ) {
956            // Probably IIS; doesn't set REQUEST_URI
957            $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
958        } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
959            $base = $_SERVER['SCRIPT_NAME'];
960            if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
961                $base .= '?' . $_SERVER['QUERY_STRING'];
962            }
963        } else {
964            // This shouldn't happen!
965            throw new MWException(
966                "Web server doesn't provide either " .
967                "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
968                "of your web server configuration to https://phabricator.wikimedia.org/"
969            );
970        }
971        // User-agents should not send a fragment with the URI, but
972        // if they do, and the web server passes it on to us, we
973        // need to strip it or we get false-positive redirect loops
974        // or weird output URLs
975        $hash = strpos( $base, '#' );
976        if ( $hash !== false ) {
977            $base = substr( $base, 0, $hash );
978        }
979
980        if ( $base[0] == '/' ) {
981            // More than one slash will look like it is protocol relative
982            return preg_replace( '!^/+!', '/', $base );
983        } else {
984            // We may get paths with a host prepended; strip it.
985            return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
986        }
987    }
988
989    /**
990     * Return the path and query string portion of the request URI.
991     * This will be suitable for use as a relative link in HTML output.
992     *
993     * @throws MWException
994     * @return string
995     * @return-taint tainted
996     */
997    public function getRequestURL() {
998        return self::getGlobalRequestURL();
999    }
1000
1001    /**
1002     * Return the request URI with the canonical service and hostname, path,
1003     * and query string. This will be suitable for use as an absolute link
1004     * in HTML or other output.
1005     *
1006     * If $wgServer is protocol-relative, this will return a fully
1007     * qualified URL with the protocol of this request object.
1008     *
1009     * @return string
1010     * @return-taint tainted
1011     */
1012    public function getFullRequestURL() {
1013        $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
1014        // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
1015        // do not rely on state from the global $wgRequest object (which it would,
1016        // via UrlUtils::getServer()/UrlUtils::expand()/$wgRequest->protocol).
1017        if ( $this->getProtocol() === 'http' ) {
1018            return ( $urlUtils->getServer( PROTO_HTTP ) ?? '' ) . $this->getRequestURL();
1019        } else {
1020            return ( $urlUtils->getServer( PROTO_HTTPS ) ?? '' ) . $this->getRequestURL();
1021        }
1022    }
1023
1024    /**
1025     * @param string $key
1026     * @param string $value
1027     * @return string
1028     */
1029    public function appendQueryValue( $key, $value ) {
1030        return $this->appendQueryArray( [ $key => $value ] );
1031    }
1032
1033    /**
1034     * Appends or replaces value of query variables.
1035     *
1036     * @param array $array Array of values to replace/add to query
1037     * @return string
1038     */
1039    public function appendQueryArray( $array ) {
1040        $newquery = $this->getQueryValues();
1041        unset( $newquery['title'] );
1042        $newquery = array_merge( $newquery, $array );
1043
1044        return wfArrayToCgi( $newquery );
1045    }
1046
1047    /**
1048     * Check for limit and offset parameters on the input, and return sensible
1049     * defaults if not given. The limit must be positive and is capped at 5000.
1050     * Offset must be positive but is not capped.
1051     *
1052     * @param UserIdentity $user UserIdentity to get option for
1053     * @param int $deflimit Limit to use if no input and the user hasn't set the option.
1054     * @param string $optionname To specify an option other than rclimit to pull from.
1055     * @return int[] First element is limit, second is offset
1056     */
1057    public function getLimitOffsetForUser( UserIdentity $user, $deflimit = 50, $optionname = 'rclimit' ) {
1058        $limit = $this->getInt( 'limit', 0 );
1059        if ( $limit < 0 ) {
1060            $limit = 0;
1061        }
1062        if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
1063            $limit = MediaWikiServices::getInstance()
1064                ->getUserOptionsLookup()
1065                ->getIntOption( $user, $optionname );
1066        }
1067        if ( $limit <= 0 ) {
1068            $limit = $deflimit;
1069        }
1070        if ( $limit > 5000 ) {
1071            $limit = 5000; # We have *some* limits...
1072        }
1073
1074        $offset = $this->getInt( 'offset', 0 );
1075        if ( $offset < 0 ) {
1076            $offset = 0;
1077        }
1078
1079        return [ $limit, $offset ];
1080    }
1081
1082    /**
1083     * Return the path to the temporary file where PHP has stored the upload.
1084     *
1085     * @param string $key
1086     * @return string|null String or null if no such file.
1087     */
1088    public function getFileTempname( $key ) {
1089        return $this->getUpload( $key )->getTempName();
1090    }
1091
1092    /**
1093     * Return the upload error or 0
1094     *
1095     * @param string $key
1096     * @return int
1097     */
1098    public function getUploadError( $key ) {
1099        return $this->getUpload( $key )->getError();
1100    }
1101
1102    /**
1103     * Return the original filename of the uploaded file, as reported by
1104     * the submitting user agent. HTML-style character entities are
1105     * interpreted and normalized to Unicode normalization form C, in part
1106     * to deal with weird input from Safari with non-ASCII filenames.
1107     *
1108     * Other than this the name is not verified for being a safe filename.
1109     *
1110     * @param string $key
1111     * @return string|null String or null if no such file.
1112     */
1113    public function getFileName( $key ) {
1114        return $this->getUpload( $key )->getName();
1115    }
1116
1117    /**
1118     * Return a MediaWiki\Request\WebRequestUpload object corresponding to the key
1119     *
1120     * @param string $key
1121     * @return WebRequestUpload
1122     */
1123    public function getUpload( $key ) {
1124        return new WebRequestUpload( $this, $key );
1125    }
1126
1127    /**
1128     * Return a handle to WebResponse style object, for setting cookies,
1129     * headers and other stuff, for Request being worked on.
1130     */
1131    public function response(): WebResponse {
1132        /* Lazy initialization of response object for this request */
1133        if ( !$this->response ) {
1134            $this->response = new WebResponse();
1135        }
1136        return $this->response;
1137    }
1138
1139    /**
1140     * Initialise the header list
1141     */
1142    protected function initHeaders() {
1143        if ( count( $this->headers ) ) {
1144            return;
1145        }
1146
1147        $this->headers = array_change_key_case( getallheaders(), CASE_UPPER );
1148    }
1149
1150    /**
1151     * Get an array containing all request headers
1152     *
1153     * @return string[] Mapping header name to its value
1154     * @return-taint tainted
1155     */
1156    public function getAllHeaders() {
1157        $this->initHeaders();
1158        return $this->headers;
1159    }
1160
1161    /**
1162     * Get a request header, or false if it isn't set.
1163     *
1164     * @param string $name Case-insensitive header name
1165     * @param int $flags Bitwise combination of:
1166     *   WebRequest::GETHEADER_LIST  Treat the header as a comma-separated list
1167     *                               of values, as described in RFC 2616 Â§ 4.2.
1168     *                               (since 1.26).
1169     * @return string|string[]|false False if header is unset; otherwise the
1170     *  header value(s) as either a string (the default) or an array, if
1171     *  WebRequest::GETHEADER_LIST flag was set.
1172     * @return-taint tainted
1173     */
1174    public function getHeader( $name, $flags = 0 ) {
1175        $this->initHeaders();
1176        $name = strtoupper( $name );
1177        if ( !isset( $this->headers[$name] ) ) {
1178            return false;
1179        }
1180        $value = $this->headers[$name];
1181        if ( $flags & self::GETHEADER_LIST ) {
1182            $value = array_map( 'trim', explode( ',', $value ) );
1183        }
1184        return $value;
1185    }
1186
1187    /**
1188     * Get data from the session
1189     *
1190     * @note Prefer $this->getSession() instead if making multiple calls.
1191     * @param string $key Name of key in the session
1192     * @return mixed
1193     */
1194    public function getSessionData( $key ) {
1195        return $this->getSession()->get( $key );
1196    }
1197
1198    /**
1199     * @note Prefer $this->getSession() instead if making multiple calls.
1200     * @param string $key Name of key in the session
1201     * @param mixed $data
1202     */
1203    public function setSessionData( $key, $data ) {
1204        $this->getSession()->set( $key, $data );
1205    }
1206
1207    /**
1208     * Parse the Accept-Language header sent by the client into an array
1209     *
1210     * @return array [ languageCode => q-value ] sorted by q-value in
1211     *   descending order then appearing time in the header in ascending order.
1212     * May contain the "language" '*', which applies to languages other than those explicitly listed.
1213     *
1214     * This logic is aligned with RFC 7231 section 5 (previously RFC 2616 section 14),
1215     * at <https://tools.ietf.org/html/rfc7231#section-5.3.5>.
1216     *
1217     * Earlier languages in the list are preferred as per the RFC 23282 extension to HTTP/1.1,
1218     * at <https://tools.ietf.org/html/rfc3282>.
1219     * @return-taint tainted
1220     */
1221    public function getAcceptLang() {
1222        // Modified version of code found at
1223        // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1224        $acceptLang = $this->getHeader( 'Accept-Language' );
1225        if ( !$acceptLang ) {
1226            return [];
1227        }
1228
1229        // Return the language codes in lower case
1230        $acceptLang = strtolower( $acceptLang );
1231
1232        // Break up string into pieces (languages and q factors)
1233        if ( !preg_match_all(
1234            '/
1235                # a language code or a star is required
1236                ([a-z]{1,8}(?:-[a-z]{1,8})*|\*)
1237                # from here everything is optional
1238                \s*
1239                (?:
1240                    # this accepts only numbers in the range ;q=0.000 to ;q=1.000
1241                    ;\s*q\s*=\s*
1242                    (1(?:\.0{0,3})?|0(?:\.\d{0,3})?)?
1243                )?
1244            /x',
1245            $acceptLang,
1246            $matches,
1247            PREG_SET_ORDER
1248        ) ) {
1249            return [];
1250        }
1251
1252        // Create a list like "en" => 0.8
1253        $langs = [];
1254        foreach ( $matches as $match ) {
1255            $languageCode = $match[1];
1256            // When not present, the default value is 1
1257            $qValue = (float)( $match[2] ?? 1.0 );
1258            if ( $qValue ) {
1259                $langs[$languageCode] = $qValue;
1260            }
1261        }
1262
1263        // Sort list by qValue
1264        arsort( $langs, SORT_NUMERIC );
1265        return $langs;
1266    }
1267
1268    /**
1269     * Fetch the raw IP from the request
1270     *
1271     * @since 1.19
1272     * @return string|null
1273     */
1274    protected function getRawIP() {
1275        $remoteAddr = $this->getServerInfo( 'REMOTE_ADDR' );
1276        if ( !$remoteAddr ) {
1277            return null;
1278        }
1279        if ( str_contains( $remoteAddr, ',' ) ) {
1280            throw new MWException( 'Remote IP must not contain multiple values' );
1281        }
1282
1283        return IPUtils::canonicalize( $remoteAddr );
1284    }
1285
1286    /**
1287     * Work out the IP address based on various globals
1288     * For trusted proxies, use the XFF client IP (first of the chain)
1289     *
1290     * @since 1.19
1291     * @return string
1292     */
1293    public function getIP(): string {
1294        global $wgUsePrivateIPs;
1295
1296        # Return cached result
1297        if ( $this->ip !== null ) {
1298            return $this->ip;
1299        }
1300
1301        # collect the originating IPs
1302        $ip = $this->getRawIP();
1303        if ( !$ip ) {
1304            throw new MWException( 'Unable to determine IP.' );
1305        }
1306
1307        $services = MediaWikiServices::getInstance();
1308        # Append XFF
1309        $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1310        if ( $forwardedFor !== false ) {
1311            $proxyLookup = $services->getProxyLookup();
1312            $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1313            $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1314            $ipchain = array_reverse( $ipchain );
1315            array_unshift( $ipchain, $ip );
1316
1317            # Step through XFF list and find the last address in the list which is a
1318            # trusted server. Set $ip to the IP address given by that trusted server,
1319            # unless the address is not sensible (e.g. private). However, prefer private
1320            # IP addresses over proxy servers controlled by this site (more sensible).
1321            # Note that some XFF values might be "unknown" with Squid/Varnish.
1322            foreach ( $ipchain as $i => $curIP ) {
1323                $curIP = IPUtils::sanitizeIP(
1324                    IPUtils::canonicalize(
1325                        self::canonicalizeIPv6LoopbackAddress( $curIP )
1326                    )
1327                );
1328                if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1329                    || !$proxyLookup->isTrustedProxy( $curIP )
1330                ) {
1331                    break; // IP is not valid/trusted or does not point to anything
1332                }
1333                if (
1334                    IPUtils::isPublic( $ipchain[$i + 1] ) ||
1335                    $wgUsePrivateIPs ||
1336                    // T50919; treat IP as valid
1337                    $proxyLookup->isConfiguredProxy( $curIP )
1338                ) {
1339                    $nextIP = $ipchain[$i + 1];
1340
1341                    // Follow the next IP according to the proxy
1342                    $nextIP = IPUtils::canonicalize(
1343                        self::canonicalizeIPv6LoopbackAddress( $nextIP )
1344                    );
1345                    if ( !$nextIP && $isConfigured ) {
1346                        // We have not yet made it past CDN/proxy servers of this site,
1347                        // so either they are misconfigured or there is some IP spoofing.
1348                        throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1349                    }
1350                    $ip = $nextIP;
1351
1352                    // keep traversing the chain
1353                    continue;
1354                }
1355                break;
1356            }
1357        }
1358
1359        // Allow extensions to modify the result
1360        $hookContainer = $services->getHookContainer();
1361        // Optimisation: Hot code called on most requests (T85805).
1362        if ( $hookContainer->isRegistered( 'GetIP' ) ) {
1363            // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1364            ( new HookRunner( $hookContainer ) )->onGetIP( $ip );
1365        }
1366
1367        if ( !$ip ) {
1368            throw new MWException( 'Unable to determine IP.' );
1369        }
1370
1371        $this->ip = $ip;
1372        return $ip;
1373    }
1374
1375    /**
1376     * Converts ::1 (IPv6 loopback address) to 127.0.0.1 (IPv4 loopback address);
1377     * assists in matching trusted proxies.
1378     *
1379     * @param string $ip
1380     * @return string either '127.0.0.1' or $ip
1381     * @since 1.36
1382     */
1383    public static function canonicalizeIPv6LoopbackAddress( $ip ) {
1384        // Code moved from IPUtils library. See T248237#6614927
1385        if ( preg_match( '/^0*' . IPUtils::RE_IPV6_GAP . '1$/', $ip ) ) {
1386            return '127.0.0.1';
1387        }
1388        return $ip;
1389    }
1390
1391    /**
1392     * @param string $ip
1393     * @return void
1394     * @since 1.21
1395     */
1396    public function setIP( $ip ) {
1397        $this->ip = $ip;
1398    }
1399
1400    /**
1401     * Check if this request uses a "safe" HTTP method
1402     *
1403     * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1404     * are not expected to mutate content, especially in ways attributable to the client. Verbs
1405     * like POST and PUT are typical of non-safe requests which often change content.
1406     *
1407     * @return bool
1408     * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1409     * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1410     * @since 1.28
1411     */
1412    public function hasSafeMethod() {
1413        if ( $this->getServerInfo( 'REQUEST_METHOD' ) === null ) {
1414            return false; // CLI mode
1415        }
1416
1417        return in_array( $this->getServerInfo( 'REQUEST_METHOD' ), [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1418    }
1419
1420    /**
1421     * Whether this request should be identified as being "safe"
1422     *
1423     * This means that the client is not requesting any state changes and that database writes
1424     * are not inherently required. Ideally, no visible updates would happen at all. If they
1425     * must, then they should not be publicly attributed to the end user.
1426     *
1427     * In more detail:
1428     *   - Cache populations and refreshes MAY occur.
1429     *   - Private user session updates and private server logging MAY occur.
1430     *   - Updates to private viewing activity data MAY occur via DeferredUpdates.
1431     *   - Other updates SHOULD NOT occur (e.g. modifying content assets).
1432     *
1433     * @deprecated since 1.41, use hasSafeMethod() instead.
1434     *
1435     * @return bool
1436     * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1437     * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1438     * @since 1.28
1439     */
1440    public function isSafeRequest() {
1441        wfDeprecated( __METHOD__, '1.41' );
1442        if ( $this->markedAsSafe && $this->wasPosted() ) {
1443            return true; // marked as a "safe" POST
1444        }
1445
1446        return $this->hasSafeMethod();
1447    }
1448
1449    /**
1450     * Mark this request as identified as being nullipotent even if it is a POST request
1451     *
1452     * POST requests are often used due to the need for a client payload, even if the request
1453     * is otherwise equivalent to a "safe method" request.
1454     *
1455     * @deprecated since 1.41
1456     *
1457     * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1458     * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1459     * @since 1.28
1460     */
1461    public function markAsSafeRequest() {
1462        wfDeprecated( __METHOD__, '1.41' );
1463        $this->markedAsSafe = true;
1464    }
1465
1466    /**
1467     * Determine if the request URL matches one of a given set of canonical CDN URLs.
1468     *
1469     * MediaWiki uses this to determine whether to set a long 'Cache-Control: s-maxage='
1470     * header on the response. {@see MainConfigNames::CdnMatchParameterOrder} controls whether
1471     * the matching is sensitive to the order of query parameters.
1472     *
1473     * @param string[] $cdnUrls URLs to match against
1474     * @return bool
1475     * @since 1.39
1476     */
1477    public function matchURLForCDN( array $cdnUrls ) {
1478        $services = MediaWikiServices::getInstance();
1479        $reqUrl = (string)$services->getUrlUtils()->expand( $this->getRequestURL(), PROTO_INTERNAL );
1480        $config = $services->getMainConfig();
1481        if ( $config->get( MainConfigNames::CdnMatchParameterOrder ) ) {
1482            // Strict matching
1483            return in_array( $reqUrl, $cdnUrls, true );
1484        }
1485
1486        // Loose matching (order of query parameters is ignored)
1487        $reqUrlParts = explode( '?', $reqUrl, 2 );
1488        $reqUrlBase = $reqUrlParts[0];
1489        $reqUrlParams = count( $reqUrlParts ) === 2 ? explode( '&', $reqUrlParts[1] ) : [];
1490        // The order of parameters after the sort() call below does not match
1491        // the order set by the CDN, and does not need to. The CDN needs to
1492        // take special care to preserve the relative order of duplicate keys
1493        // and array-like parameters.
1494        sort( $reqUrlParams );
1495        foreach ( $cdnUrls as $cdnUrl ) {
1496            if ( strlen( $reqUrl ) !== strlen( $cdnUrl ) ) {
1497                continue;
1498            }
1499            $cdnUrlParts = explode( '?', $cdnUrl, 2 );
1500            $cdnUrlBase = $cdnUrlParts[0];
1501            if ( $reqUrlBase !== $cdnUrlBase ) {
1502                continue;
1503            }
1504            $cdnUrlParams = count( $cdnUrlParts ) === 2 ? explode( '&', $cdnUrlParts[1] ) : [];
1505            sort( $cdnUrlParams );
1506            if ( $reqUrlParams === $cdnUrlParams ) {
1507                return true;
1508            }
1509        }
1510        return false;
1511    }
1512
1513    /**
1514     * Returns an array suitable for addition to a PSR-3 log context that will contain information
1515     * about the request that is useful when investigating security or abuse issues (IP, user agent
1516     * etc).
1517     *
1518     * @param ?UserIdentity $user The user whose action is being logged. Optional; passing it will
1519     *   result in more context information. The user is not required to exist locally. It must
1520     *   have a name though (ie. it should not have the IP address as its name; temp users are
1521     *   allowed).
1522     * @return array By default it will have the following keys:
1523     *   - clientIp: the IP address (as in WebRequest::getIP())
1524     *   - ua: the User-Agent header (or the Api-User-Agent header when using the action API)
1525     *   - originalUserAgent: the User-Agent header (only when Api-User-Agent is also present)
1526     *   Furthermore, when $user has been provided:
1527     *   - user: the username
1528     *   - user_exists_locally: whether the user account exists on the current wiki
1529     *   More fields can be added via the GetSecurityLogContext hook.
1530     *
1531     * @since 1.45 (also backported to 1.43.9, 1.44.6)
1532     * @see GetSecurityLogContextHook
1533     */
1534    public function getSecurityLogContext( ?UserIdentity $user = null ): array {
1535        $this->securityLogContext ??= new HashBagOStuff( [ 'maxKeys' => 5 ] );
1536        $cacheKey = $user
1537            ? $this->securityLogContext->makeKey( 'user', $user->getName() )
1538            : $this->securityLogContext->makeKey( 'anon', '-' );
1539        if ( $this->securityLogContext->hasKey( $cacheKey ) ) {
1540            return $this->securityLogContext->get( $cacheKey );
1541        }
1542
1543        $context = [
1544            'clientIp' => $this->getIP(),
1545        ];
1546
1547        $userAgent = $this->getHeader( 'User-Agent' );
1548        $apiUserAgent = null;
1549        if ( defined( 'MW_API' ) ) {
1550            // matches ApiMain::getUserAgent()
1551            $apiUserAgent = $this->getHeader( 'Api-User-Agent' );
1552        }
1553        $context['ua'] = $apiUserAgent ?: $userAgent;
1554        if ( $apiUserAgent ) {
1555            $context['originalUserAgent'] = $userAgent;
1556        }
1557
1558        $services = MediaWikiServices::getInstance();
1559        if ( $user ) {
1560            $context += [
1561                'user' => $user->getName(),
1562                'user_exists_locally' => $user->isRegistered(),
1563                'user_is_bot' => $services->getUserFactory()->newFromUserIdentity( $user )->isBot(),
1564            ];
1565        }
1566
1567        $info = [ 'request' => $this, 'user' => $user ];
1568        $hookRunner = new HookRunner( $services->getHookContainer() );
1569        $hookRunner->onGetSecurityLogContext( $info, $context );
1570
1571        $this->securityLogContext->set( $cacheKey, $context );
1572        return $context;
1573    }
1574}
1575
1576/** @deprecated class alias since 1.41 */
1577class_alias( WebRequest::class, 'WebRequest' );