122 $this->requestTime = $_SERVER[
'REQUEST_TIME_FLOAT'];
126 $this->data = $_POST + $_GET;
128 $this->queryAndPathParams = $this->queryParams = $_GET;
155 if ( isset( $_SERVER[
'REQUEST_URI'] ) ) {
157 $url = $_SERVER[
'REQUEST_URI'];
158 if ( !preg_match(
'!^https?://!', $url ) ) {
159 $url =
'http://unused' . $url;
161 $a = parse_url( $url );
165 $path = $a[
'path'] ??
'';
177 $router->
add(
"$wgScript/$1" );
187 if ( $articlePaths ) {
188 $router->add( $articlePaths, [
'action' =>
'$key' ] );
193 $services = MediaWikiServices::getInstance();
196 [
'variant' =>
'$2' ],
197 [
'$2' => $services->getLanguageConverterFactory()
198 ->getLanguageConverter( $services->getContentLanguage() )
203 Hooks::runner()->onWebRequestPathInfoRouter( $router );
210 if ( !empty( $_SERVER[
'ORIG_PATH_INFO'] ) ) {
214 $matches[
'title'] = substr( $_SERVER[
'ORIG_PATH_INFO'], 1 );
215 } elseif ( !empty( $_SERVER[
'PATH_INFO'] ) ) {
217 $matches[
'title'] = substr( $_SERVER[
'PATH_INFO'], 1 );
237 $basePath = rtrim( $basePath,
'/' ) .
'/';
238 $requestUrl = self::getGlobalRequestURL();
239 $qpos = strpos( $requestUrl,
'?' );
240 if ( $qpos !==
false ) {
241 $requestPath = substr( $requestUrl, 0, $qpos );
243 $requestPath = $requestUrl;
245 if ( substr( $requestPath, 0, strlen( $basePath ) ) !== $basePath ) {
248 return rawurldecode( substr( $requestPath, strlen( $basePath ) ) );
260 $proto = self::detectProtocol();
261 $stdPort = $proto ===
'https' ? 443 : 80;
263 $varNames = [
'HTTP_HOST',
'SERVER_NAME',
'HOSTNAME',
'SERVER_ADDR' ];
266 foreach ( $varNames as $varName ) {
267 if ( !isset( $_SERVER[$varName] ) ) {
271 $parts = IPUtils::splitHostAndPort( $_SERVER[$varName] );
283 } elseif ( $parts[1] ===
false ) {
284 if ( isset( $_SERVER[
'SERVER_PORT'] ) ) {
285 $port = $_SERVER[
'SERVER_PORT'];
293 return $proto .
'://' . IPUtils::combineHostAndPort( $host, $port, $stdPort );
304 if ( ( !empty( $_SERVER[
'HTTPS'] ) && $_SERVER[
'HTTPS'] !==
'off' ) ||
305 ( isset( $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ) &&
306 $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ===
'https' ) ) {
321 return microtime(
true ) - $this->requestTime;
335 if ( !self::$reqId ) {
338 $id = $_SERVER[
'HTTP_X_REQUEST_ID'] ?? $_SERVER[
'UNIQUE_ID'] ??
wfRandomString( 24 );
364 if ( $this->protocol ===
null ) {
365 $this->protocol = self::detectProtocol();
367 return $this->protocol;
378 $matches = self::getPathInfo(
'title' );
379 foreach (
$matches as $key => $val ) {
380 $this->data[$key] = $this->queryAndPathParams[$key] = $val;
395 foreach ( (array)$bases as $keyValue =>
$base ) {
398 $baseLen = strlen(
$base );
399 if ( substr(
$path, 0, $baseLen ) ==
$base ) {
400 $raw = substr(
$path, $baseLen );
402 $matches = [
'title' => rawurldecode( $raw ) ];
421 if ( is_array(
$data ) ) {
422 foreach (
$data as $key => $val ) {
426 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
441 # PHP is so nice to not touch input data, except sometimes:
443 # Work around PHP *feature* to avoid *bugs* elsewhere.
444 $name = strtr( $name,
'.',
'_' );
446 if ( !isset( $arr[$name] ) ) {
451 # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
452 $isAsciiStr = ( is_string(
$data ) && preg_match(
'/[^\x20-\x7E]/',
$data ) === 0 );
453 if ( !$isAsciiStr ) {
454 if ( isset( $_GET[$name] ) && is_string(
$data ) ) {
455 # Check for alternate/legacy character encoding.
456 $data = MediaWikiServices::getInstance()
457 ->getContentLanguage()
458 ->checkTitleEncoding(
$data );
479 $name = strtr( $name,
'.',
'_' );
480 if ( isset( $this->data[$name] ) && !is_array( $this->data[$name] ) ) {
481 $val = $this->data[$name];
486 return $val ===
null ? null : (string)$val;
505 public function getVal( $name, $default =
null ) {
506 $val = $this->
getGPCVal( $this->data, $name, $default );
507 if ( is_array( $val ) ) {
511 return $val ===
null ? null : (string)$val;
530 public function getText( $name, $default =
'' ) {
531 $val = $this->
getVal( $name, $default );
532 return str_replace(
"\r\n",
"\n", $val );
543 $ret = $this->data[$key] ??
null;
544 $this->data[$key] = $value;
555 if ( !isset( $this->data[$key] ) ) {
558 $ret = $this->data[$key];
559 unset( $this->data[$key] );
573 public function getArray( $name, $default =
null ) {
574 $val = $this->
getGPCVal( $this->data, $name, $default );
575 if ( $val ===
null ) {
593 $val = $this->
getArray( $name, $default );
594 if ( is_array( $val ) ) {
595 $val = array_map(
'intval', $val );
609 public function getInt( $name, $default = 0 ) {
610 return intval( $this->
getRawVal( $name, $default ) );
623 return is_numeric( $val )
638 public function getFloat( $name, $default = 0.0 ) {
639 return floatval( $this->
getRawVal( $name, $default ) );
651 public function getBool( $name, $default =
false ) {
652 return (
bool)$this->
getRawVal( $name, $default );
665 return $this->
getBool( $name, $default )
666 && strcasecmp( $this->
getRawVal( $name ),
'false' ) !== 0;
678 # Checkboxes and buttons are only present when clicked
679 # Presence connotes truth, absence false
680 return $this->
getRawVal( $name,
null ) !==
null;
691 if ( $names === [] ) {
692 $names = array_keys( $this->data );
696 foreach ( $names as $name ) {
697 $value = $this->
getGPCVal( $this->data, $name,
null );
698 if ( $value !==
null ) {
699 $retVal[$name] = $value;
712 return array_diff( array_keys( $this->
getValues() ), $exclude );
723 return $this->queryAndPathParams;
736 return $this->queryParams;
759 return $_SERVER[
'QUERY_STRING'];
783 static $input =
null;
784 if ( $input ===
null ) {
785 $input = file_get_contents(
'php://input' );
796 return $_SERVER[
'REQUEST_METHOD'] ??
'GET';
823 if ( $this->sessionId !==
null ) {
824 $session = SessionManager::singleton()->getSessionById( (
string)$this->sessionId,
true, $this );
830 $session = SessionManager::singleton()->getSessionForRequest( $this );
831 $this->sessionId = $session->getSessionId();
842 $this->sessionId = $sessionId;
852 return $this->sessionId;
863 public function getCookie( $key, $prefix =
null, $default =
null ) {
864 if ( $prefix ===
null ) {
868 $name = $prefix . $key;
870 $name = strtr( $name,
'.',
'_' );
871 if ( isset( $_COOKIE[$name] ) ) {
872 return $_COOKIE[$name];
888 $name = $prefix . $key;
890 $name = strtr( $name,
'.',
'_' );
891 if ( isset( $_COOKIE[$name] ) ) {
892 return $_COOKIE[$name];
895 $legacyName = $prefix .
"ss0-" . $key;
896 $legacyName = strtr( $legacyName,
'.',
'_' );
897 if ( isset( $_COOKIE[$legacyName] ) ) {
898 return $_COOKIE[$legacyName];
914 if ( isset( $_SERVER[
'REQUEST_URI'] ) && strlen( $_SERVER[
'REQUEST_URI'] ) ) {
915 $base = $_SERVER[
'REQUEST_URI'];
916 } elseif ( isset( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
917 && strlen( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
920 $base = $_SERVER[
'HTTP_X_ORIGINAL_URL'];
921 } elseif ( isset( $_SERVER[
'SCRIPT_NAME'] ) ) {
922 $base = $_SERVER[
'SCRIPT_NAME'];
923 if ( isset( $_SERVER[
'QUERY_STRING'] ) && $_SERVER[
'QUERY_STRING'] !=
'' ) {
924 $base .=
'?' . $_SERVER[
'QUERY_STRING'];
928 throw new MWException(
"Web server doesn't provide either " .
929 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
930 "of your web server configuration to https://phabricator.wikimedia.org/" );
936 $hash = strpos(
$base,
'#' );
937 if ( $hash !==
false ) {
941 if (
$base[0] ==
'/' ) {
943 return preg_replace(
'!^/+!',
'/',
$base );
946 return preg_replace(
'!^[^:]+://[^/]+/+!',
'/',
$base );
958 return self::getGlobalRequestURL();
999 unset( $newquery[
'title'] );
1000 $newquery = array_merge( $newquery, $array );
1016 $limit = $this->
getInt(
'limit', 0 );
1020 if ( ( $limit == 0 ) && ( $optionname !=
'' ) ) {
1021 $limit = MediaWikiServices::getInstance()
1022 ->getUserOptionsLookup()
1023 ->getIntOption( $user, $optionname );
1025 if ( $limit <= 0 ) {
1028 if ( $limit > 5000 ) {
1029 $limit = 5000; # We have *some* limits...
1032 $offset = $this->
getInt(
'offset', 0 );
1033 if ( $offset < 0 ) {
1037 return [ $limit, $offset ];
1047 return $this->
getUpload( $key )->getTempName();
1057 return $this->
getUpload( $key )->getError();
1072 return $this->
getUpload( $key )->getName();
1093 if ( !is_object( $this->
response ) ) {
1094 $class = ( $this instanceof
FauxRequest ) ? FauxResponse::class : WebResponse::class;
1097 return $this->response;
1104 if ( count( $this->headers ) ) {
1108 $this->headers = array_change_key_case( getallheaders(), CASE_UPPER );
1118 return $this->headers;
1135 $name = strtoupper( $name );
1136 if ( !isset( $this->headers[$name] ) ) {
1139 $value = $this->headers[$name];
1140 if ( $flags & self::GETHEADER_LIST ) {
1141 $value = array_map(
'trim', explode(
',', $value ) );
1196 $acceptLang = $this->
getHeader(
'Accept-Language' );
1197 if ( !$acceptLang ) {
1202 $acceptLang = strtolower( $acceptLang );
1205 if ( !preg_match_all(
1207 # a language code or a star is required
1208 ([a-z]{1,8}(?:-[a-z]{1,8})*|\*)
1209 # from here everything is optional
1212 # this accepts only numbers in the range ;q=0.000 to ;q=1.000
1214 (1(?:\.0{0,3})?|0(?:\.\d{0,3})?)?
1227 $languageCode = $match[1];
1229 $qValue = (float)( $match[2] ?? 1.0 );
1231 $langs[$languageCode] = $qValue;
1236 arsort( $langs, SORT_NUMERIC );
1249 if ( !isset( $_SERVER[
'REMOTE_ADDR'] ) ) {
1253 if ( is_array( $_SERVER[
'REMOTE_ADDR'] ) || strpos( $_SERVER[
'REMOTE_ADDR'],
',' ) !==
false ) {
1255 .
" : Could not determine the remote IP address due to multiple values." );
1257 $ipchain = $_SERVER[
'REMOTE_ADDR'];
1260 return IPUtils::canonicalize( $ipchain );
1275 # Return cached result
1276 if ( $this->ip !==
null ) {
1280 # collect the originating ips
1283 throw new MWException(
'Unable to determine IP.' );
1287 $forwardedFor = $this->
getHeader(
'X-Forwarded-For' );
1288 if ( $forwardedFor !==
false ) {
1289 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1290 $isConfigured = $proxyLookup->isConfiguredProxy(
$ip );
1291 $ipchain = array_map(
'trim', explode(
',', $forwardedFor ) );
1292 $ipchain = array_reverse( $ipchain );
1293 array_unshift( $ipchain,
$ip );
1295 # Step through XFF list and find the last address in the list which is a
1296 # trusted server. Set $ip to the IP address given by that trusted server,
1297 # unless the address is not sensible (e.g. private). However, prefer private
1298 # IP addresses over proxy servers controlled by this site (more sensible).
1299 # Note that some XFF values might be "unknown" with Squid/Varnish.
1300 foreach ( $ipchain as $i => $curIP ) {
1301 $curIP = IPUtils::sanitizeIP(
1302 IPUtils::canonicalize(
1303 self::canonicalizeIPv6LoopbackAddress( $curIP )
1306 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] ===
'unknown'
1307 || !$proxyLookup->isTrustedProxy( $curIP )
1312 IPUtils::isPublic( $ipchain[$i + 1] ) ||
1314 $proxyLookup->isConfiguredProxy( $curIP )
1316 $nextIP = $ipchain[$i + 1];
1319 $nextIP = IPUtils::canonicalize(
1320 self::canonicalizeIPv6LoopbackAddress( $nextIP )
1322 if ( !$nextIP && $isConfigured ) {
1325 throw new MWException(
"Invalid IP given in XFF '$forwardedFor'." );
1336 # Allow extensions to improve our guess
1337 Hooks::runner()->onGetIP(
$ip );
1340 throw new MWException(
"Unable to determine IP." );
1358 if ( preg_match(
'/^0*' . IPUtils::RE_IPV6_GAP .
'1$/',
$ip, $m ) ) {
1386 if ( !isset( $_SERVER[
'REQUEST_METHOD'] ) ) {
1390 return in_array( $_SERVER[
'REQUEST_METHOD'], [
'GET',
'HEAD',
'OPTIONS',
'TRACE' ] );
1412 if ( $this->markedAsSafe && $this->
wasPosted() ) {
1430 $this->markedAsSafe =
true;
$wgUsePathInfo
Whether to support URLs like index.php/Page_title These often break when PHP is set up in CGI mode.
$wgScript
The URL path to index.php.
$wgActionPaths
To set 'pretty' URL paths for actions other than plain page views, add to this array.
bool $wgUseSameSiteLegacyCookies
If true, when a cross-site cookie with SameSite=None is sent, a legacy cookie with an "ss0" prefix wi...
$wgArticlePath
The URL path for primary article page views.
$wgAllowExternalReqID
Whether to respect/honour the request ID provided by the incoming request via the X-Request-Id header...
bool $wgAssumeProxiesUseDefaultProtocolPorts
When the wiki is running behind a proxy and this is set to true, assumes that the proxy exposes the w...
$wgVariantArticlePath
Like $wgArticlePath, but on multi-variant wikis, this provides a path format that describes which par...
$wgCookiePrefix
Cookies generated by MediaWiki have names starting with this prefix.
$wgUsePrivateIPs
Should forwarded Private IPs be accepted?
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
WebRequest clone which takes values from a provided array.
add( $path, $params=[], $options=[])
Add a new path pattern to the path router.
Object to access the $_FILES array.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
markAsSafeRequest()
Mark this request as identified as being nullipotent even if it is a POST request.
getIntOrNull( $name)
Fetch an integer value from the input or return null if empty.
string[] $queryParams
The parameters from $_GET only.
getLimitOffsetForUser(UserIdentity $user, $deflimit=50, $optionname='rclimit')
Check for limit and offset parameters on the input, and return sensible defaults if not given.
getValueNames( $exclude=[])
Returns the names of all input values excluding those in $exclude.
bool $markedAsSafe
Whether this HTTP request is "safe" (even if it is an HTTP post)
getUpload( $key)
Return a WebRequestUpload object corresponding to the key.
string $protocol
Cached URL protocol.
getArray( $name, $default=null)
Fetch an array from the input or return $default if it's not set.
interpolateTitle()
Check for title, action, and/or variant data in the URL and interpolate it into the GET variables.
getPostValues()
Get the values passed via POST.
static detectProtocol()
Detect the protocol from $_SERVER.
isSafeRequest()
Whether this request should be identified as being "safe".
getSession()
Return the session for this request.
getRawInput()
Return the raw request body, with no processing.
checkUrlExtension( $extList=[])
This function formerly did a security check to prevent an XSS vulnerability in IE6,...
getValues(... $names)
Extracts the (given) named values into an array.
getRawQueryString()
Return the contents of the Query with no decoding.
getFileTempname( $key)
Return the path to the temporary file where PHP has stored the upload.
getVal( $name, $default=null)
Fetch a text string and partially normalized it.
getFloat( $name, $default=0.0)
Fetch a floating point value from the input or return $default if not set.
WebResponse $response
Lazy-init response object.
getUploadError( $key)
Return the upload error or 0.
getAllHeaders()
Get an array containing all request headers.
getFuzzyBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
getGPCVal( $arr, $name, $default)
Fetch a value from the given array or return $default if it's not set.
static getRequestId()
Get the current request ID.
getProtocol()
Get the current URL protocol (http or https)
getMethod()
Get the HTTP method used for this request.
initHeaders()
Initialise the header list.
getBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
static getRequestPathSuffix( $basePath)
If the request URL matches a given base path, extract the path part of the request URL after that bas...
string $ip
Cached client IP address.
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
setVal( $key, $value)
Set an arbitrary value into our get/post data.
static string $reqId
The unique request ID.
getFullRequestURL()
Return the request URI with the canonical service and hostname, path, and query string.
getElapsedTime()
Get the number of seconds to have elapsed since request start, in fractional seconds,...
float $requestTime
The timestamp of the start of the request, with microsecond precision.
string[] $headers
Lazy-initialized request headers indexed by upper-case header name.
getCrossSiteCookie( $key, $prefix='', $default=null)
Get a cookie set with SameSite=None possibly with a legacy fallback cookie.
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
appendQueryArray( $array)
Appends or replaces value of query variables.
static detectServer()
Work out an appropriate URL prefix containing scheme and host, based on information detected from $_S...
getSessionId()
Get the session id for this request, if any.
getAcceptLang()
Parse the Accept-Language header sent by the client into an array.
static canonicalizeIPv6LoopbackAddress( $ip)
Converts ::1 (IPv6 loopback address) to 127.0.0.1 (IPv4 loopback address); assists in matching truste...
getRawPostString()
Return the contents of the POST with no decoding.
getQueryValues()
Get the values passed in the query string and the path router parameters.
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
getInt( $name, $default=0)
Fetch an integer value from the input or return $default if not set.
wasPosted()
Returns true if the present request was reached by a POST operation, false otherwise (GET,...
setSessionData( $key, $data)
getFileName( $key)
Return the original filename of the uploaded file, as reported by the submitting user agent.
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
hasSafeMethod()
Check if this request uses a "safe" HTTP method.
getRawVal( $name, $default=null)
Fetch a string WITHOUT any Unicode or line break normalization.
getIntArray( $name, $default=null)
Fetch an array of integers, or return $default if it's not set.
appendQueryValue( $key, $value)
normalizeUnicode( $data)
Recursively normalizes UTF-8 strings in the given array.
static overrideRequestId( $id)
Override the unique request ID.
unsetVal( $key)
Unset an arbitrary value from our get/post data.
static getPathInfo( $want='all')
Extract relevant query arguments from the http request uri's path to be merged with the normal php pr...
SessionId null $sessionId
Session ID to use for this request.
getRawIP()
Fetch the raw IP from the request.
setSessionId(SessionId $sessionId)
Set the session for this request.
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
array $data
The parameters from $_GET, $_POST and the path router.
static extractTitle( $path, $bases, $key=false)
URL rewriting function; tries to extract page title and, optionally, one other fixed parameter value ...
getText( $name, $default='')
Fetch a text string and return it in normalized form.
getRequestURL()
Return the path and query string portion of the request URI.
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
getSessionData( $key)
Get data from the session.
string[] $queryAndPathParams
The parameters from $_GET.
getQueryValuesOnly()
Get the values passed in the query string only, not including the path router parameters.
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...