Debian Codegraph @

includes/Request/WebRequest.php

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