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
;
32 * The WebRequest class encapsulates getting at data passed in the
33 * URL or via a POSTed form stripping illegal input characters and
34 * normalizing Unicode sequences.
39 protected $data, $headers = [];
42 * Flag to make WebRequest::getHeader return an array of values.
45 const GETHEADER_LIST
= 1;
48 * The unique request ID.
51 private static $reqId;
54 * Lazy-init response object
60 * Cached client IP address
66 * The timestamp of the start of the request, with microsecond precision.
69 protected $requestTime;
78 * @var SessionId|null Session ID to use for this
79 * request. We can't save the session directly due to reference cycles not
80 * working too well (slow GC in Zend and never collected in HHVM).
82 protected $sessionId = null;
84 /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
85 protected $markedAsSafe = false;
90 public function __construct() {
91 $this->requestTime
= isset( $_SERVER['REQUEST_TIME_FLOAT'] )
92 ?
$_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
94 // POST overrides GET data
95 // We don't use $_REQUEST here to avoid interference from cookies...
96 $this->data
= $_POST +
$_GET;
100 * Extract relevant query arguments from the http request uri's path
101 * to be merged with the normal php provided query arguments.
102 * Tries to use the REQUEST_URI data if available and parses it
103 * according to the wiki's configuration looking for any known pattern.
105 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
106 * provided by the server if any and use that to set a 'title' parameter.
108 * @param string $want If this is not 'all', then the function
109 * will return an empty array if it determines that the URL is
110 * inside a rewrite path.
112 * @return array Any query arguments found in path matches.
114 public static function getPathInfo( $want = 'all' ) {
115 global $wgUsePathInfo;
116 // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
117 // And also by Apache 2.x, double slashes are converted to single slashes.
118 // So we will use REQUEST_URI if possible.
120 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
121 // Slurp out the path portion to examine...
122 $url = $_SERVER['REQUEST_URI'];
123 if ( !preg_match( '!^https?://!', $url ) ) {
124 $url = 'http://unused' . $url;
126 MediaWiki\
suppressWarnings();
127 $a = parse_url( $url );
128 MediaWiki\restoreWarnings
();
130 $path = isset( $a['path'] ) ?
$a['path'] : '';
133 if ( $path == $wgScript && $want !== 'all' ) {
134 // Script inside a rewrite path?
135 // Abort to keep from breaking...
139 $router = new PathRouter
;
141 // Raw PATH_INFO style
142 $router->add( "$wgScript/$1" );
144 if ( isset( $_SERVER['SCRIPT_NAME'] )
145 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
147 # Check for SCRIPT_NAME, we handle index.php explicitly
148 # But we do have some other .php files such as img_auth.php
149 # Don't let root article paths clober the parsing for them
150 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
153 global $wgArticlePath;
154 if ( $wgArticlePath ) {
155 $router->add( $wgArticlePath );
158 global $wgActionPaths;
159 if ( $wgActionPaths ) {
160 $router->add( $wgActionPaths, [ 'action' => '$key' ] );
163 global $wgVariantArticlePath, $wgContLang;
164 if ( $wgVariantArticlePath ) {
165 $router->add( $wgVariantArticlePath,
166 [ 'variant' => '$2' ],
167 [ '$2' => $wgContLang->getVariants() ]
171 Hooks
::run( 'WebRequestPathInfoRouter', [ $router ] );
173 $matches = $router->parse( $path );
175 } elseif ( $wgUsePathInfo ) {
176 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
178 // https://bugs.php.net/bug.php?id=31892
179 // Also reported when ini_get('cgi.fix_pathinfo')==false
180 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
182 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
183 // Regular old PATH_INFO yay
184 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
192 * Work out an appropriate URL prefix containing scheme and host, based on
193 * information detected from $_SERVER
197 public static function detectServer() {
198 global $wgAssumeProxiesUseDefaultProtocolPorts;
200 $proto = self
::detectProtocol();
201 $stdPort = $proto === 'https' ?
443 : 80;
203 $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
206 foreach ( $varNames as $varName ) {
207 if ( !isset( $_SERVER[$varName] ) ) {
211 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
213 // Invalid, do not use
218 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
219 // Bug 70021: Assume that upstream proxy is running on the default
220 // port based on the protocol. We have no reliable way to determine
221 // the actual port in use upstream.
223 } elseif ( $parts[1] === false ) {
224 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
225 $port = $_SERVER['SERVER_PORT'];
226 } // else leave it as $stdPort
233 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
237 * Detect the protocol from $_SERVER.
238 * This is for use prior to Setup.php, when no WebRequest object is available.
239 * At other times, use the non-static function getProtocol().
243 public static function detectProtocol() {
244 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
245 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
246 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
254 * Get the number of seconds to have elapsed since request start,
255 * in fractional seconds, with microsecond resolution.
260 public function getElapsedTime() {
261 return microtime( true ) - $this->requestTime
;
265 * Get the unique request ID.
266 * This is either the value of the UNIQUE_ID envvar (if present) or a
267 * randomly-generated 24-character string.
272 public static function getRequestId() {
273 if ( !self
::$reqId ) {
274 self
::$reqId = isset( $_SERVER['UNIQUE_ID'] )
275 ?
$_SERVER['UNIQUE_ID'] : wfRandomString( 24 );
282 * Override the unique request ID. This is for sub-requests, such as jobs,
283 * that wish to use the same id but are not part of the same execution context.
288 public static function overrideRequestId( $id ) {
293 * Get the current URL protocol (http or https)
296 public function getProtocol() {
297 if ( $this->protocol
=== null ) {
298 $this->protocol
= self
::detectProtocol();
300 return $this->protocol
;
304 * Check for title, action, and/or variant data in the URL
305 * and interpolate it into the GET variables.
306 * This should only be run after $wgContLang is available,
307 * as we may need the list of language variants to determine
308 * available variant URLs.
310 public function interpolateTitle() {
311 // bug 16019: title interpolation on API queries is useless and sometimes harmful
312 if ( defined( 'MW_API' ) ) {
316 $matches = self
::getPathInfo( 'title' );
317 foreach ( $matches as $key => $val ) {
318 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
323 * URL rewriting function; tries to extract page title and,
324 * optionally, one other fixed parameter value from a URL path.
326 * @param string $path The URL path given from the client
327 * @param array $bases One or more URLs, optionally with $1 at the end
328 * @param string|bool $key If provided, the matching key in $bases will be
329 * passed on as the value of this URL parameter
330 * @return array Array of URL variables to interpolate; empty if no match
332 static function extractTitle( $path, $bases, $key = false ) {
333 foreach ( (array)$bases as $keyValue => $base ) {
334 // Find the part after $wgArticlePath
335 $base = str_replace( '$1', '', $base );
336 $baseLen = strlen( $base );
337 if ( substr( $path, 0, $baseLen ) == $base ) {
338 $raw = substr( $path, $baseLen );
340 $matches = [ 'title' => rawurldecode( $raw ) ];
342 $matches[$key] = $keyValue;
352 * Recursively normalizes UTF-8 strings in the given array.
354 * @param string|array $data
355 * @return array|string Cleaned-up version of the given
358 public function normalizeUnicode( $data ) {
359 if ( is_array( $data ) ) {
360 foreach ( $data as $key => $val ) {
361 $data[$key] = $this->normalizeUnicode( $val );
365 $data = isset( $wgContLang ) ?
366 $wgContLang->normalize( $data ) :
367 UtfNormal\Validator
::cleanUp( $data );
373 * Fetch a value from the given array or return $default if it's not set.
376 * @param string $name
377 * @param mixed $default
380 private function getGPCVal( $arr, $name, $default ) {
381 # PHP is so nice to not touch input data, except sometimes:
382 # https://secure.php.net/variables.external#language.variables.external.dot-in-names
383 # Work around PHP *feature* to avoid *bugs* elsewhere.
384 $name = strtr( $name, '.', '_' );
385 if ( isset( $arr[$name] ) ) {
388 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
389 # Check for alternate/legacy character encoding.
390 if ( isset( $wgContLang ) ) {
391 $data = $wgContLang->checkTitleEncoding( $data );
394 $data = $this->normalizeUnicode( $data );
402 * Fetch a scalar from the input without normalization, or return $default
405 * Unlike self::getVal(), this does not perform any normalization on the
409 * @param string $name
410 * @param string|null $default Optional default
413 public function getRawVal( $name, $default = null ) {
414 $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
415 if ( isset( $this->data
[$name] ) && !is_array( $this->data
[$name] ) ) {
416 $val = $this->data
[$name];
420 if ( is_null( $val ) ) {
428 * Fetch a scalar from the input or return $default if it's not set.
429 * Returns a string. Arrays are discarded. Useful for
430 * non-freeform text inputs (e.g. predefined internal text keys
431 * selected by a drop-down menu). For freeform input, see getText().
433 * @param string $name
434 * @param string $default Optional default (or null)
437 public function getVal( $name, $default = null ) {
438 $val = $this->getGPCVal( $this->data
, $name, $default );
439 if ( is_array( $val ) ) {
442 if ( is_null( $val ) ) {
450 * Set an arbitrary value into our get/post data.
452 * @param string $key Key name to use
453 * @param mixed $value Value to set
454 * @return mixed Old value if one was present, null otherwise
456 public function setVal( $key, $value ) {
457 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
458 $this->data
[$key] = $value;
463 * Unset an arbitrary value from our get/post data.
465 * @param string $key Key name to use
466 * @return mixed Old value if one was present, null otherwise
468 public function unsetVal( $key ) {
469 if ( !isset( $this->data
[$key] ) ) {
472 $ret = $this->data
[$key];
473 unset( $this->data
[$key] );
479 * Fetch an array from the input or return $default if it's not set.
480 * If source was scalar, will return an array with a single element.
481 * If no source and no default, returns null.
483 * @param string $name
484 * @param array $default Optional default (or null)
487 public function getArray( $name, $default = null ) {
488 $val = $this->getGPCVal( $this->data
, $name, $default );
489 if ( is_null( $val ) ) {
497 * Fetch an array of integers, or return $default if it's not set.
498 * If source was scalar, will return an array with a single element.
499 * If no source and no default, returns null.
500 * If an array is returned, contents are guaranteed to be integers.
502 * @param string $name
503 * @param array $default Option default (or null)
504 * @return array Array of ints
506 public function getIntArray( $name, $default = null ) {
507 $val = $this->getArray( $name, $default );
508 if ( is_array( $val ) ) {
509 $val = array_map( 'intval', $val );
515 * Fetch an integer value from the input or return $default if not set.
516 * Guaranteed to return an integer; non-numeric input will typically
519 * @param string $name
520 * @param int $default
523 public function getInt( $name, $default = 0 ) {
524 return intval( $this->getRawVal( $name, $default ) );
528 * Fetch an integer value from the input or return null if empty.
529 * Guaranteed to return an integer or null; non-numeric input will
530 * typically return null.
532 * @param string $name
535 public function getIntOrNull( $name ) {
536 $val = $this->getRawVal( $name );
537 return is_numeric( $val )
543 * Fetch a floating point value from the input or return $default if not set.
544 * Guaranteed to return a float; non-numeric input will typically
548 * @param string $name
549 * @param float $default
552 public function getFloat( $name, $default = 0.0 ) {
553 return floatval( $this->getRawVal( $name, $default ) );
557 * Fetch a boolean value from the input or return $default if not set.
558 * Guaranteed to return true or false, with normal PHP semantics for
559 * boolean interpretation of strings.
561 * @param string $name
562 * @param bool $default
565 public function getBool( $name, $default = false ) {
566 return (bool)$this->getRawVal( $name, $default );
570 * Fetch a boolean value from the input or return $default if not set.
571 * Unlike getBool, the string "false" will result in boolean false, which is
572 * useful when interpreting information sent from JavaScript.
574 * @param string $name
575 * @param bool $default
578 public function getFuzzyBool( $name, $default = false ) {
579 return $this->getBool( $name, $default )
580 && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
584 * Return true if the named value is set in the input, whatever that
585 * value is (even "0"). Return false if the named value is not set.
586 * Example use is checking for the presence of check boxes in forms.
588 * @param string $name
591 public function getCheck( $name ) {
592 # Checkboxes and buttons are only present when clicked
593 # Presence connotes truth, absence false
594 return $this->getRawVal( $name, null ) !== null;
598 * Fetch a text string from the given array or return $default if it's not
599 * set. Carriage returns are stripped from the text. This should generally
600 * be used for form "<textarea>" and "<input>" fields, and for
601 * user-supplied freeform text input.
603 * @param string $name
604 * @param string $default Optional
607 public function getText( $name, $default = '' ) {
608 $val = $this->getVal( $name, $default );
609 return str_replace( "\r\n", "\n", $val );
613 * Extracts the given named values into an array.
614 * If no arguments are given, returns all input values.
615 * No transformation is performed on the values.
619 public function getValues() {
620 $names = func_get_args();
621 if ( count( $names ) == 0 ) {
622 $names = array_keys( $this->data
);
626 foreach ( $names as $name ) {
627 $value = $this->getGPCVal( $this->data
, $name, null );
628 if ( !is_null( $value ) ) {
629 $retVal[$name] = $value;
636 * Returns the names of all input values excluding those in $exclude.
638 * @param array $exclude
641 public function getValueNames( $exclude = [] ) {
642 return array_diff( array_keys( $this->getValues() ), $exclude );
646 * Get the values passed in the query string.
647 * No transformation is performed on the values.
649 * @codeCoverageIgnore
652 public function getQueryValues() {
657 * Return the contents of the Query with no decoding. Use when you need to
658 * know exactly what was sent, e.g. for an OAuth signature over the elements.
660 * @codeCoverageIgnore
663 public function getRawQueryString() {
664 return $_SERVER['QUERY_STRING'];
668 * Return the contents of the POST with no decoding. Use when you need to
669 * know exactly what was sent, e.g. for an OAuth signature over the elements.
673 public function getRawPostString() {
674 if ( !$this->wasPosted() ) {
677 return $this->getRawInput();
681 * Return the raw request body, with no processing. Cached since some methods
682 * disallow reading the stream more than once. As stated in the php docs, this
683 * does not work with enctype="multipart/form-data".
687 public function getRawInput() {
688 static $input = null;
689 if ( $input === null ) {
690 $input = file_get_contents( 'php://input' );
696 * Get the HTTP method used for this request.
700 public function getMethod() {
701 return isset( $_SERVER['REQUEST_METHOD'] ) ?
$_SERVER['REQUEST_METHOD'] : 'GET';
705 * Returns true if the present request was reached by a POST operation,
706 * false otherwise (GET, HEAD, or command-line).
708 * Note that values retrieved by the object may come from the
709 * GET URL etc even on a POST request.
713 public function wasPosted() {
714 return $this->getMethod() == 'POST';
718 * Return the session for this request
720 * This might unpersist an existing session if it was invalid.
723 * @note For performance, keep the session locally if you will be making
724 * much use of it instead of calling this method repeatedly.
727 public function getSession() {
728 if ( $this->sessionId
!== null ) {
729 $session = SessionManager
::singleton()->getSessionById( (string)$this->sessionId
, true, $this );
735 $session = SessionManager
::singleton()->getSessionForRequest( $this );
736 $this->sessionId
= $session->getSessionId();
741 * Set the session for this request
743 * @private For use by MediaWiki\Session classes only
744 * @param SessionId $sessionId
746 public function setSessionId( SessionId
$sessionId ) {
747 $this->sessionId
= $sessionId;
751 * Get the session id for this request, if any
753 * @private For use by MediaWiki\Session classes only
754 * @return SessionId|null
756 public function getSessionId() {
757 return $this->sessionId
;
761 * Get a cookie from the $_COOKIE jar
763 * @param string $key The name of the cookie
764 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
765 * @param mixed $default What to return if the value isn't found
766 * @return mixed Cookie value or $default if the cookie not set
768 public function getCookie( $key, $prefix = null, $default = null ) {
769 if ( $prefix === null ) {
770 global $wgCookiePrefix;
771 $prefix = $wgCookiePrefix;
773 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
777 * Return the path and query string portion of the main request URI.
778 * This will be suitable for use as a relative link in HTML output.
780 * @throws MWException
783 public static function getGlobalRequestURL() {
784 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
785 $base = $_SERVER['REQUEST_URI'];
786 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
787 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
789 // Probably IIS; doesn't set REQUEST_URI
790 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
791 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
792 $base = $_SERVER['SCRIPT_NAME'];
793 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
794 $base .= '?' . $_SERVER['QUERY_STRING'];
797 // This shouldn't happen!
798 throw new MWException( "Web server doesn't provide either " .
799 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
800 "of your web server configuration to https://phabricator.wikimedia.org/" );
802 // User-agents should not send a fragment with the URI, but
803 // if they do, and the web server passes it on to us, we
804 // need to strip it or we get false-positive redirect loops
805 // or weird output URLs
806 $hash = strpos( $base, '#' );
807 if ( $hash !== false ) {
808 $base = substr( $base, 0, $hash );
811 if ( $base[0] == '/' ) {
812 // More than one slash will look like it is protocol relative
813 return preg_replace( '!^/+!', '/', $base );
815 // We may get paths with a host prepended; strip it.
816 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
821 * Return the path and query string portion of the request URI.
822 * This will be suitable for use as a relative link in HTML output.
824 * @throws MWException
827 public function getRequestURL() {
828 return self
::getGlobalRequestURL();
832 * Return the request URI with the canonical service and hostname, path,
833 * and query string. This will be suitable for use as an absolute link
834 * in HTML or other output.
836 * If $wgServer is protocol-relative, this will return a fully
837 * qualified URL with the protocol that was used for this request.
841 public function getFullRequestURL() {
842 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
847 * @param string $value
850 public function appendQueryValue( $key, $value ) {
851 return $this->appendQueryArray( [ $key => $value ] );
855 * Appends or replaces value of query variables.
857 * @param array $array Array of values to replace/add to query
860 public function appendQueryArray( $array ) {
861 $newquery = $this->getQueryValues();
862 unset( $newquery['title'] );
863 $newquery = array_merge( $newquery, $array );
865 return wfArrayToCgi( $newquery );
869 * Check for limit and offset parameters on the input, and return sensible
870 * defaults if not given. The limit must be positive and is capped at 5000.
871 * Offset must be positive but is not capped.
873 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
874 * @param string $optionname To specify an option other than rclimit to pull from.
875 * @return int[] First element is limit, second is offset
877 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
880 $limit = $this->getInt( 'limit', 0 );
884 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
885 $limit = $wgUser->getIntOption( $optionname );
890 if ( $limit > 5000 ) {
891 $limit = 5000; # We have *some* limits...
894 $offset = $this->getInt( 'offset', 0 );
899 return [ $limit, $offset ];
903 * Return the path to the temporary file where PHP has stored the upload.
906 * @return string|null String or null if no such file.
908 public function getFileTempname( $key ) {
909 $file = new WebRequestUpload( $this, $key );
910 return $file->getTempName();
914 * Return the upload error or 0
919 public function getUploadError( $key ) {
920 $file = new WebRequestUpload( $this, $key );
921 return $file->getError();
925 * Return the original filename of the uploaded file, as reported by
926 * the submitting user agent. HTML-style character entities are
927 * interpreted and normalized to Unicode normalization form C, in part
928 * to deal with weird input from Safari with non-ASCII filenames.
930 * Other than this the name is not verified for being a safe filename.
933 * @return string|null String or null if no such file.
935 public function getFileName( $key ) {
936 $file = new WebRequestUpload( $this, $key );
937 return $file->getName();
941 * Return a WebRequestUpload object corresponding to the key
944 * @return WebRequestUpload
946 public function getUpload( $key ) {
947 return new WebRequestUpload( $this, $key );
951 * Return a handle to WebResponse style object, for setting cookies,
952 * headers and other stuff, for Request being worked on.
954 * @return WebResponse
956 public function response() {
957 /* Lazy initialization of response object for this request */
958 if ( !is_object( $this->response
) ) {
959 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
960 $this->response
= new $class();
962 return $this->response
;
966 * Initialise the header list
968 protected function initHeaders() {
969 if ( count( $this->headers
) ) {
973 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
974 if ( $apacheHeaders ) {
975 foreach ( $apacheHeaders as $tempName => $tempValue ) {
976 $this->headers
[strtoupper( $tempName )] = $tempValue;
979 foreach ( $_SERVER as $name => $value ) {
980 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
981 $name = str_replace( '_', '-', substr( $name, 5 ) );
982 $this->headers
[$name] = $value;
983 } elseif ( $name === 'CONTENT_LENGTH' ) {
984 $this->headers
['CONTENT-LENGTH'] = $value;
991 * Get an array containing all request headers
993 * @return array Mapping header name to its value
995 public function getAllHeaders() {
996 $this->initHeaders();
997 return $this->headers
;
1001 * Get a request header, or false if it isn't set.
1003 * @param string $name Case-insensitive header name
1004 * @param int $flags Bitwise combination of:
1005 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1006 * of values, as described in RFC 2616 § 4.2.
1008 * @return string|array|bool False if header is unset; otherwise the
1009 * header value(s) as either a string (the default) or an array, if
1010 * WebRequest::GETHEADER_LIST flag was set.
1012 public function getHeader( $name, $flags = 0 ) {
1013 $this->initHeaders();
1014 $name = strtoupper( $name );
1015 if ( !isset( $this->headers
[$name] ) ) {
1018 $value = $this->headers
[$name];
1019 if ( $flags & self
::GETHEADER_LIST
) {
1020 $value = array_map( 'trim', explode( ',', $value ) );
1026 * Get data from the session
1028 * @note Prefer $this->getSession() instead if making multiple calls.
1029 * @param string $key Name of key in the session
1032 public function getSessionData( $key ) {
1033 return $this->getSession()->get( $key );
1039 * @note Prefer $this->getSession() instead if making multiple calls.
1040 * @param string $key Name of key in the session
1041 * @param mixed $data
1043 public function setSessionData( $key, $data ) {
1044 $this->getSession()->set( $key, $data );
1048 * Check if Internet Explorer will detect an incorrect cache extension in
1049 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1050 * message or redirect to a safer URL. Returns true if the URL is OK, and
1051 * false if an error message has been shown and the request should be aborted.
1053 * @param array $extWhitelist
1057 public function checkUrlExtension( $extWhitelist = [] ) {
1058 $extWhitelist[] = 'php';
1059 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1060 if ( !$this->wasPosted() ) {
1061 $newUrl = IEUrlExtension
::fixUrlForIE6(
1062 $this->getFullRequestURL(), $extWhitelist );
1063 if ( $newUrl !== false ) {
1064 $this->doSecurityRedirect( $newUrl );
1068 throw new HttpError( 403,
1069 'Invalid file extension found in the path info or query string.' );
1075 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1076 * IE 6. Returns true if it was successful, false otherwise.
1078 * @param string $url
1081 protected function doSecurityRedirect( $url ) {
1082 header( 'Location: ' . $url );
1083 header( 'Content-Type: text/html' );
1084 $encUrl = htmlspecialchars( $url );
1089 <title>Security redirect</title>
1092 <h1>Security redirect</h1>
1094 We can't serve non-HTML content from the URL you have requested
, because
1095 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
1097 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
1098 URL you have requested
, except that
"&*" is appended
. This prevents Internet
1099 Explorer from seeing a bogus file extension
.
1109 * Parse the Accept-Language header sent by the client into an array
1111 * @return array Array( languageCode => q-value ) sorted by q-value in
1112 * descending order then appearing time in the header in ascending order.
1113 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1114 * This is aligned with rfc2616 section 14.4
1115 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1117 public function getAcceptLang() {
1118 // Modified version of code found at
1119 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1120 $acceptLang = $this->getHeader( 'Accept-Language' );
1121 if ( !$acceptLang ) {
1125 // Return the language codes in lower case
1126 $acceptLang = strtolower( $acceptLang );
1128 // Break up string into pieces (languages and q factors)
1131 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1136 if ( !count( $lang_parse[1] ) ) {
1140 $langcodes = $lang_parse[1];
1141 $qvalues = $lang_parse[4];
1142 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1144 // Set default q factor to 1
1145 foreach ( $indices as $index ) {
1146 if ( $qvalues[$index] === '' ) {
1147 $qvalues[$index] = 1;
1148 } elseif ( $qvalues[$index] == 0 ) {
1149 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1153 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1154 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1156 // Create a list like "en" => 0.8
1157 $langs = array_combine( $langcodes, $qvalues );
1163 * Fetch the raw IP from the request
1167 * @throws MWException
1170 protected function getRawIP() {
1171 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1175 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1176 throw new MWException( __METHOD__
1177 . " : Could not determine the remote IP address due to multiple values." );
1179 $ipchain = $_SERVER['REMOTE_ADDR'];
1182 return IP
::canonicalize( $ipchain );
1186 * Work out the IP address based on various globals
1187 * For trusted proxies, use the XFF client IP (first of the chain)
1191 * @throws MWException
1194 public function getIP() {
1195 global $wgUsePrivateIPs;
1197 # Return cached result
1198 if ( $this->ip
!== null ) {
1202 # collect the originating ips
1203 $ip = $this->getRawIP();
1205 throw new MWException( 'Unable to determine IP.' );
1209 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1210 if ( $forwardedFor !== false ) {
1211 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1212 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1213 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1214 $ipchain = array_reverse( $ipchain );
1215 array_unshift( $ipchain, $ip );
1217 # Step through XFF list and find the last address in the list which is a
1218 # trusted server. Set $ip to the IP address given by that trusted server,
1219 # unless the address is not sensible (e.g. private). However, prefer private
1220 # IP addresses over proxy servers controlled by this site (more sensible).
1221 # Note that some XFF values might be "unknown" with Squid/Varnish.
1222 foreach ( $ipchain as $i => $curIP ) {
1223 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1224 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1225 ||
!$proxyLookup->isTrustedProxy( $curIP )
1227 break; // IP is not valid/trusted or does not point to anything
1230 IP
::isPublic( $ipchain[$i +
1] ) ||
1232 $proxyLookup->isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1234 // Follow the next IP according to the proxy
1235 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1236 if ( !$nextIP && $isConfigured ) {
1237 // We have not yet made it past CDN/proxy servers of this site,
1238 // so either they are misconfigured or there is some IP spoofing.
1239 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1242 // keep traversing the chain
1249 # Allow extensions to improve our guess
1250 Hooks
::run( 'GetIP', [ &$ip ] );
1253 throw new MWException( "Unable to determine IP." );
1256 wfDebug( "IP: $ip\n" );
1266 public function setIP( $ip ) {
1271 * Check if this request uses a "safe" HTTP method
1273 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1274 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1275 * like POST and PUT are typical of non-safe requests which often change content.
1278 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1279 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1282 public function hasSafeMethod() {
1283 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1284 return false; // CLI mode
1287 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1291 * Whether this request should be identified as being "safe"
1293 * This means that the client is not requesting any state changes and that database writes
1294 * are not inherently required. Ideally, no visible updates would happen at all. If they
1295 * must, then they should not be publically attributed to the end user.
1298 * - Cache populations and refreshes MAY occur.
1299 * - Private user session updates and private server logging MAY occur.
1300 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1301 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1304 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1305 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1308 public function isSafeRequest() {
1309 if ( $this->markedAsSafe
&& $this->wasPosted() ) {
1310 return true; // marked as a "safe" POST
1313 return $this->hasSafeMethod();
1317 * Mark this request as identified as being nullipotent even if it is a POST request
1319 * POST requests are often used due to the need for a client payload, even if the request
1320 * is otherwise equivalent to a "safe method" request.
1322 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1323 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1326 public function markAsSafeRequest() {
1327 $this->markedAsSafe
= true;