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.
43 * The parameters from $_GET, $_POST and the path router
49 * The parameters from $_GET. The parameters from the path router are
50 * added by interpolateTitle() during Setup.php.
53 protected $queryAndPathParams;
56 * The parameters from $_GET only.
58 protected $queryParams;
61 * Lazy-initialized request headers indexed by upper-case header name
64 protected $headers = [];
67 * Flag to make WebRequest::getHeader return an array of values.
70 const GETHEADER_LIST
= 1;
73 * The unique request ID.
76 private static $reqId;
79 * Lazy-init response object
85 * Cached client IP address
91 * The timestamp of the start of the request, with microsecond precision.
94 protected $requestTime;
103 * @var SessionId|null Session ID to use for this
104 * request. We can't save the session directly due to reference cycles not
105 * working too well (slow GC in Zend and never collected in HHVM).
107 protected $sessionId = null;
109 /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
110 protected $markedAsSafe = false;
113 * @codeCoverageIgnore
115 public function __construct() {
116 $this->requestTime
= $_SERVER['REQUEST_TIME_FLOAT'];
118 // POST overrides GET data
119 // We don't use $_REQUEST here to avoid interference from cookies...
120 $this->data
= $_POST +
$_GET;
122 $this->queryAndPathParams
= $this->queryParams
= $_GET;
126 * Extract relevant query arguments from the http request uri's path
127 * to be merged with the normal php provided query arguments.
128 * Tries to use the REQUEST_URI data if available and parses it
129 * according to the wiki's configuration looking for any known pattern.
131 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
132 * provided by the server if any and use that to set a 'title' parameter.
134 * @param string $want If this is not 'all', then the function
135 * will return an empty array if it determines that the URL is
136 * inside a rewrite path.
138 * @return array Any query arguments found in path matches.
140 public static function getPathInfo( $want = 'all' ) {
141 global $wgUsePathInfo;
142 // PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
143 // And also by Apache 2.x, double slashes are converted to single slashes.
144 // So we will use REQUEST_URI if possible.
146 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
147 // Slurp out the path portion to examine...
148 $url = $_SERVER['REQUEST_URI'];
149 if ( !preg_match( '!^https?://!', $url ) ) {
150 $url = 'http://unused' . $url;
152 Wikimedia\
suppressWarnings();
153 $a = parse_url( $url );
154 Wikimedia\restoreWarnings
();
156 $path = $a['path'] ??
'';
159 if ( $path == $wgScript && $want !== 'all' ) {
160 // Script inside a rewrite path?
161 // Abort to keep from breaking...
165 $router = new PathRouter
;
167 // Raw PATH_INFO style
168 $router->add( "$wgScript/$1" );
170 if ( isset( $_SERVER['SCRIPT_NAME'] )
171 && preg_match( '/\.php/', $_SERVER['SCRIPT_NAME'] )
173 # Check for SCRIPT_NAME, we handle index.php explicitly
174 # But we do have some other .php files such as img_auth.php
175 # Don't let root article paths clober the parsing for them
176 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
179 global $wgArticlePath;
180 if ( $wgArticlePath ) {
181 $router->add( $wgArticlePath );
184 global $wgActionPaths;
185 if ( $wgActionPaths ) {
186 $router->add( $wgActionPaths, [ 'action' => '$key' ] );
189 global $wgVariantArticlePath;
190 if ( $wgVariantArticlePath ) {
191 $router->add( $wgVariantArticlePath,
192 [ 'variant' => '$2' ],
193 [ '$2' => MediaWikiServices
::getInstance()->getContentLanguage()->
198 Hooks
::run( 'WebRequestPathInfoRouter', [ $router ] );
200 $matches = $router->parse( $path );
202 } elseif ( $wgUsePathInfo ) {
203 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
205 // https://bugs.php.net/bug.php?id=31892
206 // Also reported when ini_get('cgi.fix_pathinfo')==false
207 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
209 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
210 // Regular old PATH_INFO yay
211 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
219 * Work out an appropriate URL prefix containing scheme and host, based on
220 * information detected from $_SERVER
224 public static function detectServer() {
225 global $wgAssumeProxiesUseDefaultProtocolPorts;
227 $proto = self
::detectProtocol();
228 $stdPort = $proto === 'https' ?
443 : 80;
230 $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
233 foreach ( $varNames as $varName ) {
234 if ( !isset( $_SERVER[$varName] ) ) {
238 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
240 // Invalid, do not use
245 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
246 // T72021: Assume that upstream proxy is running on the default
247 // port based on the protocol. We have no reliable way to determine
248 // the actual port in use upstream.
250 } elseif ( $parts[1] === false ) {
251 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
252 $port = $_SERVER['SERVER_PORT'];
253 } // else leave it as $stdPort
260 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
264 * Detect the protocol from $_SERVER.
265 * This is for use prior to Setup.php, when no WebRequest object is available.
266 * At other times, use the non-static function getProtocol().
270 public static function detectProtocol() {
271 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
272 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
273 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
281 * Get the number of seconds to have elapsed since request start,
282 * in fractional seconds, with microsecond resolution.
287 public function getElapsedTime() {
288 return microtime( true ) - $this->requestTime
;
292 * Get the unique request ID.
293 * This is either the value of the UNIQUE_ID envvar (if present) or a
294 * randomly-generated 24-character string.
299 public static function getRequestId() {
300 // This method is called from various error handlers and should be kept simple.
302 if ( self
::$reqId ) {
306 global $wgAllowExternalReqID;
308 self
::$reqId = $_SERVER['UNIQUE_ID'] ??
wfRandomString( 24 );
309 if ( $wgAllowExternalReqID ) {
310 $id = RequestContext
::getMain()->getRequest()->getHeader( 'X-Request-Id' );
320 * Override the unique request ID. This is for sub-requests, such as jobs,
321 * that wish to use the same id but are not part of the same execution context.
326 public static function overrideRequestId( $id ) {
331 * Get the current URL protocol (http or https)
334 public function getProtocol() {
335 if ( $this->protocol
=== null ) {
336 $this->protocol
= self
::detectProtocol();
338 return $this->protocol
;
342 * Check for title, action, and/or variant data in the URL
343 * and interpolate it into the GET variables.
344 * This should only be run after the content language is available,
345 * as we may need the list of language variants to determine
346 * available variant URLs.
348 public function interpolateTitle() {
349 // T18019: title interpolation on API queries is useless and sometimes harmful
350 if ( defined( 'MW_API' ) ) {
354 $matches = self
::getPathInfo( 'title' );
355 foreach ( $matches as $key => $val ) {
356 $this->data
[$key] = $this->queryAndPathParams
[$key] = $val;
361 * URL rewriting function; tries to extract page title and,
362 * optionally, one other fixed parameter value from a URL path.
364 * @param string $path The URL path given from the client
365 * @param array $bases One or more URLs, optionally with $1 at the end
366 * @param string|bool $key If provided, the matching key in $bases will be
367 * passed on as the value of this URL parameter
368 * @return array Array of URL variables to interpolate; empty if no match
370 static function extractTitle( $path, $bases, $key = false ) {
371 foreach ( (array)$bases as $keyValue => $base ) {
372 // Find the part after $wgArticlePath
373 $base = str_replace( '$1', '', $base );
374 $baseLen = strlen( $base );
375 if ( substr( $path, 0, $baseLen ) == $base ) {
376 $raw = substr( $path, $baseLen );
378 $matches = [ 'title' => rawurldecode( $raw ) ];
380 $matches[$key] = $keyValue;
390 * Recursively normalizes UTF-8 strings in the given array.
392 * @param string|array $data
393 * @return array|string Cleaned-up version of the given
396 public function normalizeUnicode( $data ) {
397 if ( is_array( $data ) ) {
398 foreach ( $data as $key => $val ) {
399 $data[$key] = $this->normalizeUnicode( $val );
402 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
403 $data = $contLang ?
$contLang->normalize( $data ) :
404 UtfNormal\Validator
::cleanUp( $data );
410 * Fetch a value from the given array or return $default if it's not set.
413 * @param string $name
414 * @param mixed $default
417 private function getGPCVal( $arr, $name, $default ) {
418 # PHP is so nice to not touch input data, except sometimes:
419 # https://www.php.net/variables.external#language.variables.external.dot-in-names
420 # Work around PHP *feature* to avoid *bugs* elsewhere.
421 $name = strtr( $name, '.', '_' );
423 if ( !isset( $arr[$name] ) ) {
428 # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
429 $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
430 if ( !$isAsciiStr ) {
431 if ( isset( $_GET[$name] ) && is_string( $data ) ) {
432 # Check for alternate/legacy character encoding.
433 $data = MediaWikiServices
::getInstance()
434 ->getContentLanguage()
435 ->checkTitleEncoding( $data );
437 $data = $this->normalizeUnicode( $data );
444 * Fetch a scalar from the input without normalization, or return $default
447 * Unlike self::getVal(), this does not perform any normalization on the
451 * @param string $name
452 * @param string|null $default
453 * @return string|null
455 public function getRawVal( $name, $default = null ) {
456 $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
457 if ( isset( $this->data
[$name] ) && !is_array( $this->data
[$name] ) ) {
458 $val = $this->data
[$name];
462 if ( is_null( $val ) ) {
470 * Fetch a scalar from the input or return $default if it's not set.
471 * Returns a string. Arrays are discarded. Useful for
472 * non-freeform text inputs (e.g. predefined internal text keys
473 * selected by a drop-down menu). For freeform input, see getText().
475 * @param string $name
476 * @param string|null $default Optional default (or null)
477 * @return string|null
479 public function getVal( $name, $default = null ) {
480 $val = $this->getGPCVal( $this->data
, $name, $default );
481 if ( is_array( $val ) ) {
484 if ( is_null( $val ) ) {
492 * Set an arbitrary value into our get/post data.
494 * @param string $key Key name to use
495 * @param mixed $value Value to set
496 * @return mixed Old value if one was present, null otherwise
498 public function setVal( $key, $value ) {
499 $ret = $this->data
[$key] ??
null;
500 $this->data
[$key] = $value;
505 * Unset an arbitrary value from our get/post data.
507 * @param string $key Key name to use
508 * @return mixed Old value if one was present, null otherwise
510 public function unsetVal( $key ) {
511 if ( !isset( $this->data
[$key] ) ) {
514 $ret = $this->data
[$key];
515 unset( $this->data
[$key] );
521 * Fetch an array from the input or return $default if it's not set.
522 * If source was scalar, will return an array with a single element.
523 * If no source and no default, returns null.
525 * @param string $name
526 * @param array|null $default Optional default (or null)
529 public function getArray( $name, $default = null ) {
530 $val = $this->getGPCVal( $this->data
, $name, $default );
531 if ( is_null( $val ) ) {
539 * Fetch an array of integers, or return $default if it's not set.
540 * If source was scalar, will return an array with a single element.
541 * If no source and no default, returns null.
542 * If an array is returned, contents are guaranteed to be integers.
544 * @param string $name
545 * @param array|null $default Option default (or null)
546 * @return array Array of ints
548 public function getIntArray( $name, $default = null ) {
549 $val = $this->getArray( $name, $default );
550 if ( is_array( $val ) ) {
551 $val = array_map( 'intval', $val );
557 * Fetch an integer value from the input or return $default if not set.
558 * Guaranteed to return an integer; non-numeric input will typically
561 * @param string $name
562 * @param int $default
565 public function getInt( $name, $default = 0 ) {
566 return intval( $this->getRawVal( $name, $default ) );
570 * Fetch an integer value from the input or return null if empty.
571 * Guaranteed to return an integer or null; non-numeric input will
572 * typically return null.
574 * @param string $name
577 public function getIntOrNull( $name ) {
578 $val = $this->getRawVal( $name );
579 return is_numeric( $val )
585 * Fetch a floating point value from the input or return $default if not set.
586 * Guaranteed to return a float; non-numeric input will typically
590 * @param string $name
591 * @param float $default
594 public function getFloat( $name, $default = 0.0 ) {
595 return floatval( $this->getRawVal( $name, $default ) );
599 * Fetch a boolean value from the input or return $default if not set.
600 * Guaranteed to return true or false, with normal PHP semantics for
601 * boolean interpretation of strings.
603 * @param string $name
604 * @param bool $default
607 public function getBool( $name, $default = false ) {
608 return (bool)$this->getRawVal( $name, $default );
612 * Fetch a boolean value from the input or return $default if not set.
613 * Unlike getBool, the string "false" will result in boolean false, which is
614 * useful when interpreting information sent from JavaScript.
616 * @param string $name
617 * @param bool $default
620 public function getFuzzyBool( $name, $default = false ) {
621 return $this->getBool( $name, $default )
622 && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
626 * Return true if the named value is set in the input, whatever that
627 * value is (even "0"). Return false if the named value is not set.
628 * Example use is checking for the presence of check boxes in forms.
630 * @param string $name
633 public function getCheck( $name ) {
634 # Checkboxes and buttons are only present when clicked
635 # Presence connotes truth, absence false
636 return $this->getRawVal( $name, null ) !== null;
640 * Fetch a text string from the given array or return $default if it's not
641 * set. Carriage returns are stripped from the text. This should generally
642 * be used for form "<textarea>" and "<input>" fields, and for
643 * user-supplied freeform text input.
645 * @param string $name
646 * @param string $default Optional
649 public function getText( $name, $default = '' ) {
650 $val = $this->getVal( $name, $default );
651 return str_replace( "\r\n", "\n", $val );
655 * Extracts the given named values into an array.
656 * If no arguments are given, returns all input values.
657 * No transformation is performed on the values.
661 public function getValues() {
662 $names = func_get_args();
663 if ( count( $names ) == 0 ) {
664 $names = array_keys( $this->data
);
668 foreach ( $names as $name ) {
669 $value = $this->getGPCVal( $this->data
, $name, null );
670 if ( !is_null( $value ) ) {
671 $retVal[$name] = $value;
678 * Returns the names of all input values excluding those in $exclude.
680 * @param array $exclude
683 public function getValueNames( $exclude = [] ) {
684 return array_diff( array_keys( $this->getValues() ), $exclude );
688 * Get the values passed in the query string and the path router parameters.
689 * No transformation is performed on the values.
691 * @codeCoverageIgnore
694 public function getQueryValues() {
695 return $this->queryAndPathParams
;
699 * Get the values passed in the query string only, not including the path
700 * router parameters. This is less suitable for self-links to index.php but
701 * useful for other entry points. No transformation is performed on the
707 public function getQueryValuesOnly() {
708 return $this->queryParams
;
712 * Get the values passed via POST.
713 * No transformation is performed on the values.
716 * @codeCoverageIgnore
719 public function getPostValues() {
724 * Return the contents of the Query with no decoding. Use when you need to
725 * know exactly what was sent, e.g. for an OAuth signature over the elements.
727 * @codeCoverageIgnore
730 public function getRawQueryString() {
731 return $_SERVER['QUERY_STRING'];
735 * Return the contents of the POST with no decoding. Use when you need to
736 * know exactly what was sent, e.g. for an OAuth signature over the elements.
740 public function getRawPostString() {
741 if ( !$this->wasPosted() ) {
744 return $this->getRawInput();
748 * Return the raw request body, with no processing. Cached since some methods
749 * disallow reading the stream more than once. As stated in the php docs, this
750 * does not work with enctype="multipart/form-data".
754 public function getRawInput() {
755 static $input = null;
756 if ( $input === null ) {
757 $input = file_get_contents( 'php://input' );
763 * Get the HTTP method used for this request.
767 public function getMethod() {
768 return $_SERVER['REQUEST_METHOD'] ??
'GET';
772 * Returns true if the present request was reached by a POST operation,
773 * false otherwise (GET, HEAD, or command-line).
775 * Note that values retrieved by the object may come from the
776 * GET URL etc even on a POST request.
780 public function wasPosted() {
781 return $this->getMethod() == 'POST';
785 * Return the session for this request
787 * This might unpersist an existing session if it was invalid.
790 * @note For performance, keep the session locally if you will be making
791 * much use of it instead of calling this method repeatedly.
794 public function getSession() {
795 if ( $this->sessionId
!== null ) {
796 $session = SessionManager
::singleton()->getSessionById( (string)$this->sessionId
, true, $this );
802 $session = SessionManager
::singleton()->getSessionForRequest( $this );
803 $this->sessionId
= $session->getSessionId();
808 * Set the session for this request
810 * @private For use by MediaWiki\Session classes only
811 * @param SessionId $sessionId
813 public function setSessionId( SessionId
$sessionId ) {
814 $this->sessionId
= $sessionId;
818 * Get the session id for this request, if any
820 * @private For use by MediaWiki\Session classes only
821 * @return SessionId|null
823 public function getSessionId() {
824 return $this->sessionId
;
828 * Get a cookie from the $_COOKIE jar
830 * @param string $key The name of the cookie
831 * @param string|null $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
832 * @param mixed|null $default What to return if the value isn't found
833 * @return mixed Cookie value or $default if the cookie not set
835 public function getCookie( $key, $prefix = null, $default = null ) {
836 if ( $prefix === null ) {
837 global $wgCookiePrefix;
838 $prefix = $wgCookiePrefix;
840 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
844 * Return the path and query string portion of the main request URI.
845 * This will be suitable for use as a relative link in HTML output.
847 * @throws MWException
850 public static function getGlobalRequestURL() {
851 // This method is called on fatal errors; it should not depend on anything complex.
853 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
854 $base = $_SERVER['REQUEST_URI'];
855 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
856 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
858 // Probably IIS; doesn't set REQUEST_URI
859 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
860 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
861 $base = $_SERVER['SCRIPT_NAME'];
862 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
863 $base .= '?' . $_SERVER['QUERY_STRING'];
866 // This shouldn't happen!
867 throw new MWException( "Web server doesn't provide either " .
868 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
869 "of your web server configuration to https://phabricator.wikimedia.org/" );
871 // User-agents should not send a fragment with the URI, but
872 // if they do, and the web server passes it on to us, we
873 // need to strip it or we get false-positive redirect loops
874 // or weird output URLs
875 $hash = strpos( $base, '#' );
876 if ( $hash !== false ) {
877 $base = substr( $base, 0, $hash );
880 if ( $base[0] == '/' ) {
881 // More than one slash will look like it is protocol relative
882 return preg_replace( '!^/+!', '/', $base );
884 // We may get paths with a host prepended; strip it.
885 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
890 * Return the path and query string portion of the request URI.
891 * This will be suitable for use as a relative link in HTML output.
893 * @throws MWException
896 public function getRequestURL() {
897 return self
::getGlobalRequestURL();
901 * Return the request URI with the canonical service and hostname, path,
902 * and query string. This will be suitable for use as an absolute link
903 * in HTML or other output.
905 * If $wgServer is protocol-relative, this will return a fully
906 * qualified URL with the protocol of this request object.
910 public function getFullRequestURL() {
911 // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
912 // do not rely on state from the global $wgRequest object (which it would,
913 // via wfGetServerUrl/wfExpandUrl/$wgRequest->protocol).
914 if ( $this->getProtocol() === 'http' ) {
915 return wfGetServerUrl( PROTO_HTTP
) . $this->getRequestURL();
917 return wfGetServerUrl( PROTO_HTTPS
) . $this->getRequestURL();
923 * @param string $value
926 public function appendQueryValue( $key, $value ) {
927 return $this->appendQueryArray( [ $key => $value ] );
931 * Appends or replaces value of query variables.
933 * @param array $array Array of values to replace/add to query
936 public function appendQueryArray( $array ) {
937 $newquery = $this->getQueryValues();
938 unset( $newquery['title'] );
939 $newquery = array_merge( $newquery, $array );
941 return wfArrayToCgi( $newquery );
945 * Check for limit and offset parameters on the input, and return sensible
946 * defaults if not given. The limit must be positive and is capped at 5000.
947 * Offset must be positive but is not capped.
949 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
950 * @param string $optionname To specify an option other than rclimit to pull from.
951 * @return int[] First element is limit, second is offset
953 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
956 $limit = $this->getInt( 'limit', 0 );
960 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
961 $limit = $wgUser->getIntOption( $optionname );
966 if ( $limit > 5000 ) {
967 $limit = 5000; # We have *some* limits...
970 $offset = $this->getInt( 'offset', 0 );
975 return [ $limit, $offset ];
979 * Return the path to the temporary file where PHP has stored the upload.
982 * @return string|null String or null if no such file.
984 public function getFileTempname( $key ) {
985 $file = new WebRequestUpload( $this, $key );
986 return $file->getTempName();
990 * Return the upload error or 0
995 public function getUploadError( $key ) {
996 $file = new WebRequestUpload( $this, $key );
997 return $file->getError();
1001 * Return the original filename of the uploaded file, as reported by
1002 * the submitting user agent. HTML-style character entities are
1003 * interpreted and normalized to Unicode normalization form C, in part
1004 * to deal with weird input from Safari with non-ASCII filenames.
1006 * Other than this the name is not verified for being a safe filename.
1008 * @param string $key
1009 * @return string|null String or null if no such file.
1011 public function getFileName( $key ) {
1012 $file = new WebRequestUpload( $this, $key );
1013 return $file->getName();
1017 * Return a WebRequestUpload object corresponding to the key
1019 * @param string $key
1020 * @return WebRequestUpload
1022 public function getUpload( $key ) {
1023 return new WebRequestUpload( $this, $key );
1027 * Return a handle to WebResponse style object, for setting cookies,
1028 * headers and other stuff, for Request being worked on.
1030 * @return WebResponse
1032 public function response() {
1033 /* Lazy initialization of response object for this request */
1034 if ( !is_object( $this->response
) ) {
1035 $class = ( $this instanceof FauxRequest
) ? FauxResponse
::class : WebResponse
::class;
1036 $this->response
= new $class();
1038 return $this->response
;
1042 * Initialise the header list
1044 protected function initHeaders() {
1045 if ( count( $this->headers
) ) {
1049 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
1050 if ( $apacheHeaders ) {
1051 foreach ( $apacheHeaders as $tempName => $tempValue ) {
1052 $this->headers
[strtoupper( $tempName )] = $tempValue;
1055 foreach ( $_SERVER as $name => $value ) {
1056 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
1057 $name = str_replace( '_', '-', substr( $name, 5 ) );
1058 $this->headers
[$name] = $value;
1059 } elseif ( $name === 'CONTENT_LENGTH' ) {
1060 $this->headers
['CONTENT-LENGTH'] = $value;
1067 * Get an array containing all request headers
1069 * @return array Mapping header name to its value
1071 public function getAllHeaders() {
1072 $this->initHeaders();
1073 return $this->headers
;
1077 * Get a request header, or false if it isn't set.
1079 * @param string $name Case-insensitive header name
1080 * @param int $flags Bitwise combination of:
1081 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1082 * of values, as described in RFC 2616 § 4.2.
1084 * @return string|array|bool False if header is unset; otherwise the
1085 * header value(s) as either a string (the default) or an array, if
1086 * WebRequest::GETHEADER_LIST flag was set.
1088 public function getHeader( $name, $flags = 0 ) {
1089 $this->initHeaders();
1090 $name = strtoupper( $name );
1091 if ( !isset( $this->headers
[$name] ) ) {
1094 $value = $this->headers
[$name];
1095 if ( $flags & self
::GETHEADER_LIST
) {
1096 $value = array_map( 'trim', explode( ',', $value ) );
1102 * Get data from the session
1104 * @note Prefer $this->getSession() instead if making multiple calls.
1105 * @param string $key Name of key in the session
1108 public function getSessionData( $key ) {
1109 return $this->getSession()->get( $key );
1115 * @note Prefer $this->getSession() instead if making multiple calls.
1116 * @param string $key Name of key in the session
1117 * @param mixed $data
1119 public function setSessionData( $key, $data ) {
1120 $this->getSession()->set( $key, $data );
1124 * Check if Internet Explorer will detect an incorrect cache extension in
1125 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1126 * message or redirect to a safer URL. Returns true if the URL is OK, and
1127 * false if an error message has been shown and the request should be aborted.
1129 * @param array $extWhitelist
1133 public function checkUrlExtension( $extWhitelist = [] ) {
1134 $extWhitelist[] = 'php';
1135 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1136 if ( !$this->wasPosted() ) {
1137 $newUrl = IEUrlExtension
::fixUrlForIE6(
1138 $this->getFullRequestURL(), $extWhitelist );
1139 if ( $newUrl !== false ) {
1140 $this->doSecurityRedirect( $newUrl );
1144 throw new HttpError( 403,
1145 'Invalid file extension found in the path info or query string.' );
1151 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1152 * IE 6. Returns true if it was successful, false otherwise.
1154 * @param string $url
1157 protected function doSecurityRedirect( $url ) {
1158 header( 'Location: ' . $url );
1159 header( 'Content-Type: text/html' );
1160 $encUrl = htmlspecialchars( $url );
1165 <title>Security redirect</title>
1168 <h1>Security redirect</h1>
1170 We can't serve non-HTML content from the URL you have requested
, because
1171 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
1173 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
1174 URL you have requested
, except that
"&*" is appended
. This prevents Internet
1175 Explorer from seeing a bogus file extension
.
1185 * Parse the Accept-Language header sent by the client into an array
1187 * @return array [ languageCode => q-value ] sorted by q-value in
1188 * descending order then appearing time in the header in ascending order.
1189 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1190 * This is aligned with rfc2616 section 14.4
1191 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1193 public function getAcceptLang() {
1194 // Modified version of code found at
1195 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1196 $acceptLang = $this->getHeader( 'Accept-Language' );
1197 if ( !$acceptLang ) {
1201 // Return the language codes in lower case
1202 $acceptLang = strtolower( $acceptLang );
1204 // Break up string into pieces (languages and q factors)
1207 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1212 if ( !count( $lang_parse[1] ) ) {
1216 $langcodes = $lang_parse[1];
1217 $qvalues = $lang_parse[4];
1218 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1220 // Set default q factor to 1
1221 foreach ( $indices as $index ) {
1222 if ( $qvalues[$index] === '' ) {
1223 $qvalues[$index] = 1;
1224 } elseif ( $qvalues[$index] == 0 ) {
1225 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1229 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1230 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1232 // Create a list like "en" => 0.8
1233 $langs = array_combine( $langcodes, $qvalues );
1239 * Fetch the raw IP from the request
1243 * @throws MWException
1246 protected function getRawIP() {
1247 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1251 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1252 throw new MWException( __METHOD__
1253 . " : Could not determine the remote IP address due to multiple values." );
1255 $ipchain = $_SERVER['REMOTE_ADDR'];
1258 return IP
::canonicalize( $ipchain );
1262 * Work out the IP address based on various globals
1263 * For trusted proxies, use the XFF client IP (first of the chain)
1267 * @throws MWException
1270 public function getIP() {
1271 global $wgUsePrivateIPs;
1273 # Return cached result
1274 if ( $this->ip
!== null ) {
1278 # collect the originating ips
1279 $ip = $this->getRawIP();
1281 throw new MWException( 'Unable to determine IP.' );
1285 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1286 if ( $forwardedFor !== false ) {
1287 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1288 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1289 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1290 $ipchain = array_reverse( $ipchain );
1291 array_unshift( $ipchain, $ip );
1293 # Step through XFF list and find the last address in the list which is a
1294 # trusted server. Set $ip to the IP address given by that trusted server,
1295 # unless the address is not sensible (e.g. private). However, prefer private
1296 # IP addresses over proxy servers controlled by this site (more sensible).
1297 # Note that some XFF values might be "unknown" with Squid/Varnish.
1298 foreach ( $ipchain as $i => $curIP ) {
1299 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1300 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1301 ||
!$proxyLookup->isTrustedProxy( $curIP )
1303 break; // IP is not valid/trusted or does not point to anything
1306 IP
::isPublic( $ipchain[$i +
1] ) ||
1308 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1310 // Follow the next IP according to the proxy
1311 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1312 if ( !$nextIP && $isConfigured ) {
1313 // We have not yet made it past CDN/proxy servers of this site,
1314 // so either they are misconfigured or there is some IP spoofing.
1315 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1318 // keep traversing the chain
1325 # Allow extensions to improve our guess
1326 Hooks
::run( 'GetIP', [ &$ip ] );
1329 throw new MWException( "Unable to determine IP." );
1332 wfDebug( "IP: $ip\n" );
1342 public function setIP( $ip ) {
1347 * Check if this request uses a "safe" HTTP method
1349 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1350 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1351 * like POST and PUT are typical of non-safe requests which often change content.
1354 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1355 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1358 public function hasSafeMethod() {
1359 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1360 return false; // CLI mode
1363 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1367 * Whether this request should be identified as being "safe"
1369 * This means that the client is not requesting any state changes and that database writes
1370 * are not inherently required. Ideally, no visible updates would happen at all. If they
1371 * must, then they should not be publicly attributed to the end user.
1374 * - Cache populations and refreshes MAY occur.
1375 * - Private user session updates and private server logging MAY occur.
1376 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1377 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1380 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1381 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1384 public function isSafeRequest() {
1385 if ( $this->markedAsSafe
&& $this->wasPosted() ) {
1386 return true; // marked as a "safe" POST
1389 return $this->hasSafeMethod();
1393 * Mark this request as identified as being nullipotent even if it is a POST request
1395 * POST requests are often used due to the need for a client payload, even if the request
1396 * is otherwise equivalent to a "safe method" request.
1398 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1399 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1402 public function markAsSafeRequest() {
1403 $this->markedAsSafe
= true;