85 protected $markedAsSafe =
false;
91 $this->requestTime = isset( $_SERVER[
'REQUEST_TIME_FLOAT'] )
92 ? $_SERVER[
'REQUEST_TIME_FLOAT'] : microtime(
true );
96 $this->data = $_POST + $_GET;
120 if ( !empty( $_SERVER[
'REQUEST_URI'] ) ) {
122 $url = $_SERVER[
'REQUEST_URI'];
123 if ( !preg_match(
'!^https?://!', $url ) ) {
124 $url =
'http://unused' . $url;
126 MediaWiki\suppressWarnings();
127 $a = parse_url( $url );
128 MediaWiki\restoreWarnings();
130 $path = isset( $a[
'path'] ) ? $a[
'path'] :
'';
133 if ( $path ==
$wgScript && $want !==
'all' ) {
142 $router->
add(
"$wgScript/$1" );
144 if ( isset( $_SERVER[
'SCRIPT_NAME'] )
145 && preg_match(
'/\.php5?/', $_SERVER[
'SCRIPT_NAME'] )
147 # Check for SCRIPT_NAME, we handle index.php explicitly
148 # But we do have some other .php files such as img_auth.php
149 # Don't let root article paths clober the parsing for them
150 $router->add( $_SERVER[
'SCRIPT_NAME'] .
"/$1" );
166 [
'variant' =>
'$2' ],
171 Hooks::run(
'WebRequestPathInfoRouter', [ $router ] );
176 if ( isset( $_SERVER[
'ORIG_PATH_INFO'] ) && $_SERVER[
'ORIG_PATH_INFO'] !=
'' ) {
180 $matches[
'title'] = substr( $_SERVER[
'ORIG_PATH_INFO'], 1 );
182 } elseif ( isset( $_SERVER[
'PATH_INFO'] ) && $_SERVER[
'PATH_INFO'] !=
'' ) {
184 $matches[
'title'] = substr( $_SERVER[
'PATH_INFO'], 1 );
200 $proto = self::detectProtocol();
201 $stdPort = $proto ===
'https' ? 443 : 80;
203 $varNames = [
'HTTP_HOST',
'SERVER_NAME',
'HOSTNAME',
'SERVER_ADDR' ];
206 foreach ( $varNames as $varName ) {
207 if ( !isset( $_SERVER[$varName] ) ) {
211 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
223 } elseif ( $parts[1] ===
false ) {
224 if ( isset( $_SERVER[
'SERVER_PORT'] ) ) {
225 $port = $_SERVER[
'SERVER_PORT'];
233 return $proto .
'://' . IP::combineHostAndPort( $host, $port, $stdPort );
244 if ( ( !empty( $_SERVER[
'HTTPS'] ) && $_SERVER[
'HTTPS'] !==
'off' ) ||
245 ( isset( $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ) &&
246 $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ===
'https' ) ) {
261 return microtime(
true ) - $this->requestTime;
273 if ( !self::$reqId ) {
274 self::$reqId = isset( $_SERVER[
'UNIQUE_ID'] )
297 if ( $this->protocol ===
null ) {
298 $this->protocol = self::detectProtocol();
300 return $this->protocol;
312 if ( defined(
'MW_API' ) ) {
316 $matches = self::getPathInfo(
'title' );
317 foreach (
$matches as $key => $val ) {
318 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
333 foreach ( (array)$bases as $keyValue =>
$base ) {
336 $baseLen = strlen(
$base );
337 if ( substr( $path, 0, $baseLen ) ==
$base ) {
338 $raw = substr( $path, $baseLen );
340 $matches = [
'title' => rawurldecode( $raw ) ];
359 if ( is_array(
$data ) ) {
360 foreach (
$data as $key => $val ) {
367 UtfNormal\Validator::cleanUp(
$data );
381 # PHP is so nice to not touch input data, except sometimes:
383 # Work around PHP *feature* to avoid *bugs* elsewhere.
384 $name = strtr( $name,
'.',
'_' );
385 if ( isset( $arr[$name] ) ) {
388 if ( isset( $_GET[$name] ) && !is_array(
$data ) ) {
389 # Check for alternate/legacy character encoding.
414 $name = strtr( $name,
'.',
'_' );
415 if ( isset( $this->data[$name] ) && !is_array( $this->data[$name] ) ) {
416 $val = $this->data[
$name];
420 if ( is_null( $val ) ) {
437 public function getVal( $name, $default =
null ) {
438 $val = $this->
getGPCVal( $this->data, $name, $default );
439 if ( is_array( $val ) ) {
442 if ( is_null( $val ) ) {
457 $ret = isset( $this->data[$key] ) ? $this->data[$key] :
null;
458 $this->data[$key] =
$value;
469 if ( !isset( $this->data[$key] ) ) {
472 $ret = $this->data[$key];
473 unset( $this->data[$key] );
487 public function getArray( $name, $default =
null ) {
488 $val = $this->
getGPCVal( $this->data, $name, $default );
489 if ( is_null( $val ) ) {
507 $val = $this->
getArray( $name, $default );
508 if ( is_array( $val ) ) {
509 $val = array_map(
'intval', $val );
523 public function getInt( $name, $default = 0 ) {
524 return intval( $this->
getRawVal( $name, $default ) );
537 return is_numeric( $val )
552 public function getFloat( $name, $default = 0.0 ) {
553 return floatval( $this->
getRawVal( $name, $default ) );
565 public function getBool( $name, $default =
false ) {
566 return (
bool)$this->
getRawVal( $name, $default );
579 return $this->
getBool( $name, $default )
580 && strcasecmp( $this->
getRawVal( $name ),
'false' ) !== 0;
592 # Checkboxes and buttons are only present when clicked
593 # Presence connotes truth, absence false
594 return $this->
getRawVal( $name,
null ) !==
null;
607 public function getText( $name, $default =
'' ) {
608 $val = $this->
getVal( $name, $default );
609 return str_replace(
"\r\n",
"\n", $val );
620 $names = func_get_args();
621 if ( count( $names ) == 0 ) {
622 $names = array_keys( $this->data );
626 foreach ( $names as $name ) {
628 if ( !is_null(
$value ) ) {
642 return array_diff( array_keys( $this->
getValues() ), $exclude );
664 return $_SERVER[
'QUERY_STRING'];
690 $input = file_get_contents(
'php://input' );
701 return isset( $_SERVER[
'REQUEST_METHOD'] ) ? $_SERVER[
'REQUEST_METHOD'] :
'GET';
728 if ( $this->sessionId !==
null ) {
729 $session = SessionManager::singleton()->getSessionById( (
string)$this->sessionId,
true, $this );
735 $session = SessionManager::singleton()->getSessionForRequest( $this );
736 $this->sessionId = $session->getSessionId();
747 $this->sessionId = $sessionId;
757 return $this->sessionId;
768 public function getCookie( $key, $prefix =
null, $default =
null ) {
769 if ( $prefix ===
null ) {
773 return $this->
getGPCVal( $_COOKIE, $prefix . $key, $default );
784 if ( isset( $_SERVER[
'REQUEST_URI'] ) && strlen( $_SERVER[
'REQUEST_URI'] ) ) {
785 $base = $_SERVER[
'REQUEST_URI'];
786 } elseif ( isset( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
787 && strlen( $_SERVER[
'HTTP_X_ORIGINAL_URL'] )
790 $base = $_SERVER[
'HTTP_X_ORIGINAL_URL'];
791 } elseif ( isset( $_SERVER[
'SCRIPT_NAME'] ) ) {
792 $base = $_SERVER[
'SCRIPT_NAME'];
793 if ( isset( $_SERVER[
'QUERY_STRING'] ) && $_SERVER[
'QUERY_STRING'] !=
'' ) {
794 $base .=
'?' . $_SERVER[
'QUERY_STRING'];
798 throw new MWException(
"Web server doesn't provide either " .
799 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
800 "of your web server configuration to https://phabricator.wikimedia.org/" );
806 $hash = strpos(
$base,
'#' );
807 if ( $hash !==
false ) {
811 if (
$base[0] ==
'/' ) {
813 return preg_replace(
'!^/+!',
'/',
$base );
816 return preg_replace(
'!^[^:]+://[^/]+/+!',
'/',
$base );
828 return self::getGlobalRequestURL();
862 unset( $newquery[
'title'] );
863 $newquery = array_merge( $newquery, $array );
880 $limit = $this->
getInt(
'limit', 0 );
884 if ( ( $limit == 0 ) && ( $optionname !=
'' ) ) {
885 $limit =
$wgUser->getIntOption( $optionname );
890 if ( $limit > 5000 ) {
891 $limit = 5000; # We have *
some* limits...
894 $offset = $this->
getInt(
'offset', 0 );
899 return [ $limit, $offset ];
910 return $file->getTempName();
921 return $file->getError();
937 return $file->getName();
958 if ( !is_object( $this->
response ) ) {
959 $class = ( $this instanceof
FauxRequest ) ?
'FauxResponse' :
'WebResponse';
969 if ( count( $this->
headers ) ) {
973 $apacheHeaders = function_exists(
'apache_request_headers' ) ? apache_request_headers() :
false;
974 if ( $apacheHeaders ) {
975 foreach ( $apacheHeaders as $tempName => $tempValue ) {
976 $this->
headers[strtoupper( $tempName )] = $tempValue;
979 foreach ( $_SERVER as $name =>
$value ) {
980 if ( substr( $name, 0, 5 ) ===
'HTTP_' ) {
981 $name = str_replace(
'_',
'-', substr( $name, 5 ) );
983 } elseif ( $name ===
'CONTENT_LENGTH' ) {
997 return $this->headers;
1014 $name = strtoupper( $name );
1015 if ( !isset( $this->
headers[$name] ) ) {
1019 if (
$flags & self::GETHEADER_LIST ) {
1058 $extWhitelist[] =
'php';
1063 if ( $newUrl !==
false ) {
1069 'Invalid file extension found in the path info or query string.' );
1082 header(
'Location: ' . $url );
1083 header(
'Content-Type: text/html' );
1084 $encUrl = htmlspecialchars( $url );
1094We can
't serve non-HTML content from the URL you have requested, because
1095Internet Explorer would interpret it as an incorrect and potentially dangerous
1097<p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1098URL you have requested, except that "&*" is appended. This prevents Internet
1099Explorer from seeing a bogus file extension.
1117 public function getAcceptLang() {
1118 // Modified version of code found at
1119 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1120 $acceptLang = $this->getHeader( 'Accept-
Language' );
1121 if ( !$acceptLang ) {
1125 // Return the language codes in lower case
1126 $acceptLang = strtolower( $acceptLang );
1128 // Break up string into pieces (languages and q factors)
1131 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/
',
1136 if ( !count( $lang_parse[1] ) ) {
1140 $langcodes = $lang_parse[1];
1141 $qvalues = $lang_parse[4];
1142 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1144 // Set default q factor to 1
1145 foreach ( $indices as $index ) {
1146 if ( $qvalues[$index] === '' ) {
1147 $qvalues[$index] = 1;
1148 } elseif ( $qvalues[$index] == 0 ) {
1149 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1153 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1154 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1156 // Create a list like "en" => 0.8
1157 $langs = array_combine( $langcodes, $qvalues );
1170 protected function getRawIP() {
1171 if ( !isset( $_SERVER['REMOTE_ADDR
'] ) ) {
1175 if ( is_array( $_SERVER['REMOTE_ADDR
'] ) || strpos( $_SERVER['REMOTE_ADDR
'], ',
' ) !== false ) {
1176 throw new MWException( __METHOD__
1177 . " : Could not determine the remote IP address due to multiple values." );
1179 $ipchain = $_SERVER['REMOTE_ADDR
'];
1182 return IP::canonicalize( $ipchain );
1194 public function getIP() {
1195 global $wgUsePrivateIPs;
1197 # Return cached result
1198 if ( $this->ip !== null ) {
1202 # collect the originating ips
1203 $ip = $this->getRawIP();
1205 throw new MWException( 'Unable to determine
IP.
' );
1209 $forwardedFor = $this->getHeader( 'X-Forwarded-For
' );
1210 if ( $forwardedFor !== false ) {
1211 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1212 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1213 $ipchain = array_map( 'trim
', explode( ',
', $forwardedFor ) );
1214 $ipchain = array_reverse( $ipchain );
1215 array_unshift( $ipchain, $ip );
1217 # Step through XFF list and find the last address in the list which is a
1218 # trusted server. Set $ip to the IP address given by that trusted server,
1219 # unless the address is not sensible (e.g. private). However, prefer private
1220 # IP addresses over proxy servers controlled by this site (more sensible).
1221 # Note that some XFF values might be "unknown" with Squid/Varnish.
1222 foreach ( $ipchain as $i => $curIP ) {
1223 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1224 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown
'
1225 || !$proxyLookup->isTrustedProxy( $curIP )
1227 break; // IP is not valid/trusted or does not point to anything
1230 IP::isPublic( $ipchain[$i + 1] ) ||
1232 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1234 // Follow the next IP according to the proxy
1235 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1236 if ( !$nextIP && $isConfigured ) {
1237 // We have not yet made it past CDN/proxy servers of this site,
1238 // so either they are misconfigured or there is some IP spoofing.
1239 throw new MWException( "Invalid IP given in XFF '$forwardedFor
'." );
1242 // keep traversing the chain
1249 # Allow extensions to improve our guess
1250 Hooks::run( 'GetIP
', [ &$ip ] );
1253 throw new MWException( "Unable to determine IP." );
1256 wfDebug( "IP: $ip\n" );
1266 public function setIP( $ip ) {
1282 public function hasSafeMethod() {
1283 if ( !isset( $_SERVER['REQUEST_METHOD
'] ) ) {
1284 return false; // CLI mode
1287 return in_array( $_SERVER['REQUEST_METHOD
'], [ 'GET
', 'HEAD
', 'OPTIONS
', 'TRACE
' ] );
1308 public function isSafeRequest() {
1309 if ( $this->markedAsSafe && $this->wasPosted() ) {
1310 return true; // marked as a "safe" POST
1313 return $this->hasSafeMethod();
1326 public function markAsSafeRequest() {
1327 $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
$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.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
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.
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 ...
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
I won t presume to tell you how to I m just describing the methods I chose to use for myself If you do choose to follow these it will probably be easier for you to collaborate with others on the but if you want to contribute without by all means do which work well I also use K &R brace matching style I know that s a religious issue for some
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add headers
it s the revision text itself In either if gzip is the revision text is gzipped $flags
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
if(is_array($mode)) switch( $mode) $input