Go to the documentation of this file.
94 $this->requestTime = $_SERVER[
'REQUEST_TIME_FLOAT'];
98 $this->
data = $_POST + $_GET;
122 if ( !empty( $_SERVER[
'REQUEST_URI'] ) ) {
124 $url = $_SERVER[
'REQUEST_URI'];
125 if ( !preg_match(
'!^https?://!', $url ) ) {
126 $url =
'http://unused' . $url;
128 Wikimedia\suppressWarnings();
129 $a = parse_url( $url );
130 Wikimedia\restoreWarnings();
132 $path = $a[
'path'] ??
'';
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'] !=
'' ) {
183 $matches[
'title'] = substr( $_SERVER[
'ORIG_PATH_INFO'], 1 );
185 } elseif ( isset( $_SERVER[
'PATH_INFO'] ) && $_SERVER[
'PATH_INFO'] !=
'' ) {
187 $matches[
'title'] = substr( $_SERVER[
'PATH_INFO'], 1 );
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] ) ) {
226 } elseif ( $parts[1] ===
false ) {
227 if ( isset( $_SERVER[
'SERVER_PORT'] ) ) {
228 $port = $_SERVER[
'SERVER_PORT'];
247 if ( ( !empty( $_SERVER[
'HTTPS'] ) && $_SERVER[
'HTTPS'] !==
'off' ) ||
248 ( isset( $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ) &&
249 $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ===
'https' ) ) {
278 if ( !self::$reqId ) {
301 if ( $this->protocol ===
null ) {
316 if ( defined(
'MW_API' ) ) {
322 $this->
data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
340 $baseLen = strlen(
$base );
341 if ( substr(
$path, 0, $baseLen ) ==
$base ) {
342 $raw = substr(
$path, $baseLen );
344 $matches = [
'title' => rawurldecode( $raw ) ];
363 if ( is_array(
$data ) ) {
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:
385 # https://secure.php.net/variables.external#language.variables.external.dot-in-names
386 # Work around PHP *feature* to avoid *bugs* elsewhere.
388 if ( isset( $arr[
$name] ) ) {
390 if ( isset( $_GET[
$name] ) && !is_array(
$data ) ) {
391 # Check for alternate/legacy character encoding.
392 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
394 $data = $contLang->checkTitleEncoding(
$data );
418 if ( isset( $this->
data[
$name] ) && !is_array( $this->
data[$name] ) ) {
423 if ( is_null( $val ) ) {
442 if ( is_array( $val ) ) {
445 if ( is_null( $val ) ) {
472 if ( !isset( $this->
data[$key] ) ) {
476 unset( $this->
data[$key] );
492 if ( is_null( $val ) ) {
511 if ( is_array( $val ) ) {
512 $val = array_map(
'intval', $val );
540 return is_numeric( $val )
595 # Checkboxes and buttons are only present when clicked
596 # Presence connotes truth, absence false
612 return str_replace(
"\r\n",
"\n", $val );
623 $names = func_get_args();
624 if (
count( $names ) == 0 ) {
625 $names = array_keys( $this->
data );
631 if ( !is_null(
$value ) ) {
645 return array_diff( array_keys( $this->
getValues() ), $exclude );
679 return $_SERVER[
'QUERY_STRING'];
705 $input = file_get_contents(
'php://input' );
716 return $_SERVER[
'REQUEST_METHOD'] ??
'GET';
743 if ( $this->sessionId !==
null ) {
744 $session = SessionManager::singleton()->getSessionById( (
string)$this->sessionId,
true, $this );
750 $session = SessionManager::singleton()->getSessionForRequest( $this );
751 $this->sessionId = $session->getSessionId();
783 public function getCookie( $key, $prefix =
null, $default =
null ) {
784 if ( $prefix ===
null ) {
788 return $this->
getGPCVal( $_COOKIE, $prefix . $key, $default );
801 if ( isset( $_SERVER[
'REQUEST_URI'] ) && strlen( $_SERVER[
'REQUEST_URI'] ) ) {
802 $base = $_SERVER[
'REQUEST_URI'];
803 } elseif ( isset( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
804 && strlen( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
807 $base = $_SERVER[
'HTTP_X_ORIGINAL_URL'];
808 } elseif ( isset( $_SERVER[
'SCRIPT_NAME'] ) ) {
809 $base = $_SERVER[
'SCRIPT_NAME'];
810 if ( isset( $_SERVER[
'QUERY_STRING'] ) && $_SERVER[
'QUERY_STRING'] !=
'' ) {
811 $base .=
'?' . $_SERVER[
'QUERY_STRING'];
815 throw new MWException(
"Web server doesn't provide either " .
816 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
817 "of your web server configuration to https://phabricator.wikimedia.org/" );
823 $hash = strpos(
$base,
'#' );
824 if ( $hash !==
false ) {
828 if (
$base[0] ==
'/' ) {
830 return preg_replace(
'!^/+!',
'/',
$base );
833 return preg_replace(
'!^[^:]+://[^/]+/+!',
'/',
$base );
879 unset( $newquery[
'title'] );
880 $newquery = array_merge( $newquery, $array );
897 $limit = $this->
getInt(
'limit', 0 );
901 if ( ( $limit == 0 ) && ( $optionname !=
'' ) ) {
902 $limit = $wgUser->getIntOption( $optionname );
907 if ( $limit > 5000 ) {
908 $limit = 5000; # We have *some* limits...
911 $offset = $this->
getInt(
'offset', 0 );
916 return [ $limit, $offset ];
927 return $file->getTempName();
938 return $file->getError();
954 return $file->getName();
975 if ( !is_object( $this->
response ) ) {
986 if (
count( $this->headers ) ) {
990 $apacheHeaders = function_exists(
'apache_request_headers' ) ? apache_request_headers() :
false;
991 if ( $apacheHeaders ) {
992 foreach ( $apacheHeaders
as $tempName => $tempValue ) {
993 $this->headers[strtoupper( $tempName )] = $tempValue;
997 if ( substr(
$name, 0, 5 ) ===
'HTTP_' ) {
998 $name = str_replace(
'_',
'-', substr(
$name, 5 ) );
1000 } elseif (
$name ===
'CONTENT_LENGTH' ) {
1001 $this->headers[
'CONTENT-LENGTH'] =
$value;
1032 if ( !isset( $this->headers[
$name] ) ) {
1036 if ( $flags & self::GETHEADER_LIST ) {
1075 $extWhitelist[] =
'php';
1080 if ( $newUrl !==
false ) {
1086 'Invalid file extension found in the path info or query string.' );
1099 header(
'Location: ' . $url );
1100 header(
'Content-Type: text/html' );
1101 $encUrl = htmlspecialchars( $url );
1111 We can
't serve non-HTML content from the URL you have requested, because
1112 Internet Explorer would interpret it as an incorrect and potentially dangerous
1114 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1115 URL you have requested, except that "&*" is appended. This prevents Internet
1116 Explorer from seeing a bogus file extension.
1134 public function getAcceptLang() {
1135 // Modified version of code found at
1136 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1137 $acceptLang = $this->getHeader( 'Accept-
Language' );
1138 if ( !$acceptLang ) {
1142 // Return the language codes in lower case
1143 $acceptLang = strtolower( $acceptLang );
1145 // Break up string into pieces (languages and q factors)
1148 '/([
a-z]{1,8}(-[
a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/
',
1153 if ( !count( $lang_parse[1] ) ) {
1157 $langcodes = $lang_parse[1];
1158 $qvalues = $lang_parse[4];
1159 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1161 // Set default q factor to 1
1162 foreach ( $indices as $index ) {
1163 if ( $qvalues[$index] === '' ) {
1164 $qvalues[$index] = 1;
1165 } elseif ( $qvalues[$index] == 0 ) {
1166 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1170 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1171 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1173 // Create a list like "en" => 0.8
1174 $langs = array_combine( $langcodes, $qvalues );
1187 protected function getRawIP() {
1188 if ( !isset( $_SERVER['REMOTE_ADDR
'] ) ) {
1192 if ( is_array( $_SERVER['REMOTE_ADDR
'] ) || strpos( $_SERVER['REMOTE_ADDR
'], ',
' ) !== false ) {
1193 throw new MWException( __METHOD__
1194 . " : Could not determine the remote IP address due to multiple values." );
1196 $ipchain = $_SERVER['REMOTE_ADDR
'];
1199 return IP::canonicalize( $ipchain );
1211 public function getIP() {
1212 global $wgUsePrivateIPs;
1214 # Return cached result
1215 if ( $this->ip !== null ) {
1219 # collect the originating ips
1220 $ip = $this->getRawIP();
1222 throw new MWException( 'Unable to determine
IP.
' );
1226 $forwardedFor = $this->getHeader( 'X-Forwarded-For
' );
1227 if ( $forwardedFor !== false ) {
1228 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1229 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1230 $ipchain = array_map( 'trim
', explode( ',
', $forwardedFor ) );
1231 $ipchain = array_reverse( $ipchain );
1232 array_unshift( $ipchain, $ip );
1234 # Step through XFF list and find the last address in the list which is a
1235 # trusted server. Set $ip to the IP address given by that trusted server,
1236 # unless the address is not sensible (e.g. private). However, prefer private
1237 # IP addresses over proxy servers controlled by this site (more sensible).
1238 # Note that some XFF values might be "unknown" with Squid/Varnish.
1239 foreach ( $ipchain as $i => $curIP ) {
1240 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1241 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown
'
1242 || !$proxyLookup->isTrustedProxy( $curIP )
1244 break; // IP is not valid/trusted or does not point to anything
1247 IP::isPublic( $ipchain[$i + 1] ) ||
1249 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1251 // Follow the next IP according to the proxy
1252 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1253 if ( !$nextIP && $isConfigured ) {
1254 // We have not yet made it past CDN/proxy servers of this site,
1255 // so either they are misconfigured or there is some IP spoofing.
1256 throw new MWException( "Invalid IP given in XFF '$forwardedFor
'." );
1259 // keep traversing the chain
1266 # Allow extensions to improve our guess
1267 Hooks::run( 'GetIP
', [ &$ip ] );
1270 throw new MWException( "Unable to determine IP." );
1273 wfDebug( "IP: $ip\n" );
1283 public function setIP( $ip ) {
1299 public function hasSafeMethod() {
1300 if ( !isset( $_SERVER['REQUEST_METHOD
'] ) ) {
1301 return false; // CLI mode
1304 return in_array( $_SERVER['REQUEST_METHOD
'], [ 'GET
', 'HEAD
', 'OPTIONS
', 'TRACE
' ] );
1325 public function isSafeRequest() {
1326 if ( $this->markedAsSafe && $this->wasPosted() ) {
1327 return true; // marked as a "safe" POST
1330 return $this->hasSafeMethod();
1343 public function markAsSafeRequest() {
1344 $this->markedAsSafe = true;
add( $path, $params=[], $options=[])
Add a new path pattern to the path router.
initHeaders()
Initialise the header list.
SessionId null $sessionId
Session ID to use for this request.
WebRequest clone which takes values from a provided array.
getSessionData( $key)
Get data from the session.
getValueNames( $exclude=[])
Returns the names of all input values excluding those in $exclude.
static combineHostAndPort( $host, $port, $defaultPort=false)
Given a host name and a port, combine them into host/port string like you might find in a URL.
getSessionId()
Get the session id for this request, if any.
$wgScript
The URL path to index.php.
appendQueryValue( $key, $value)
interpolateTitle()
Check for title, action, and/or variant data in the URL and interpolate it into the GET variables.
setSessionId(SessionId $sessionId)
Set the session for this request.
getElapsedTime()
Get the number of seconds to have elapsed since request start, in fractional seconds,...
getIntOrNull( $name)
Fetch an integer value from the input or return null if empty.
A collection of public static functions to play with IP address and IP ranges.
getRawPostString()
Return the contents of the POST with no decoding.
static detectProtocol()
Detect the protocol from $_SERVER.
getGPCVal( $arr, $name, $default)
Fetch a value from the given array or return $default if it's not set.
</source > ! result< div class="mw-highlight mw-content-ltr" dir="ltr">< pre >< span ></span >< span class="kd"> var</span >< span class="nx"> a</span >< span class="p"></span ></pre ></div > ! end ! test Multiline< source/> in lists !input *< source > a b</source > *foo< source > a b</source > ! html< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! html tidy< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! end ! test Custom attributes !input< source lang="javascript" id="foo" class="bar" dir="rtl" style="font-size: larger;"> var a
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of data
Show an error that looks like an HTTP server error.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
getRawQueryString()
Return the contents of the Query with no decoding.
appendQueryArray( $array)
Appends or replaces value of query variables.
getFileTempname( $key)
Return the path to the temporary file where PHP has stored the upload.
bool $wgAssumeProxiesUseDefaultProtocolPorts
When the wiki is running behind a proxy and this is set to true, assumes that the proxy exposes the w...
getText( $name, $default='')
Fetch a text string from the given array or return $default if it's not set.
string $protocol
Cached URL protocol.
getMethod()
Get the HTTP method used for this request.
getFileName( $key)
Return the original filename of the uploaded file, as reported by the submitting user agent.
setVal( $key, $value)
Set an arbitrary value into our get/post data.
if(is_array( $mode)) switch( $mode) $input
static string $reqId
The unique request ID.
getRawInput()
Return the raw request body, with no processing.
getUpload( $key)
Return a WebRequestUpload object corresponding to the key.
getValues()
Extracts the given named values into an array.
static getPathInfo( $want='all')
Extract relevant query arguments from the http request uri's path to be merged with the normal php pr...
getFullRequestURL()
Return the request URI with the canonical service and hostname, path, and query string.
getArray( $name, $default=null)
Fetch an array from the input or return $default if it's not set.
WebResponse $response
Lazy-init response object.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
getAllHeaders()
Get an array containing all request headers.
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))
Object to access the $_FILES array.
normalizeUnicode( $data)
Recursively normalizes UTF-8 strings in the given array.
getRawVal( $name, $default=null)
Fetch a scalar from the input without normalization, or return $default if it's not set.
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...
Allows to change the fields on the form that will be generated $name
getCheck( $name)
Return true if the named value is set in the input, whatever that value is (even "0").
getProtocol()
Get the current URL protocol (http or https)
getSession()
Return the session for this request.
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
static splitHostAndPort( $both)
Given a host/port string, like one might find in the host part of a URL per RFC 2732,...
getLimitOffset( $deflimit=50, $optionname='rclimit')
Check for limit and offset parameters on the input, and return sensible defaults if not given.
checkUrlExtension( $extWhitelist=[])
Check if Internet Explorer will detect an incorrect cache extension in PATH_INFO or QUERY_STRING.
getIntArray( $name, $default=null)
Fetch an array of integers, or return $default if it's not set.
float $requestTime
The timestamp of the start of the request, with microsecond precision.
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
static fixUrlForIE6( $url, $extWhitelist=[])
Returns a variant of $url which will pass isUrlExtensionBad() but has the same GET parameters,...
bool $markedAsSafe
Whether this HTTP request is "safe" (even if it is an HTTP post)
getCookie( $key, $prefix=null, $default=null)
Get a cookie from the $_COOKIE jar.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
getUploadError( $key)
Return the upload error or 0.
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.
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
getVal( $name, $default=null)
Fetch a scalar from the input or return $default if it's not set.
getInt( $name, $default=0)
Fetch an integer value from the input or return $default if not set.
static getRequestId()
Get the unique request ID.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
getFloat( $name, $default=0.0)
Fetch a floating point value from the input or return $default if not set.
static detectServer()
Work out an appropriate URL prefix containing scheme and host, based on information detected from $_S...
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
string $ip
Cached client IP address.
getPostValues()
Get the values passed via POST.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
wasPosted()
Returns true if the present request was reached by a POST operation, false otherwise (GET,...
unsetVal( $key)
Unset an arbitrary value from our get/post data.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
getRequestURL()
Return the path and query string portion of the request URI.
static overrideRequestId( $id)
Override the unique request ID.
static extractTitle( $path, $bases, $key=false)
URL rewriting function; tries to extract page title and, optionally, one other fixed parameter value ...
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
getQueryValues()
Get the values passed in the query string.
getFuzzyBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
$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.
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
Internationalisation code.
getBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
$wgUsePathInfo
Whether to support URLs like index.php/Page_title These often break when PHP is set up in CGI mode.
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.