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
;
30 use Wikimedia\AtEase\AtEase
;
32 // The point of this class is to be a wrapper around super globals
33 // phpcs:disable MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
36 * The WebRequest class encapsulates getting at data passed in the
37 * URL or via a POSTed form stripping illegal input characters and
38 * normalizing Unicode sequences.
46 protected $headers = [];
49 * Flag to make WebRequest::getHeader return an array of values.
52 const GETHEADER_LIST
= 1;
55 * The unique request ID.
58 private static $reqId;
61 * Lazy-init response object
67 * Cached client IP address
73 * The timestamp of the start of the request, with microsecond precision.
76 protected $requestTime;
85 * @var SessionId|null Session ID to use for this
86 * request. We can't save the session directly due to reference cycles not
87 * working too well (slow GC in Zend and never collected in HHVM).
89 protected $sessionId = null;
91 /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
92 protected $markedAsSafe = false;
97 public function __construct() {
98 $this->requestTime
= $_SERVER['REQUEST_TIME_FLOAT'];
100 // POST overrides GET data
101 // We don't use $_REQUEST here to avoid interference from cookies...
102 $this->data
= $_POST +
$_GET;
106 * Extract relevant query arguments from the http request uri's path
107 * to be merged with the normal php provided query arguments.
108 * Tries to use the REQUEST_URI data if available and parses it
109 * according to the wiki's configuration looking for any known pattern.
111 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
112 * provided by the server if any and use that to set a 'title' parameter.
114 * @param string $want If this is not 'all', then the function
115 * will return an empty array if it determines that the URL is
116 * inside a rewrite path.
118 * @return array Any query arguments found in path matches.
120 public static function getPathInfo( $want = 'all' ) {
121 // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
122 // And also by Apache 2.x, double slashes are converted to single slashes.
123 // So we will use REQUEST_URI if possible.
124 if ( isset( $_SERVER['REQUEST_URI'] ) ) {
125 // Slurp out the path portion to examine...
126 $url = $_SERVER['REQUEST_URI'];
127 if ( !preg_match( '!^https?://!', $url ) ) {
128 $url = 'http://unused' . $url;
130 AtEase
::suppressWarnings();
131 $a = parse_url( $url );
132 AtEase
::restoreWarnings();
136 $path = $a['path'] ??
'';
139 if ( $path == $wgScript && $want !== 'all' ) {
140 // Script inside a rewrite path?
141 // Abort to keep from breaking...
145 $router = new PathRouter
;
147 // Raw PATH_INFO style
148 $router->add( "$wgScript/$1" );
150 if ( isset( $_SERVER['SCRIPT_NAME'] )
151 && strpos( $_SERVER['SCRIPT_NAME'], '.php' ) !== false
153 // Check for SCRIPT_NAME, we handle index.php explicitly
154 // But we do have some other .php files such as img_auth.php
155 // Don't let root article paths clober the parsing for them
156 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
159 global $wgArticlePath;
160 if ( $wgArticlePath ) {
161 $router->add( $wgArticlePath );
164 global $wgActionPaths;
165 $articlePaths = PathRouter
::getActionPaths( $wgActionPaths, $wgArticlePath );
166 if ( $articlePaths ) {
167 $router->add( $articlePaths, [ 'action' => '$key' ] );
170 global $wgVariantArticlePath;
171 if ( $wgVariantArticlePath ) {
172 $router->add( $wgVariantArticlePath,
173 [ 'variant' => '$2' ],
174 [ '$2' => MediaWikiServices
::getInstance()->getContentLanguage()->
179 Hooks
::run( 'WebRequestPathInfoRouter', [ $router ] );
181 $matches = $router->parse( $path );
183 global $wgUsePathInfo;
185 if ( $wgUsePathInfo ) {
186 if ( !empty( $_SERVER['ORIG_PATH_INFO'] ) ) {
188 // https://bugs.php.net/bug.php?id=31892
189 // Also reported when ini_get('cgi.fix_pathinfo')==false
190 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
191 } elseif ( !empty( $_SERVER['PATH_INFO'] ) ) {
192 // Regular old PATH_INFO yay
193 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
202 * Work out an appropriate URL prefix containing scheme and host, based on
203 * information detected from $_SERVER
207 public static function detectServer() {
208 global $wgAssumeProxiesUseDefaultProtocolPorts;
210 $proto = self
::detectProtocol();
211 $stdPort = $proto === 'https' ?
443 : 80;
213 $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
216 foreach ( $varNames as $varName ) {
217 if ( !isset( $_SERVER[$varName] ) ) {
221 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
223 // Invalid, do not use
228 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
229 // T72021: Assume that upstream proxy is running on the default
230 // port based on the protocol. We have no reliable way to determine
231 // the actual port in use upstream.
233 } elseif ( $parts[1] === false ) {
234 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
235 $port = $_SERVER['SERVER_PORT'];
236 } // else leave it as $stdPort
243 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
247 * Detect the protocol from $_SERVER.
248 * This is for use prior to Setup.php, when no WebRequest object is available.
249 * At other times, use the non-static function getProtocol().
253 public static function detectProtocol() {
254 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
255 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
256 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
264 * Get the number of seconds to have elapsed since request start,
265 * in fractional seconds, with microsecond resolution.
270 public function getElapsedTime() {
271 return microtime( true ) - $this->requestTime
;
275 * Get the unique request ID.
276 * This is either the value of the UNIQUE_ID envvar (if present) or a
277 * randomly-generated 24-character string.
282 public static function getRequestId() {
283 // This method is called from various error handlers and should be kept simple.
285 if ( self
::$reqId ) {
289 global $wgAllowExternalReqID;
291 self
::$reqId = $_SERVER['UNIQUE_ID'] ??
wfRandomString( 24 );
292 if ( $wgAllowExternalReqID ) {
293 $id = RequestContext
::getMain()->getRequest()->getHeader( 'X-Request-Id' );
303 * Override the unique request ID. This is for sub-requests, such as jobs,
304 * that wish to use the same id but are not part of the same execution context.
309 public static function overrideRequestId( $id ) {
314 * Get the current URL protocol (http or https)
317 public function getProtocol() {
318 if ( $this->protocol
=== null ) {
319 $this->protocol
= self
::detectProtocol();
321 return $this->protocol
;
325 * Check for title, action, and/or variant data in the URL
326 * and interpolate it into the GET variables.
327 * This should only be run after the content language is available,
328 * as we may need the list of language variants to determine
329 * available variant URLs.
331 public function interpolateTitle() {
332 // T18019: title interpolation on API queries is useless and sometimes harmful
333 if ( defined( 'MW_API' ) ) {
337 $matches = self
::getPathInfo( 'title' );
338 foreach ( $matches as $key => $val ) {
339 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
344 * URL rewriting function; tries to extract page title and,
345 * optionally, one other fixed parameter value from a URL path.
347 * @param string $path The URL path given from the client
348 * @param array $bases One or more URLs, optionally with $1 at the end
349 * @param string|bool $key If provided, the matching key in $bases will be
350 * passed on as the value of this URL parameter
351 * @return array Array of URL variables to interpolate; empty if no match
353 static function extractTitle( $path, $bases, $key = false ) {
354 foreach ( (array)$bases as $keyValue => $base ) {
355 // Find the part after $wgArticlePath
356 $base = str_replace( '$1', '', $base );
357 $baseLen = strlen( $base );
358 if ( substr( $path, 0, $baseLen ) == $base ) {
359 $raw = substr( $path, $baseLen );
361 $matches = [ 'title' => rawurldecode( $raw ) ];
363 $matches[$key] = $keyValue;
373 * Recursively normalizes UTF-8 strings in the given array.
375 * @param string|array $data
376 * @return array|string Cleaned-up version of the given
379 public function normalizeUnicode( $data ) {
380 if ( is_array( $data ) ) {
381 foreach ( $data as $key => $val ) {
382 $data[$key] = $this->normalizeUnicode( $val );
385 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
386 $data = $contLang ?
$contLang->normalize( $data ) :
387 UtfNormal\Validator
::cleanUp( $data );
393 * Fetch a value from the given array or return $default if it's not set.
396 * @param string $name
397 * @param mixed $default
400 private function getGPCVal( $arr, $name, $default ) {
401 # PHP is so nice to not touch input data, except sometimes:
402 # https://www.php.net/variables.external#language.variables.external.dot-in-names
403 # Work around PHP *feature* to avoid *bugs* elsewhere.
404 $name = strtr( $name, '.', '_' );
406 if ( !isset( $arr[$name] ) ) {
411 # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
412 $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
413 if ( !$isAsciiStr ) {
414 if ( isset( $_GET[$name] ) && is_string( $data ) ) {
415 # Check for alternate/legacy character encoding.
416 $data = MediaWikiServices
::getInstance()
417 ->getContentLanguage()
418 ->checkTitleEncoding( $data );
420 $data = $this->normalizeUnicode( $data );
427 * Fetch a scalar from the input without normalization, or return $default
430 * Unlike self::getVal(), this does not perform any normalization on the
434 * @param string $name
435 * @param string|null $default
436 * @return string|null
438 public function getRawVal( $name, $default = null ) {
439 $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
440 if ( isset( $this->data
[$name] ) && !is_array( $this->data
[$name] ) ) {
441 $val = $this->data
[$name];
445 if ( is_null( $val ) ) {
453 * Fetch a scalar from the input or return $default if it's not set.
454 * Returns a string. Arrays are discarded. Useful for
455 * non-freeform text inputs (e.g. predefined internal text keys
456 * selected by a drop-down menu). For freeform input, see getText().
458 * @param string $name
459 * @param string|null $default Optional default (or null)
460 * @return string|null
462 public function getVal( $name, $default = null ) {
463 $val = $this->getGPCVal( $this->data
, $name, $default );
464 if ( is_array( $val ) ) {
467 if ( is_null( $val ) ) {
475 * Set an arbitrary value into our get/post data.
477 * @param string $key Key name to use
478 * @param mixed $value Value to set
479 * @return mixed Old value if one was present, null otherwise
481 public function setVal( $key, $value ) {
482 $ret = $this->data
[$key] ??
null;
483 $this->data
[$key] = $value;
488 * Unset an arbitrary value from our get/post data.
490 * @param string $key Key name to use
491 * @return mixed Old value if one was present, null otherwise
493 public function unsetVal( $key ) {
494 if ( !isset( $this->data
[$key] ) ) {
497 $ret = $this->data
[$key];
498 unset( $this->data
[$key] );
504 * Fetch an array from the input or return $default if it's not set.
505 * If source was scalar, will return an array with a single element.
506 * If no source and no default, returns null.
508 * @param string $name
509 * @param array|null $default Optional default (or null)
512 public function getArray( $name, $default = null ) {
513 $val = $this->getGPCVal( $this->data
, $name, $default );
514 if ( is_null( $val ) ) {
522 * Fetch an array of integers, or return $default if it's not set.
523 * If source was scalar, will return an array with a single element.
524 * If no source and no default, returns null.
525 * If an array is returned, contents are guaranteed to be integers.
527 * @param string $name
528 * @param array|null $default Option default (or null)
529 * @return array Array of ints
531 public function getIntArray( $name, $default = null ) {
532 $val = $this->getArray( $name, $default );
533 if ( is_array( $val ) ) {
534 $val = array_map( 'intval', $val );
540 * Fetch an integer value from the input or return $default if not set.
541 * Guaranteed to return an integer; non-numeric input will typically
544 * @param string $name
545 * @param int $default
548 public function getInt( $name, $default = 0 ) {
549 return intval( $this->getRawVal( $name, $default ) );
553 * Fetch an integer value from the input or return null if empty.
554 * Guaranteed to return an integer or null; non-numeric input will
555 * typically return null.
557 * @param string $name
560 public function getIntOrNull( $name ) {
561 $val = $this->getRawVal( $name );
562 return is_numeric( $val )
568 * Fetch a floating point value from the input or return $default if not set.
569 * Guaranteed to return a float; non-numeric input will typically
573 * @param string $name
574 * @param float $default
577 public function getFloat( $name, $default = 0.0 ) {
578 return floatval( $this->getRawVal( $name, $default ) );
582 * Fetch a boolean value from the input or return $default if not set.
583 * Guaranteed to return true or false, with normal PHP semantics for
584 * boolean interpretation of strings.
586 * @param string $name
587 * @param bool $default
590 public function getBool( $name, $default = false ) {
591 return (bool)$this->getRawVal( $name, $default );
595 * Fetch a boolean value from the input or return $default if not set.
596 * Unlike getBool, the string "false" will result in boolean false, which is
597 * useful when interpreting information sent from JavaScript.
599 * @param string $name
600 * @param bool $default
603 public function getFuzzyBool( $name, $default = false ) {
604 return $this->getBool( $name, $default )
605 && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
609 * Return true if the named value is set in the input, whatever that
610 * value is (even "0"). Return false if the named value is not set.
611 * Example use is checking for the presence of check boxes in forms.
613 * @param string $name
616 public function getCheck( $name ) {
617 # Checkboxes and buttons are only present when clicked
618 # Presence connotes truth, absence false
619 return $this->getRawVal( $name, null ) !== null;
623 * Fetch a text string from the given array or return $default if it's not
624 * set. Carriage returns are stripped from the text. This should generally
625 * be used for form "<textarea>" and "<input>" fields, and for
626 * user-supplied freeform text input.
628 * @param string $name
629 * @param string $default Optional
632 public function getText( $name, $default = '' ) {
633 $val = $this->getVal( $name, $default );
634 return str_replace( "\r\n", "\n", $val );
638 * Extracts the given named values into an array.
639 * If no arguments are given, returns all input values.
640 * No transformation is performed on the values.
644 public function getValues() {
645 $names = func_get_args();
646 if ( count( $names ) == 0 ) {
647 $names = array_keys( $this->data
);
651 foreach ( $names as $name ) {
652 $value = $this->getGPCVal( $this->data
, $name, null );
653 if ( !is_null( $value ) ) {
654 $retVal[$name] = $value;
661 * Returns the names of all input values excluding those in $exclude.
663 * @param array $exclude
666 public function getValueNames( $exclude = [] ) {
667 return array_diff( array_keys( $this->getValues() ), $exclude );
671 * Get the values passed in the query string.
672 * No transformation is performed on the values.
674 * @codeCoverageIgnore
677 public function getQueryValues() {
682 * Get the values passed via POST.
683 * No transformation is performed on the values.
686 * @codeCoverageIgnore
689 public function getPostValues() {
694 * Return the contents of the Query with no decoding. Use when you need to
695 * know exactly what was sent, e.g. for an OAuth signature over the elements.
697 * @codeCoverageIgnore
700 public function getRawQueryString() {
701 return $_SERVER['QUERY_STRING'];
705 * Return the contents of the POST with no decoding. Use when you need to
706 * know exactly what was sent, e.g. for an OAuth signature over the elements.
710 public function getRawPostString() {
711 if ( !$this->wasPosted() ) {
714 return $this->getRawInput();
718 * Return the raw request body, with no processing. Cached since some methods
719 * disallow reading the stream more than once. As stated in the php docs, this
720 * does not work with enctype="multipart/form-data".
724 public function getRawInput() {
725 static $input = null;
726 if ( $input === null ) {
727 $input = file_get_contents( 'php://input' );
733 * Get the HTTP method used for this request.
737 public function getMethod() {
738 return $_SERVER['REQUEST_METHOD'] ??
'GET';
742 * Returns true if the present request was reached by a POST operation,
743 * false otherwise (GET, HEAD, or command-line).
745 * Note that values retrieved by the object may come from the
746 * GET URL etc even on a POST request.
750 public function wasPosted() {
751 return $this->getMethod() == 'POST';
755 * Return the session for this request
757 * This might unpersist an existing session if it was invalid.
760 * @note For performance, keep the session locally if you will be making
761 * much use of it instead of calling this method repeatedly.
764 public function getSession() {
765 if ( $this->sessionId
!== null ) {
766 $session = SessionManager
::singleton()->getSessionById( (string)$this->sessionId
, true, $this );
772 $session = SessionManager
::singleton()->getSessionForRequest( $this );
773 $this->sessionId
= $session->getSessionId();
778 * Set the session for this request
780 * @private For use by MediaWiki\Session classes only
781 * @param SessionId $sessionId
783 public function setSessionId( SessionId
$sessionId ) {
784 $this->sessionId
= $sessionId;
788 * Get the session id for this request, if any
790 * @private For use by MediaWiki\Session classes only
791 * @return SessionId|null
793 public function getSessionId() {
794 return $this->sessionId
;
798 * Get a cookie from the $_COOKIE jar
800 * @param string $key The name of the cookie
801 * @param string|null $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
802 * @param mixed|null $default What to return if the value isn't found
803 * @return mixed Cookie value or $default if the cookie not set
805 public function getCookie( $key, $prefix = null, $default = null ) {
806 if ( $prefix === null ) {
807 global $wgCookiePrefix;
808 $prefix = $wgCookiePrefix;
810 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
814 * Return the path and query string portion of the main request URI.
815 * This will be suitable for use as a relative link in HTML output.
817 * @throws MWException
820 public static function getGlobalRequestURL() {
821 // This method is called on fatal errors; it should not depend on anything complex.
823 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
824 $base = $_SERVER['REQUEST_URI'];
825 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
826 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
828 // Probably IIS; doesn't set REQUEST_URI
829 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
830 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
831 $base = $_SERVER['SCRIPT_NAME'];
832 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
833 $base .= '?' . $_SERVER['QUERY_STRING'];
836 // This shouldn't happen!
837 throw new MWException( "Web server doesn't provide either " .
838 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
839 "of your web server configuration to https://phabricator.wikimedia.org/" );
841 // User-agents should not send a fragment with the URI, but
842 // if they do, and the web server passes it on to us, we
843 // need to strip it or we get false-positive redirect loops
844 // or weird output URLs
845 $hash = strpos( $base, '#' );
846 if ( $hash !== false ) {
847 $base = substr( $base, 0, $hash );
850 if ( $base[0] == '/' ) {
851 // More than one slash will look like it is protocol relative
852 return preg_replace( '!^/+!', '/', $base );
854 // We may get paths with a host prepended; strip it.
855 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
860 * Return the path and query string portion of the request URI.
861 * This will be suitable for use as a relative link in HTML output.
863 * @throws MWException
866 public function getRequestURL() {
867 return self
::getGlobalRequestURL();
871 * Return the request URI with the canonical service and hostname, path,
872 * and query string. This will be suitable for use as an absolute link
873 * in HTML or other output.
875 * If $wgServer is protocol-relative, this will return a fully
876 * qualified URL with the protocol of this request object.
880 public function getFullRequestURL() {
881 // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
882 // do not rely on state from the global $wgRequest object (which it would,
883 // via wfGetServerUrl/wfExpandUrl/$wgRequest->protocol).
884 if ( $this->getProtocol() === 'http' ) {
885 return wfGetServerUrl( PROTO_HTTP
) . $this->getRequestURL();
887 return wfGetServerUrl( PROTO_HTTPS
) . $this->getRequestURL();
893 * @param string $value
896 public function appendQueryValue( $key, $value ) {
897 return $this->appendQueryArray( [ $key => $value ] );
901 * Appends or replaces value of query variables.
903 * @param array $array Array of values to replace/add to query
906 public function appendQueryArray( $array ) {
907 $newquery = $this->getQueryValues();
908 unset( $newquery['title'] );
909 $newquery = array_merge( $newquery, $array );
911 return wfArrayToCgi( $newquery );
915 * Check for limit and offset parameters on the input, and return sensible
916 * defaults if not given. The limit must be positive and is capped at 5000.
917 * Offset must be positive but is not capped.
919 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
920 * @param string $optionname To specify an option other than rclimit to pull from.
921 * @return int[] First element is limit, second is offset
923 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
926 $limit = $this->getInt( 'limit', 0 );
930 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
931 $limit = $wgUser->getIntOption( $optionname );
936 if ( $limit > 5000 ) {
937 $limit = 5000; # We have *some* limits...
940 $offset = $this->getInt( 'offset', 0 );
945 return [ $limit, $offset ];
949 * Return the path to the temporary file where PHP has stored the upload.
952 * @return string|null String or null if no such file.
954 public function getFileTempname( $key ) {
955 $file = new WebRequestUpload( $this, $key );
956 return $file->getTempName();
960 * Return the upload error or 0
965 public function getUploadError( $key ) {
966 $file = new WebRequestUpload( $this, $key );
967 return $file->getError();
971 * Return the original filename of the uploaded file, as reported by
972 * the submitting user agent. HTML-style character entities are
973 * interpreted and normalized to Unicode normalization form C, in part
974 * to deal with weird input from Safari with non-ASCII filenames.
976 * Other than this the name is not verified for being a safe filename.
979 * @return string|null String or null if no such file.
981 public function getFileName( $key ) {
982 $file = new WebRequestUpload( $this, $key );
983 return $file->getName();
987 * Return a WebRequestUpload object corresponding to the key
990 * @return WebRequestUpload
992 public function getUpload( $key ) {
993 return new WebRequestUpload( $this, $key );
997 * Return a handle to WebResponse style object, for setting cookies,
998 * headers and other stuff, for Request being worked on.
1000 * @return WebResponse
1002 public function response() {
1003 /* Lazy initialization of response object for this request */
1004 if ( !is_object( $this->response
) ) {
1005 $class = ( $this instanceof FauxRequest
) ? FauxResponse
::class : WebResponse
::class;
1006 $this->response
= new $class();
1008 return $this->response
;
1012 * Initialise the header list
1014 protected function initHeaders() {
1015 if ( count( $this->headers
) ) {
1019 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
1020 if ( $apacheHeaders ) {
1021 foreach ( $apacheHeaders as $tempName => $tempValue ) {
1022 $this->headers
[strtoupper( $tempName )] = $tempValue;
1025 foreach ( $_SERVER as $name => $value ) {
1026 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
1027 $name = str_replace( '_', '-', substr( $name, 5 ) );
1028 $this->headers
[$name] = $value;
1029 } elseif ( $name === 'CONTENT_LENGTH' ) {
1030 $this->headers
['CONTENT-LENGTH'] = $value;
1037 * Get an array containing all request headers
1039 * @return array Mapping header name to its value
1041 public function getAllHeaders() {
1042 $this->initHeaders();
1043 return $this->headers
;
1047 * Get a request header, or false if it isn't set.
1049 * @param string $name Case-insensitive header name
1050 * @param int $flags Bitwise combination of:
1051 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1052 * of values, as described in RFC 2616 § 4.2.
1054 * @return string|array|bool False if header is unset; otherwise the
1055 * header value(s) as either a string (the default) or an array, if
1056 * WebRequest::GETHEADER_LIST flag was set.
1058 public function getHeader( $name, $flags = 0 ) {
1059 $this->initHeaders();
1060 $name = strtoupper( $name );
1061 if ( !isset( $this->headers
[$name] ) ) {
1064 $value = $this->headers
[$name];
1065 if ( $flags & self
::GETHEADER_LIST
) {
1066 $value = array_map( 'trim', explode( ',', $value ) );
1072 * Get data from the session
1074 * @note Prefer $this->getSession() instead if making multiple calls.
1075 * @param string $key Name of key in the session
1078 public function getSessionData( $key ) {
1079 return $this->getSession()->get( $key );
1085 * @note Prefer $this->getSession() instead if making multiple calls.
1086 * @param string $key Name of key in the session
1087 * @param mixed $data
1089 public function setSessionData( $key, $data ) {
1090 $this->getSession()->set( $key, $data );
1094 * Check if Internet Explorer will detect an incorrect cache extension in
1095 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1096 * message or redirect to a safer URL. Returns true if the URL is OK, and
1097 * false if an error message has been shown and the request should be aborted.
1099 * @param array $extWhitelist
1103 public function checkUrlExtension( $extWhitelist = [] ) {
1104 $extWhitelist[] = 'php';
1105 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1106 if ( !$this->wasPosted() ) {
1107 $newUrl = IEUrlExtension
::fixUrlForIE6(
1108 $this->getFullRequestURL(), $extWhitelist );
1109 if ( $newUrl !== false ) {
1110 $this->doSecurityRedirect( $newUrl );
1114 throw new HttpError( 403,
1115 'Invalid file extension found in the path info or query string.' );
1121 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1122 * IE 6. Returns true if it was successful, false otherwise.
1124 * @param string $url
1127 protected function doSecurityRedirect( $url ) {
1128 header( 'Location: ' . $url );
1129 header( 'Content-Type: text/html' );
1130 $encUrl = htmlspecialchars( $url );
1135 <title>Security redirect</title>
1138 <h1>Security redirect</h1>
1140 We can't serve non-HTML content from the URL you have requested
, because
1141 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
1143 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
1144 URL you have requested
, except that
"&*" is appended
. This prevents Internet
1145 Explorer from seeing a bogus file extension
.
1155 * Parse the Accept-Language header sent by the client into an array
1157 * @return array [ languageCode => q-value ] sorted by q-value in
1158 * descending order then appearing time in the header in ascending order.
1159 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1160 * This is aligned with rfc2616 section 14.4
1161 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1163 public function getAcceptLang() {
1164 // Modified version of code found at
1165 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1166 $acceptLang = $this->getHeader( 'Accept-Language' );
1167 if ( !$acceptLang ) {
1171 // Return the language codes in lower case
1172 $acceptLang = strtolower( $acceptLang );
1174 // Break up string into pieces (languages and q factors)
1177 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1182 if ( !count( $lang_parse[1] ) ) {
1186 $langcodes = $lang_parse[1];
1187 $qvalues = $lang_parse[4];
1188 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1190 // Set default q factor to 1
1191 foreach ( $indices as $index ) {
1192 if ( $qvalues[$index] === '' ) {
1193 $qvalues[$index] = 1;
1194 } elseif ( $qvalues[$index] == 0 ) {
1195 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1199 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1200 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1202 // Create a list like "en" => 0.8
1203 $langs = array_combine( $langcodes, $qvalues );
1209 * Fetch the raw IP from the request
1213 * @throws MWException
1216 protected function getRawIP() {
1217 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1221 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1222 throw new MWException( __METHOD__
1223 . " : Could not determine the remote IP address due to multiple values." );
1225 $ipchain = $_SERVER['REMOTE_ADDR'];
1228 return IP
::canonicalize( $ipchain );
1232 * Work out the IP address based on various globals
1233 * For trusted proxies, use the XFF client IP (first of the chain)
1237 * @throws MWException
1240 public function getIP() {
1241 global $wgUsePrivateIPs;
1243 # Return cached result
1244 if ( $this->ip
!== null ) {
1248 # collect the originating ips
1249 $ip = $this->getRawIP();
1251 throw new MWException( 'Unable to determine IP.' );
1255 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1256 if ( $forwardedFor !== false ) {
1257 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1258 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1259 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1260 $ipchain = array_reverse( $ipchain );
1261 array_unshift( $ipchain, $ip );
1263 # Step through XFF list and find the last address in the list which is a
1264 # trusted server. Set $ip to the IP address given by that trusted server,
1265 # unless the address is not sensible (e.g. private). However, prefer private
1266 # IP addresses over proxy servers controlled by this site (more sensible).
1267 # Note that some XFF values might be "unknown" with Squid/Varnish.
1268 foreach ( $ipchain as $i => $curIP ) {
1269 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1270 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1271 ||
!$proxyLookup->isTrustedProxy( $curIP )
1273 break; // IP is not valid/trusted or does not point to anything
1276 IP
::isPublic( $ipchain[$i +
1] ) ||
1278 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1280 // Follow the next IP according to the proxy
1281 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1282 if ( !$nextIP && $isConfigured ) {
1283 // We have not yet made it past CDN/proxy servers of this site,
1284 // so either they are misconfigured or there is some IP spoofing.
1285 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1288 // keep traversing the chain
1295 # Allow extensions to improve our guess
1296 Hooks
::run( 'GetIP', [ &$ip ] );
1299 throw new MWException( "Unable to determine IP." );
1302 wfDebug( "IP: $ip\n" );
1312 public function setIP( $ip ) {
1317 * Check if this request uses a "safe" HTTP method
1319 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1320 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1321 * like POST and PUT are typical of non-safe requests which often change content.
1324 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1325 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1328 public function hasSafeMethod() {
1329 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1330 return false; // CLI mode
1333 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1337 * Whether this request should be identified as being "safe"
1339 * This means that the client is not requesting any state changes and that database writes
1340 * are not inherently required. Ideally, no visible updates would happen at all. If they
1341 * must, then they should not be publicly attributed to the end user.
1344 * - Cache populations and refreshes MAY occur.
1345 * - Private user session updates and private server logging MAY occur.
1346 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1347 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1350 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1351 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1354 public function isSafeRequest() {
1355 if ( $this->markedAsSafe
&& $this->wasPosted() ) {
1356 return true; // marked as a "safe" POST
1359 return $this->hasSafeMethod();
1363 * Mark this request as identified as being nullipotent even if it is a POST request
1365 * POST requests are often used due to the need for a client payload, even if the request
1366 * is otherwise equivalent to a "safe method" request.
1368 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1369 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1372 public function markAsSafeRequest() {
1373 $this->markedAsSafe
= true;