88 protected $markedAsSafe =
false;
94 $this->requestTime = $_SERVER[
'REQUEST_TIME_FLOAT'];
98 $this->data = $_POST +
$_GET;
122 if ( !empty( $_SERVER[
'REQUEST_URI'] ) ) {
124 $url = $_SERVER[
'REQUEST_URI'];
126 $url =
'http://unused' . $url;
132 $path = $a[
'path'] ??
'';
135 if ( $path ==
$wgScript && $want !==
'all' ) {
144 $router->
add(
"$wgScript/$1" );
146 if (
isset( $_SERVER[
'SCRIPT_NAME'] )
147 &&
preg_match(
'/\.php/', $_SERVER[
'SCRIPT_NAME'] )
149 # Check for SCRIPT_NAME, we handle index.php explicitly
150 # But we do have some other .php files such as img_auth.php
151 # Don't let root article paths clober the parsing for them
152 $router->add( $_SERVER[
'SCRIPT_NAME'] .
"/$1" );
168 [
'variant' =>
'$2' ],
169 [
'$2' => MediaWikiServices::getInstance()->getContentLanguage()->
174 Hooks::run(
'WebRequestPathInfoRouter', [ $router ] );
179 if (
isset( $_SERVER[
'ORIG_PATH_INFO'] ) && $_SERVER[
'ORIG_PATH_INFO'] !=
'' ) {
185 }
elseif (
isset( $_SERVER[
'PATH_INFO'] ) && $_SERVER[
'PATH_INFO'] !=
'' ) {
203 $proto = self::detectProtocol();
204 $stdPort = $proto ===
'https' ? 443 : 80;
206 $varNames = [
'HTTP_HOST',
'SERVER_NAME',
'HOSTNAME',
'SERVER_ADDR' ];
209 foreach ( $varNames as $varName ) {
210 if ( !
isset( $_SERVER[$varName] ) ) {
214 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
226 }
elseif ( $parts[1] ===
false ) {
227 if (
isset( $_SERVER[
'SERVER_PORT'] ) ) {
228 $port = $_SERVER[
'SERVER_PORT'];
236 return $proto .
'://' . IP::combineHostAndPort( $host, $port, $stdPort );
247 if ( ( !empty( $_SERVER[
'HTTPS'] ) && $_SERVER[
'HTTPS'] !==
'off' ) ||
248 (
isset( $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ) &&
249 $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ===
'https' ) ) {
264 return microtime(
true ) - $this->requestTime;
278 if ( !self::$reqId ) {
301 if ( $this->protocol ===
null ) {
302 $this->protocol = self::detectProtocol();
304 return $this->protocol;
316 if ( defined(
'MW_API' ) ) {
320 $matches = self::getPathInfo(
'title' );
321 foreach (
$matches as $key => $val ) {
322 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] =
$val;
337 foreach ( (
array)$bases as $keyValue =>
$base ) {
342 $raw =
substr( $path, $baseLen );
364 foreach (
$data as $key => $val ) {
368 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
369 $data = $contLang ? $contLang->normalize(
$data ) :
370 UtfNormal\Validator::cleanUp(
$data );
384 # PHP is so nice to not touch input data, except sometimes:
386 # Work around PHP *feature* to avoid *bugs* elsewhere.
387 $name =
strtr( $name,
'.',
'_' );
388 if (
isset( $arr[$name] ) ) {
391 # Check for alternate/legacy character encoding.
392 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
393 $data = $contLang->checkTitleEncoding(
$data );
415 $name =
strtr( $name,
'.',
'_' );
416 if (
isset( $this->data[$name] ) && !
is_array( $this->data[$name] ) ) {
417 $val = $this->data[
$name];
438 public function getVal( $name, $default =
null ) {
439 $val = $this->
getGPCVal( $this->data, $name, $default );
458 $ret = $this->data[$key] ??
null;
459 $this->data[$key] =
$value;
470 if ( !
isset( $this->data[$key] ) ) {
473 $ret = $this->data[$key];
474 unset( $this->data[$key] );
488 public function getArray( $name, $default =
null ) {
489 $val = $this->
getGPCVal( $this->data, $name, $default );
508 $val = $this->
getArray( $name, $default );
524 public function getInt( $name, $default = 0 ) {
553 public function getFloat( $name, $default = 0.0 ) {
566 public function getBool( $name, $default =
false ) {
567 return (
bool)$this->
getRawVal( $name, $default );
580 return $this->
getBool( $name, $default )
593 # Checkboxes and buttons are only present when clicked
594 # Presence connotes truth, absence false
595 return $this->
getRawVal( $name,
null ) !==
null;
608 public function getText( $name, $default =
'' ) {
609 $val = $this->
getVal( $name, $default );
622 if ( count( $names ) == 0 ) {
627 foreach ( $names as $name ) {
677 return $_SERVER[
'QUERY_STRING'];
714 return $_SERVER[
'REQUEST_METHOD'] ??
'GET';
741 if ( $this->sessionId !==
null ) {
742 $session = SessionManager::singleton()->getSessionById( (
string)$this->sessionId,
true, $this );
748 $session = SessionManager::singleton()->getSessionForRequest( $this );
749 $this->sessionId = $session->getSessionId();
760 $this->sessionId = $sessionId;
770 return $this->sessionId;
781 public function getCookie( $key, $prefix =
null, $default =
null ) {
782 if ( $prefix ===
null ) {
786 return $this->
getGPCVal( $_COOKIE, $prefix . $key, $default );
799 if (
isset( $_SERVER[
'REQUEST_URI'] ) &&
strlen( $_SERVER[
'REQUEST_URI'] ) ) {
800 $base = $_SERVER[
'REQUEST_URI'];
801 }
elseif (
isset( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
802 &&
strlen( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
805 $base = $_SERVER[
'HTTP_X_ORIGINAL_URL'];
807 $base = $_SERVER[
'SCRIPT_NAME'];
808 if (
isset( $_SERVER[
'QUERY_STRING'] ) && $_SERVER[
'QUERY_STRING'] !=
'' ) {
809 $base .=
'?' . $_SERVER[
'QUERY_STRING'];
813 throw new MWException(
"Web server doesn't provide either " .
814 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
815 "of your web server configuration to https://phabricator.wikimedia.org/" );
822 if ( $hash !==
false ) {
826 if (
$base[0] ==
'/' ) {
843 return self::getGlobalRequestURL();
877 unset( $newquery[
'title'] );
895 $limit = $this->
getInt(
'limit', 0 );
899 if ( ( $limit == 0 ) && ( $optionname !=
'' ) ) {
900 $limit = $wgUser->getIntOption( $optionname );
905 if ( $limit > 5000 ) {
906 $limit = 5000; # We have *some* limits...
909 $offset = $this->
getInt(
'offset', 0 );
914 return [ $limit, $offset ];
925 return $file->getTempName();
936 return $file->getError();
952 return $file->getName();
974 $class = ( $this instanceof
FauxRequest ) ? FauxResponse::class : WebResponse::class;
984 if ( count( $this->headers ) ) {
989 if ( $apacheHeaders ) {
990 foreach ( $apacheHeaders as $tempName => $tempValue ) {
994 foreach ( $_SERVER as $name =>
$value ) {
995 if (
substr( $name, 0, 5 ) ===
'HTTP_' ) {
998 }
elseif ( $name ===
'CONTENT_LENGTH' ) {
999 $this->headers[
'CONTENT-LENGTH'] =
$value;
1012 return $this->headers;
1030 if ( !
isset( $this->headers[$name] ) ) {
1034 if ( $flags & self::GETHEADER_LIST ) {
1073 $extWhitelist[] =
'php';
1078 if ( $newUrl !==
false ) {
1084 'Invalid file extension found in the path info or query string.' );
1097 header(
'Location: ' . $url );
1098 header(
'Content-Type: text/html' );
1109We can
't serve non-HTML content from the URL you have requested, because
1110Internet Explorer would interpret it as an incorrect and potentially dangerous
1112<p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1113URL you have requested, except that "&*" is appended. This prevents Internet
1114Explorer from seeing a bogus file extension.
1132 public function getAcceptLang() {
1133 // Modified version of code found at
1134 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1135 $acceptLang = $this->getHeader( 'Accept-
Language' );
1136 if ( !$acceptLang ) {
1140 // Return the language codes in lower case
1141 $acceptLang = strtolower( $acceptLang );
1143 // Break up string into pieces (languages and q factors)
1146 '/([a-
z]{1,8}(-[a-
z]{1,8})*|\*)\s*(;\s*
q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/
',
1151 if ( !count( $lang_parse[1] ) ) {
1155 $langcodes = $lang_parse[1];
1156 $qvalues = $lang_parse[4];
1157 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1159 // Set default q factor to 1
1160 foreach ( $indices as $index ) {
1161 if ( $qvalues[$index] === '' ) {
1162 $qvalues[$index] = 1;
1163 } elseif ( $qvalues[$index] == 0 ) {
1164 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1168 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1169 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1171 // Create a list like "en" => 0.8
1172 $langs = array_combine( $langcodes, $qvalues );
1185 protected function getRawIP() {
1186 if ( !isset( $_SERVER['REMOTE_ADDR
'] ) ) {
1190 if ( is_array( $_SERVER['REMOTE_ADDR
'] ) || strpos( $_SERVER['REMOTE_ADDR
'], ',
' ) !== false ) {
1191 throw new MWException( __METHOD__
1192 . " : Could not determine the remote IP address due to multiple values." );
1194 $ipchain = $_SERVER['REMOTE_ADDR
'];
1197 return IP::canonicalize( $ipchain );
1209 public function getIP() {
1210 global $wgUsePrivateIPs;
1212 # Return cached result
1213 if ( $this->ip !== null ) {
1217 # collect the originating ips
1218 $ip = $this->getRawIP();
1220 throw new MWException( 'Unable to determine
IP.
' );
1224 $forwardedFor = $this->getHeader( 'X-Forwarded-For
' );
1225 if ( $forwardedFor !== false ) {
1226 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1227 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1228 $ipchain = array_map( 'trim
', explode( ',
', $forwardedFor ) );
1229 $ipchain = array_reverse( $ipchain );
1230 array_unshift( $ipchain, $ip );
1232 # Step through XFF list and find the last address in the list which is a
1233 # trusted server. Set $ip to the IP address given by that trusted server,
1234 # unless the address is not sensible (e.g. private). However, prefer private
1235 # IP addresses over proxy servers controlled by this site (more sensible).
1236 # Note that some XFF values might be "unknown" with Squid/Varnish.
1237 foreach ( $ipchain as $i => $curIP ) {
1238 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1239 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown
'
1240 || !$proxyLookup->isTrustedProxy( $curIP )
1242 break; // IP is not valid/trusted or does not point to anything
1245 IP::isPublic( $ipchain[$i + 1] ) ||
1247 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1249 // Follow the next IP according to the proxy
1250 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1251 if ( !$nextIP && $isConfigured ) {
1252 // We have not yet made it past CDN/proxy servers of this site,
1253 // so either they are misconfigured or there is some IP spoofing.
1254 throw new MWException( "Invalid IP given in XFF '$forwardedFor
'." );
1257 // keep traversing the chain
1264 # Allow extensions to improve our guess
1265 Hooks::run( 'GetIP
', [ &$ip ] );
1268 throw new MWException( "Unable to determine IP." );
1271 wfDebug( "IP: $ip\n" );
1281 public function setIP( $ip ) {
1297 public function hasSafeMethod() {
1298 if ( !isset( $_SERVER['REQUEST_METHOD
'] ) ) {
1299 return false; // CLI mode
1302 return in_array( $_SERVER['REQUEST_METHOD
'], [ 'GET
', 'HEAD
', 'OPTIONS
', 'TRACE
' ] );
1323 public function isSafeRequest() {
1324 if ( $this->markedAsSafe && $this->wasPosted() ) {
1325 return true; // marked as a "safe" POST
1328 return $this->hasSafeMethod();
1341 public function markAsSafeRequest() {
1342 $this->markedAsSafe = true;
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second redirect
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
$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.
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.
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....
WebRequest clone which takes values from a provided array.
Show an error that looks like an HTTP server error.
static areServerVarsBad( $vars, $extWhitelist=[])
Check a subset of $_SERVER (or the whole of $_SERVER if you like) to see if it indicates that the req...
static fixUrlForIE6( $url, $extWhitelist=[])
Returns a variant of $url which will pass isUrlExtensionBad() but has the same GET parameters,...
A collection of public static functions to play with IP address and IP ranges.
Internationalisation code.
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...
getIntOrNull( $name)
Fetch an integer value from the input or return null if empty.
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.
getSession()
Return the session for this request.
getRawInput()
Return the raw request body, with no processing.
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 scalar from the input or return $default if it's not set.
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 unique 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.
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.
checkUrlExtension( $extWhitelist=[])
Check if Internet Explorer will detect an incorrect cache extension in PATH_INFO or 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.
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.
getRawPostString()
Return the contents of the POST with no decoding.
getQueryValues()
Get the values passed in the query string.
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
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)
Set session data.
doSecurityRedirect( $url)
Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in IE 6.
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.
getRawVal( $name, $default=null)
Fetch a scalar from the input without normalization, or return $default if it's not set.
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.
setSessionId(SessionId $sessionId)
Set the session for this request.
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
getLimitOffset( $deflimit=50, $optionname='rclimit')
Check for limit and offset parameters on the input, and return sensible defaults if not given.
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 from the given array or return $default if it's not set.
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.
getValues()
Extracts the given named values into an array.
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Allows to change the fields on the form that will be generated $name
this hook is for auditing only $response
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(is_array($mode)) switch( $mode) $input