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