3 * Deal with importing all those nasty globals and things
5 * Copyright © 2003 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
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.
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.
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
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Session\Session
;
28 use MediaWiki\Session\SessionId
;
29 use MediaWiki\Session\SessionManager
;
31 // The point of this class is to be a wrapper around super globals
32 // phpcs:disable MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
35 * The WebRequest class encapsulates getting at data passed in the
36 * URL or via a POSTed form stripping illegal input characters and
37 * normalizing Unicode sequences.
42 protected $data, $headers = [];
45 * Flag to make WebRequest::getHeader return an array of values.
48 const GETHEADER_LIST
= 1;
51 * The unique request ID.
54 private static $reqId;
57 * Lazy-init response object
63 * Cached client IP address
69 * The timestamp of the start of the request, with microsecond precision.
72 protected $requestTime;
81 * @var SessionId|null Session ID to use for this
82 * request. We can't save the session directly due to reference cycles not
83 * working too well (slow GC in Zend and never collected in HHVM).
85 protected $sessionId = null;
87 /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
88 protected $markedAsSafe = false;
93 public function __construct() {
94 $this->requestTime
= $_SERVER['REQUEST_TIME_FLOAT'];
96 // POST overrides GET data
97 // We don't use $_REQUEST here to avoid interference from cookies...
98 $this->data
= $_POST +
$_GET;
102 * Extract relevant query arguments from the http request uri's path
103 * to be merged with the normal php provided query arguments.
104 * Tries to use the REQUEST_URI data if available and parses it
105 * according to the wiki's configuration looking for any known pattern.
107 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
108 * provided by the server if any and use that to set a 'title' parameter.
110 * @param string $want If this is not 'all', then the function
111 * will return an empty array if it determines that the URL is
112 * inside a rewrite path.
114 * @return array Any query arguments found in path matches.
116 public static function getPathInfo( $want = 'all' ) {
117 global $wgUsePathInfo;
118 // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
119 // And also by Apache 2.x, double slashes are converted to single slashes.
120 // So we will use REQUEST_URI if possible.
122 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
123 // Slurp out the path portion to examine...
124 $url = $_SERVER['REQUEST_URI'];
125 if ( !preg_match( '!^https?://!', $url ) ) {
126 $url = 'http://unused' . $url;
128 Wikimedia\
suppressWarnings();
129 $a = parse_url( $url );
130 Wikimedia\restoreWarnings
();
132 $path = $a['path'] ??
'';
135 if ( $path == $wgScript && $want !== 'all' ) {
136 // Script inside a rewrite path?
137 // Abort to keep from breaking...
141 $router = new PathRouter
;
143 // Raw PATH_INFO style
144 $router->add( "$wgScript/$1" );
146 if ( isset( $_SERVER['SCRIPT_NAME'] )
147 && preg_match( '/\.php/', $_SERVER['SCRIPT_NAME'] )
149 # Check for SCRIPT_NAME, we handle index.php explicitly
150 # But we do have some other .php files such as img_auth.php
151 # Don't let root article paths clober the parsing for them
152 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
155 global $wgArticlePath;
156 if ( $wgArticlePath ) {
157 $router->add( $wgArticlePath );
160 global $wgActionPaths;
161 if ( $wgActionPaths ) {
162 $router->add( $wgActionPaths, [ 'action' => '$key' ] );
165 global $wgVariantArticlePath;
166 if ( $wgVariantArticlePath ) {
167 $router->add( $wgVariantArticlePath,
168 [ 'variant' => '$2' ],
169 [ '$2' => MediaWikiServices
::getInstance()->getContentLanguage()->
174 Hooks
::run( 'WebRequestPathInfoRouter', [ $router ] );
176 $matches = $router->parse( $path );
178 } elseif ( $wgUsePathInfo ) {
179 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
181 // https://bugs.php.net/bug.php?id=31892
182 // Also reported when ini_get('cgi.fix_pathinfo')==false
183 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
185 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
186 // Regular old PATH_INFO yay
187 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
195 * Work out an appropriate URL prefix containing scheme and host, based on
196 * information detected from $_SERVER
200 public static function detectServer() {
201 global $wgAssumeProxiesUseDefaultProtocolPorts;
203 $proto = self
::detectProtocol();
204 $stdPort = $proto === 'https' ?
443 : 80;
206 $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
209 foreach ( $varNames as $varName ) {
210 if ( !isset( $_SERVER[$varName] ) ) {
214 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
216 // Invalid, do not use
221 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
222 // T72021: Assume that upstream proxy is running on the default
223 // port based on the protocol. We have no reliable way to determine
224 // the actual port in use upstream.
226 } elseif ( $parts[1] === false ) {
227 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
228 $port = $_SERVER['SERVER_PORT'];
229 } // else leave it as $stdPort
236 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
240 * Detect the protocol from $_SERVER.
241 * This is for use prior to Setup.php, when no WebRequest object is available.
242 * At other times, use the non-static function getProtocol().
246 public static function detectProtocol() {
247 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
248 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
249 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
257 * Get the number of seconds to have elapsed since request start,
258 * in fractional seconds, with microsecond resolution.
263 public function getElapsedTime() {
264 return microtime( true ) - $this->requestTime
;
268 * Get the unique request ID.
269 * This is either the value of the UNIQUE_ID envvar (if present) or a
270 * randomly-generated 24-character string.
275 public static function getRequestId() {
276 // This method is called from various error handlers and should be kept simple.
278 if ( !self
::$reqId ) {
279 self
::$reqId = $_SERVER['UNIQUE_ID'] ??
wfRandomString( 24 );
286 * Override the unique request ID. This is for sub-requests, such as jobs,
287 * that wish to use the same id but are not part of the same execution context.
292 public static function overrideRequestId( $id ) {
297 * Get the current URL protocol (http or https)
300 public function getProtocol() {
301 if ( $this->protocol
=== null ) {
302 $this->protocol
= self
::detectProtocol();
304 return $this->protocol
;
308 * Check for title, action, and/or variant data in the URL
309 * and interpolate it into the GET variables.
310 * This should only be run after the content language is available,
311 * as we may need the list of language variants to determine
312 * available variant URLs.
314 public function interpolateTitle() {
315 // T18019: title interpolation on API queries is useless and sometimes harmful
316 if ( defined( 'MW_API' ) ) {
320 $matches = self
::getPathInfo( 'title' );
321 foreach ( $matches as $key => $val ) {
322 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
327 * URL rewriting function; tries to extract page title and,
328 * optionally, one other fixed parameter value from a URL path.
330 * @param string $path The URL path given from the client
331 * @param array $bases One or more URLs, optionally with $1 at the end
332 * @param string|bool $key If provided, the matching key in $bases will be
333 * passed on as the value of this URL parameter
334 * @return array Array of URL variables to interpolate; empty if no match
336 static function extractTitle( $path, $bases, $key = false ) {
337 foreach ( (array)$bases as $keyValue => $base ) {
338 // Find the part after $wgArticlePath
339 $base = str_replace( '$1', '', $base );
340 $baseLen = strlen( $base );
341 if ( substr( $path, 0, $baseLen ) == $base ) {
342 $raw = substr( $path, $baseLen );
344 $matches = [ 'title' => rawurldecode( $raw ) ];
346 $matches[$key] = $keyValue;
356 * Recursively normalizes UTF-8 strings in the given array.
358 * @param string|array $data
359 * @return array|string Cleaned-up version of the given
362 public function normalizeUnicode( $data ) {
363 if ( is_array( $data ) ) {
364 foreach ( $data as $key => $val ) {
365 $data[$key] = $this->normalizeUnicode( $val );
368 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
369 $data = $contLang ?
$contLang->normalize( $data ) :
370 UtfNormal\Validator
::cleanUp( $data );
376 * Fetch a value from the given array or return $default if it's not set.
379 * @param string $name
380 * @param mixed $default
383 private function getGPCVal( $arr, $name, $default ) {
384 # PHP is so nice to not touch input data, except sometimes:
385 # https://secure.php.net/variables.external#language.variables.external.dot-in-names
386 # Work around PHP *feature* to avoid *bugs* elsewhere.
387 $name = strtr( $name, '.', '_' );
388 if ( isset( $arr[$name] ) ) {
390 if ( isset( $_GET[$name] ) && is_string( $data ) ) {
391 # Check for alternate/legacy character encoding.
392 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
393 $data = $contLang->checkTitleEncoding( $data );
395 $data = $this->normalizeUnicode( $data );
403 * Fetch a scalar from the input without normalization, or return $default
406 * Unlike self::getVal(), this does not perform any normalization on the
410 * @param string $name
411 * @param string|null $default
412 * @return string|null
414 public function getRawVal( $name, $default = null ) {
415 $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
416 if ( isset( $this->data
[$name] ) && !is_array( $this->data
[$name] ) ) {
417 $val = $this->data
[$name];
421 if ( is_null( $val ) ) {
429 * Fetch a scalar from the input or return $default if it's not set.
430 * Returns a string. Arrays are discarded. Useful for
431 * non-freeform text inputs (e.g. predefined internal text keys
432 * selected by a drop-down menu). For freeform input, see getText().
434 * @param string $name
435 * @param string|null $default Optional default (or null)
436 * @return string|null
438 public function getVal( $name, $default = null ) {
439 $val = $this->getGPCVal( $this->data
, $name, $default );
440 if ( is_array( $val ) ) {
443 if ( is_null( $val ) ) {
451 * Set an arbitrary value into our get/post data.
453 * @param string $key Key name to use
454 * @param mixed $value Value to set
455 * @return mixed Old value if one was present, null otherwise
457 public function setVal( $key, $value ) {
458 $ret = $this->data
[$key] ??
null;
459 $this->data
[$key] = $value;
464 * Unset an arbitrary value from our get/post data.
466 * @param string $key Key name to use
467 * @return mixed Old value if one was present, null otherwise
469 public function unsetVal( $key ) {
470 if ( !isset( $this->data
[$key] ) ) {
473 $ret = $this->data
[$key];
474 unset( $this->data
[$key] );
480 * Fetch an array from the input or return $default if it's not set.
481 * If source was scalar, will return an array with a single element.
482 * If no source and no default, returns null.
484 * @param string $name
485 * @param array|null $default Optional default (or null)
488 public function getArray( $name, $default = null ) {
489 $val = $this->getGPCVal( $this->data
, $name, $default );
490 if ( is_null( $val ) ) {
498 * Fetch an array of integers, or return $default if it's not set.
499 * If source was scalar, will return an array with a single element.
500 * If no source and no default, returns null.
501 * If an array is returned, contents are guaranteed to be integers.
503 * @param string $name
504 * @param array|null $default Option default (or null)
505 * @return array Array of ints
507 public function getIntArray( $name, $default = null ) {
508 $val = $this->getArray( $name, $default );
509 if ( is_array( $val ) ) {
510 $val = array_map( 'intval', $val );
516 * Fetch an integer value from the input or return $default if not set.
517 * Guaranteed to return an integer; non-numeric input will typically
520 * @param string $name
521 * @param int $default
524 public function getInt( $name, $default = 0 ) {
525 return intval( $this->getRawVal( $name, $default ) );
529 * Fetch an integer value from the input or return null if empty.
530 * Guaranteed to return an integer or null; non-numeric input will
531 * typically return null.
533 * @param string $name
536 public function getIntOrNull( $name ) {
537 $val = $this->getRawVal( $name );
538 return is_numeric( $val )
544 * Fetch a floating point value from the input or return $default if not set.
545 * Guaranteed to return a float; non-numeric input will typically
549 * @param string $name
550 * @param float $default
553 public function getFloat( $name, $default = 0.0 ) {
554 return floatval( $this->getRawVal( $name, $default ) );
558 * Fetch a boolean value from the input or return $default if not set.
559 * Guaranteed to return true or false, with normal PHP semantics for
560 * boolean interpretation of strings.
562 * @param string $name
563 * @param bool $default
566 public function getBool( $name, $default = false ) {
567 return (bool)$this->getRawVal( $name, $default );
571 * Fetch a boolean value from the input or return $default if not set.
572 * Unlike getBool, the string "false" will result in boolean false, which is
573 * useful when interpreting information sent from JavaScript.
575 * @param string $name
576 * @param bool $default
579 public function getFuzzyBool( $name, $default = false ) {
580 return $this->getBool( $name, $default )
581 && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
585 * Return true if the named value is set in the input, whatever that
586 * value is (even "0"). Return false if the named value is not set.
587 * Example use is checking for the presence of check boxes in forms.
589 * @param string $name
592 public function getCheck( $name ) {
593 # Checkboxes and buttons are only present when clicked
594 # Presence connotes truth, absence false
595 return $this->getRawVal( $name, null ) !== null;
599 * Fetch a text string from the given array or return $default if it's not
600 * set. Carriage returns are stripped from the text. This should generally
601 * be used for form "<textarea>" and "<input>" fields, and for
602 * user-supplied freeform text input.
604 * @param string $name
605 * @param string $default Optional
608 public function getText( $name, $default = '' ) {
609 $val = $this->getVal( $name, $default );
610 return str_replace( "\r\n", "\n", $val );
614 * Extracts the given named values into an array.
615 * If no arguments are given, returns all input values.
616 * No transformation is performed on the values.
620 public function getValues() {
621 $names = func_get_args();
622 if ( count( $names ) == 0 ) {
623 $names = array_keys( $this->data
);
627 foreach ( $names as $name ) {
628 $value = $this->getGPCVal( $this->data
, $name, null );
629 if ( !is_null( $value ) ) {
630 $retVal[$name] = $value;
637 * Returns the names of all input values excluding those in $exclude.
639 * @param array $exclude
642 public function getValueNames( $exclude = [] ) {
643 return array_diff( array_keys( $this->getValues() ), $exclude );
647 * Get the values passed in the query string.
648 * No transformation is performed on the values.
650 * @codeCoverageIgnore
653 public function getQueryValues() {
658 * Get the values passed via POST.
659 * No transformation is performed on the values.
662 * @codeCoverageIgnore
665 public function getPostValues() {
670 * Return the contents of the Query with no decoding. Use when you need to
671 * know exactly what was sent, e.g. for an OAuth signature over the elements.
673 * @codeCoverageIgnore
676 public function getRawQueryString() {
677 return $_SERVER['QUERY_STRING'];
681 * Return the contents of the POST with no decoding. Use when you need to
682 * know exactly what was sent, e.g. for an OAuth signature over the elements.
686 public function getRawPostString() {
687 if ( !$this->wasPosted() ) {
690 return $this->getRawInput();
694 * Return the raw request body, with no processing. Cached since some methods
695 * disallow reading the stream more than once. As stated in the php docs, this
696 * does not work with enctype="multipart/form-data".
700 public function getRawInput() {
701 static $input = null;
702 if ( $input === null ) {
703 $input = file_get_contents( 'php://input' );
709 * Get the HTTP method used for this request.
713 public function getMethod() {
714 return $_SERVER['REQUEST_METHOD'] ??
'GET';
718 * Returns true if the present request was reached by a POST operation,
719 * false otherwise (GET, HEAD, or command-line).
721 * Note that values retrieved by the object may come from the
722 * GET URL etc even on a POST request.
726 public function wasPosted() {
727 return $this->getMethod() == 'POST';
731 * Return the session for this request
733 * This might unpersist an existing session if it was invalid.
736 * @note For performance, keep the session locally if you will be making
737 * much use of it instead of calling this method repeatedly.
740 public function getSession() {
741 if ( $this->sessionId
!== null ) {
742 $session = SessionManager
::singleton()->getSessionById( (string)$this->sessionId
, true, $this );
748 $session = SessionManager
::singleton()->getSessionForRequest( $this );
749 $this->sessionId
= $session->getSessionId();
754 * Set the session for this request
756 * @private For use by MediaWiki\Session classes only
757 * @param SessionId $sessionId
759 public function setSessionId( SessionId
$sessionId ) {
760 $this->sessionId
= $sessionId;
764 * Get the session id for this request, if any
766 * @private For use by MediaWiki\Session classes only
767 * @return SessionId|null
769 public function getSessionId() {
770 return $this->sessionId
;
774 * Get a cookie from the $_COOKIE jar
776 * @param string $key The name of the cookie
777 * @param string|null $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
778 * @param mixed|null $default What to return if the value isn't found
779 * @return mixed Cookie value or $default if the cookie not set
781 public function getCookie( $key, $prefix = null, $default = null ) {
782 if ( $prefix === null ) {
783 global $wgCookiePrefix;
784 $prefix = $wgCookiePrefix;
786 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
790 * Return the path and query string portion of the main request URI.
791 * This will be suitable for use as a relative link in HTML output.
793 * @throws MWException
796 public static function getGlobalRequestURL() {
797 // This method is called on fatal errors; it should not depend on anything complex.
799 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
800 $base = $_SERVER['REQUEST_URI'];
801 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
802 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
804 // Probably IIS; doesn't set REQUEST_URI
805 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
806 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
807 $base = $_SERVER['SCRIPT_NAME'];
808 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
809 $base .= '?' . $_SERVER['QUERY_STRING'];
812 // This shouldn't happen!
813 throw new MWException( "Web server doesn't provide either " .
814 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
815 "of your web server configuration to https://phabricator.wikimedia.org/" );
817 // User-agents should not send a fragment with the URI, but
818 // if they do, and the web server passes it on to us, we
819 // need to strip it or we get false-positive redirect loops
820 // or weird output URLs
821 $hash = strpos( $base, '#' );
822 if ( $hash !== false ) {
823 $base = substr( $base, 0, $hash );
826 if ( $base[0] == '/' ) {
827 // More than one slash will look like it is protocol relative
828 return preg_replace( '!^/+!', '/', $base );
830 // We may get paths with a host prepended; strip it.
831 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
836 * Return the path and query string portion of the request URI.
837 * This will be suitable for use as a relative link in HTML output.
839 * @throws MWException
842 public function getRequestURL() {
843 return self
::getGlobalRequestURL();
847 * Return the request URI with the canonical service and hostname, path,
848 * and query string. This will be suitable for use as an absolute link
849 * in HTML or other output.
851 * If $wgServer is protocol-relative, this will return a fully
852 * qualified URL with the protocol that was used for this request.
856 public function getFullRequestURL() {
857 return wfGetServerUrl( PROTO_CURRENT
) . $this->getRequestURL();
862 * @param string $value
865 public function appendQueryValue( $key, $value ) {
866 return $this->appendQueryArray( [ $key => $value ] );
870 * Appends or replaces value of query variables.
872 * @param array $array Array of values to replace/add to query
875 public function appendQueryArray( $array ) {
876 $newquery = $this->getQueryValues();
877 unset( $newquery['title'] );
878 $newquery = array_merge( $newquery, $array );
880 return wfArrayToCgi( $newquery );
884 * Check for limit and offset parameters on the input, and return sensible
885 * defaults if not given. The limit must be positive and is capped at 5000.
886 * Offset must be positive but is not capped.
888 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
889 * @param string $optionname To specify an option other than rclimit to pull from.
890 * @return int[] First element is limit, second is offset
892 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
895 $limit = $this->getInt( 'limit', 0 );
899 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
900 $limit = $wgUser->getIntOption( $optionname );
905 if ( $limit > 5000 ) {
906 $limit = 5000; # We have *some* limits...
909 $offset = $this->getInt( 'offset', 0 );
914 return [ $limit, $offset ];
918 * Return the path to the temporary file where PHP has stored the upload.
921 * @return string|null String or null if no such file.
923 public function getFileTempname( $key ) {
924 $file = new WebRequestUpload( $this, $key );
925 return $file->getTempName();
929 * Return the upload error or 0
934 public function getUploadError( $key ) {
935 $file = new WebRequestUpload( $this, $key );
936 return $file->getError();
940 * Return the original filename of the uploaded file, as reported by
941 * the submitting user agent. HTML-style character entities are
942 * interpreted and normalized to Unicode normalization form C, in part
943 * to deal with weird input from Safari with non-ASCII filenames.
945 * Other than this the name is not verified for being a safe filename.
948 * @return string|null String or null if no such file.
950 public function getFileName( $key ) {
951 $file = new WebRequestUpload( $this, $key );
952 return $file->getName();
956 * Return a WebRequestUpload object corresponding to the key
959 * @return WebRequestUpload
961 public function getUpload( $key ) {
962 return new WebRequestUpload( $this, $key );
966 * Return a handle to WebResponse style object, for setting cookies,
967 * headers and other stuff, for Request being worked on.
969 * @return WebResponse
971 public function response() {
972 /* Lazy initialization of response object for this request */
973 if ( !is_object( $this->response
) ) {
974 $class = ( $this instanceof FauxRequest
) ? FauxResponse
::class : WebResponse
::class;
975 $this->response
= new $class();
977 return $this->response
;
981 * Initialise the header list
983 protected function initHeaders() {
984 if ( count( $this->headers
) ) {
988 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
989 if ( $apacheHeaders ) {
990 foreach ( $apacheHeaders as $tempName => $tempValue ) {
991 $this->headers
[strtoupper( $tempName )] = $tempValue;
994 foreach ( $_SERVER as $name => $value ) {
995 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
996 $name = str_replace( '_', '-', substr( $name, 5 ) );
997 $this->headers
[$name] = $value;
998 } elseif ( $name === 'CONTENT_LENGTH' ) {
999 $this->headers
['CONTENT-LENGTH'] = $value;
1006 * Get an array containing all request headers
1008 * @return array Mapping header name to its value
1010 public function getAllHeaders() {
1011 $this->initHeaders();
1012 return $this->headers
;
1016 * Get a request header, or false if it isn't set.
1018 * @param string $name Case-insensitive header name
1019 * @param int $flags Bitwise combination of:
1020 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1021 * of values, as described in RFC 2616 § 4.2.
1023 * @return string|array|bool False if header is unset; otherwise the
1024 * header value(s) as either a string (the default) or an array, if
1025 * WebRequest::GETHEADER_LIST flag was set.
1027 public function getHeader( $name, $flags = 0 ) {
1028 $this->initHeaders();
1029 $name = strtoupper( $name );
1030 if ( !isset( $this->headers
[$name] ) ) {
1033 $value = $this->headers
[$name];
1034 if ( $flags & self
::GETHEADER_LIST
) {
1035 $value = array_map( 'trim', explode( ',', $value ) );
1041 * Get data from the session
1043 * @note Prefer $this->getSession() instead if making multiple calls.
1044 * @param string $key Name of key in the session
1047 public function getSessionData( $key ) {
1048 return $this->getSession()->get( $key );
1054 * @note Prefer $this->getSession() instead if making multiple calls.
1055 * @param string $key Name of key in the session
1056 * @param mixed $data
1058 public function setSessionData( $key, $data ) {
1059 $this->getSession()->set( $key, $data );
1063 * Check if Internet Explorer will detect an incorrect cache extension in
1064 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1065 * message or redirect to a safer URL. Returns true if the URL is OK, and
1066 * false if an error message has been shown and the request should be aborted.
1068 * @param array $extWhitelist
1072 public function checkUrlExtension( $extWhitelist = [] ) {
1073 $extWhitelist[] = 'php';
1074 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1075 if ( !$this->wasPosted() ) {
1076 $newUrl = IEUrlExtension
::fixUrlForIE6(
1077 $this->getFullRequestURL(), $extWhitelist );
1078 if ( $newUrl !== false ) {
1079 $this->doSecurityRedirect( $newUrl );
1083 throw new HttpError( 403,
1084 'Invalid file extension found in the path info or query string.' );
1090 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1091 * IE 6. Returns true if it was successful, false otherwise.
1093 * @param string $url
1096 protected function doSecurityRedirect( $url ) {
1097 header( 'Location: ' . $url );
1098 header( 'Content-Type: text/html' );
1099 $encUrl = htmlspecialchars( $url );
1104 <title>Security redirect</title>
1107 <h1>Security redirect</h1>
1109 We can't serve non-HTML content from the URL you have requested
, because
1110 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
1112 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
1113 URL you have requested
, except that
"&*" is appended
. This prevents Internet
1114 Explorer from seeing a bogus file extension
.
1124 * Parse the Accept-Language header sent by the client into an array
1126 * @return array Array( languageCode => q-value ) sorted by q-value in
1127 * descending order then appearing time in the header in ascending order.
1128 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1129 * This is aligned with rfc2616 section 14.4
1130 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1132 public function getAcceptLang() {
1133 // Modified version of code found at
1134 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1135 $acceptLang = $this->getHeader( 'Accept-Language' );
1136 if ( !$acceptLang ) {
1140 // Return the language codes in lower case
1141 $acceptLang = strtolower( $acceptLang );
1143 // Break up string into pieces (languages and q factors)
1146 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1151 if ( !count( $lang_parse[1] ) ) {
1155 $langcodes = $lang_parse[1];
1156 $qvalues = $lang_parse[4];
1157 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1159 // Set default q factor to 1
1160 foreach ( $indices as $index ) {
1161 if ( $qvalues[$index] === '' ) {
1162 $qvalues[$index] = 1;
1163 } elseif ( $qvalues[$index] == 0 ) {
1164 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1168 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1169 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1171 // Create a list like "en" => 0.8
1172 $langs = array_combine( $langcodes, $qvalues );
1178 * Fetch the raw IP from the request
1182 * @throws MWException
1185 protected function getRawIP() {
1186 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1190 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1191 throw new MWException( __METHOD__
1192 . " : Could not determine the remote IP address due to multiple values." );
1194 $ipchain = $_SERVER['REMOTE_ADDR'];
1197 return IP
::canonicalize( $ipchain );
1201 * Work out the IP address based on various globals
1202 * For trusted proxies, use the XFF client IP (first of the chain)
1206 * @throws MWException
1209 public function getIP() {
1210 global $wgUsePrivateIPs;
1212 # Return cached result
1213 if ( $this->ip
!== null ) {
1217 # collect the originating ips
1218 $ip = $this->getRawIP();
1220 throw new MWException( 'Unable to determine IP.' );
1224 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1225 if ( $forwardedFor !== false ) {
1226 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1227 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1228 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1229 $ipchain = array_reverse( $ipchain );
1230 array_unshift( $ipchain, $ip );
1232 # Step through XFF list and find the last address in the list which is a
1233 # trusted server. Set $ip to the IP address given by that trusted server,
1234 # unless the address is not sensible (e.g. private). However, prefer private
1235 # IP addresses over proxy servers controlled by this site (more sensible).
1236 # Note that some XFF values might be "unknown" with Squid/Varnish.
1237 foreach ( $ipchain as $i => $curIP ) {
1238 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1239 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1240 ||
!$proxyLookup->isTrustedProxy( $curIP )
1242 break; // IP is not valid/trusted or does not point to anything
1245 IP
::isPublic( $ipchain[$i +
1] ) ||
1247 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1249 // Follow the next IP according to the proxy
1250 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1251 if ( !$nextIP && $isConfigured ) {
1252 // We have not yet made it past CDN/proxy servers of this site,
1253 // so either they are misconfigured or there is some IP spoofing.
1254 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1257 // keep traversing the chain
1264 # Allow extensions to improve our guess
1265 Hooks
::run( 'GetIP', [ &$ip ] );
1268 throw new MWException( "Unable to determine IP." );
1271 wfDebug( "IP: $ip\n" );
1281 public function setIP( $ip ) {
1286 * Check if this request uses a "safe" HTTP method
1288 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1289 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1290 * like POST and PUT are typical of non-safe requests which often change content.
1293 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1294 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1297 public function hasSafeMethod() {
1298 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1299 return false; // CLI mode
1302 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1306 * Whether this request should be identified as being "safe"
1308 * This means that the client is not requesting any state changes and that database writes
1309 * are not inherently required. Ideally, no visible updates would happen at all. If they
1310 * must, then they should not be publicly attributed to the end user.
1313 * - Cache populations and refreshes MAY occur.
1314 * - Private user session updates and private server logging MAY occur.
1315 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1316 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1319 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1320 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1323 public function isSafeRequest() {
1324 if ( $this->markedAsSafe
&& $this->wasPosted() ) {
1325 return true; // marked as a "safe" POST
1328 return $this->hasSafeMethod();
1332 * Mark this request as identified as being nullipotent even if it is a POST request
1334 * POST requests are often used due to the need for a client payload, even if the request
1335 * is otherwise equivalent to a "safe method" request.
1337 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1338 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1341 public function markAsSafeRequest() {
1342 $this->markedAsSafe
= true;