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
27 * The WebRequest class encapsulates getting at data passed in the
28 * URL or via a POSTed form stripping illegal input characters and
29 * normalizing Unicode sequences.
31 * Usually this is used via a global singleton, $wgRequest. You should
32 * not create a second WebRequest object; make a FauxRequest object if
33 * you want to pass arbitrary data to some function in place of the web
39 protected $data, $headers = array();
42 * Lazy-init response object
48 * Cached client IP address
59 public function __construct() {
60 if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
61 throw new MWException( "MediaWiki does not function when magic quotes are enabled." );
64 // POST overrides GET data
65 // We don't use $_REQUEST here to avoid interference from cookies...
66 $this->data
= $_POST +
$_GET;
70 * Extract relevant query arguments from the http request uri's path
71 * to be merged with the normal php provided query arguments.
72 * Tries to use the REQUEST_URI data if available and parses it
73 * according to the wiki's configuration looking for any known pattern.
75 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
76 * provided by the server if any and use that to set a 'title' parameter.
78 * @param string $want If this is not 'all', then the function
79 * will return an empty array if it determines that the URL is
80 * inside a rewrite path.
82 * @return array Any query arguments found in path matches.
84 public static function getPathInfo( $want = 'all' ) {
85 global $wgUsePathInfo;
86 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
87 // And also by Apache 2.x, double slashes are converted to single slashes.
88 // So we will use REQUEST_URI if possible.
90 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
91 // Slurp out the path portion to examine...
92 $url = $_SERVER['REQUEST_URI'];
93 if ( !preg_match( '!^https?://!', $url ) ) {
94 $url = 'http://unused' . $url;
97 $a = parse_url( $url );
100 $path = isset( $a['path'] ) ?
$a['path'] : '';
103 if ( $path == $wgScript && $want !== 'all' ) {
104 // Script inside a rewrite path?
105 // Abort to keep from breaking...
109 $router = new PathRouter
;
111 // Raw PATH_INFO style
112 $router->add( "$wgScript/$1" );
114 if ( isset( $_SERVER['SCRIPT_NAME'] )
115 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
117 # Check for SCRIPT_NAME, we handle index.php explicitly
118 # But we do have some other .php files such as img_auth.php
119 # Don't let root article paths clober the parsing for them
120 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
123 global $wgArticlePath;
124 if ( $wgArticlePath ) {
125 $router->add( $wgArticlePath );
128 global $wgActionPaths;
129 if ( $wgActionPaths ) {
130 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
133 global $wgVariantArticlePath, $wgContLang;
134 if ( $wgVariantArticlePath ) {
135 $router->add( $wgVariantArticlePath,
136 array( 'variant' => '$2' ),
137 array( '$2' => $wgContLang->getVariants() )
141 wfRunHooks( 'WebRequestPathInfoRouter', array( $router ) );
143 $matches = $router->parse( $path );
145 } elseif ( $wgUsePathInfo ) {
146 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
148 // http://bugs.php.net/bug.php?id=31892
149 // Also reported when ini_get('cgi.fix_pathinfo')==false
150 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
152 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
153 // Regular old PATH_INFO yay
154 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
162 * Work out an appropriate URL prefix containing scheme and host, based on
163 * information detected from $_SERVER
167 public static function detectServer() {
168 $proto = self
::detectProtocol();
169 $stdPort = $proto === 'https' ?
443 : 80;
171 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
174 foreach ( $varNames as $varName ) {
175 if ( !isset( $_SERVER[$varName] ) ) {
178 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
180 // Invalid, do not use
184 if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
185 // Bug 70021: Assume that upstream proxy is running on the default
186 // port based on the protocol. We have no reliable way to determine
187 // the actual port in use upstream.
189 } elseif ( $parts[1] === false ) {
190 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
191 $port = $_SERVER['SERVER_PORT'];
192 } // else leave it as $stdPort
199 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
203 * Detect the protocol from $_SERVER.
204 * This is for use prior to Setup.php, when no WebRequest object is available.
205 * At other times, use the non-static function getProtocol().
209 public static function detectProtocol() {
210 if ( ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ||
211 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
212 $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) ) {
220 * Get the current URL protocol (http or https)
223 public function getProtocol() {
224 if ( $this->protocol
=== null ) {
225 $this->protocol
= self
::detectProtocol();
227 return $this->protocol
;
231 * Check for title, action, and/or variant data in the URL
232 * and interpolate it into the GET variables.
233 * This should only be run after $wgContLang is available,
234 * as we may need the list of language variants to determine
235 * available variant URLs.
237 public function interpolateTitle() {
238 // bug 16019: title interpolation on API queries is useless and sometimes harmful
239 if ( defined( 'MW_API' ) ) {
243 $matches = self
::getPathInfo( 'title' );
244 foreach ( $matches as $key => $val ) {
245 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
250 * URL rewriting function; tries to extract page title and,
251 * optionally, one other fixed parameter value from a URL path.
253 * @param string $path The URL path given from the client
254 * @param array $bases One or more URLs, optionally with $1 at the end
255 * @param string $key If provided, the matching key in $bases will be
256 * passed on as the value of this URL parameter
257 * @return array Array of URL variables to interpolate; empty if no match
259 static function extractTitle( $path, $bases, $key = false ) {
260 foreach ( (array)$bases as $keyValue => $base ) {
261 // Find the part after $wgArticlePath
262 $base = str_replace( '$1', '', $base );
263 $baseLen = strlen( $base );
264 if ( substr( $path, 0, $baseLen ) == $base ) {
265 $raw = substr( $path, $baseLen );
267 $matches = array( 'title' => rawurldecode( $raw ) );
269 $matches[$key] = $keyValue;
279 * Recursively normalizes UTF-8 strings in the given array.
281 * @param string|array $data
282 * @return array|string Cleaned-up version of the given
285 function normalizeUnicode( $data ) {
286 if ( is_array( $data ) ) {
287 foreach ( $data as $key => $val ) {
288 $data[$key] = $this->normalizeUnicode( $val );
292 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
298 * Fetch a value from the given array or return $default if it's not set.
301 * @param string $name
302 * @param mixed $default
305 private function getGPCVal( $arr, $name, $default ) {
306 # PHP is so nice to not touch input data, except sometimes:
307 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
308 # Work around PHP *feature* to avoid *bugs* elsewhere.
309 $name = strtr( $name, '.', '_' );
310 if ( isset( $arr[$name] ) ) {
313 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
314 # Check for alternate/legacy character encoding.
315 if ( isset( $wgContLang ) ) {
316 $data = $wgContLang->checkTitleEncoding( $data );
319 $data = $this->normalizeUnicode( $data );
327 * Fetch a scalar from the input or return $default if it's not set.
328 * Returns a string. Arrays are discarded. Useful for
329 * non-freeform text inputs (e.g. predefined internal text keys
330 * selected by a drop-down menu). For freeform input, see getText().
332 * @param string $name
333 * @param string $default Optional default (or null)
336 public function getVal( $name, $default = null ) {
337 $val = $this->getGPCVal( $this->data
, $name, $default );
338 if ( is_array( $val ) ) {
341 if ( is_null( $val ) ) {
349 * Set an arbitrary value into our get/post data.
351 * @param string $key Key name to use
352 * @param mixed $value Value to set
353 * @return mixed Old value if one was present, null otherwise
355 public function setVal( $key, $value ) {
356 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
357 $this->data
[$key] = $value;
362 * Unset an arbitrary value from our get/post data.
364 * @param string $key Key name to use
365 * @return mixed Old value if one was present, null otherwise
367 public function unsetVal( $key ) {
368 if ( !isset( $this->data
[$key] ) ) {
371 $ret = $this->data
[$key];
372 unset( $this->data
[$key] );
378 * Fetch an array from the input or return $default if it's not set.
379 * If source was scalar, will return an array with a single element.
380 * If no source and no default, returns null.
382 * @param string $name
383 * @param array $default Optional default (or null)
386 public function getArray( $name, $default = null ) {
387 $val = $this->getGPCVal( $this->data
, $name, $default );
388 if ( is_null( $val ) ) {
396 * Fetch an array of integers, or return $default if it's not set.
397 * If source was scalar, will return an array with a single element.
398 * If no source and no default, returns null.
399 * If an array is returned, contents are guaranteed to be integers.
401 * @param string $name
402 * @param array $default Option default (or null)
403 * @return array Array of ints
405 public function getIntArray( $name, $default = null ) {
406 $val = $this->getArray( $name, $default );
407 if ( is_array( $val ) ) {
408 $val = array_map( 'intval', $val );
414 * Fetch an integer value from the input or return $default if not set.
415 * Guaranteed to return an integer; non-numeric input will typically
418 * @param string $name
419 * @param int $default
422 public function getInt( $name, $default = 0 ) {
423 return intval( $this->getVal( $name, $default ) );
427 * Fetch an integer value from the input or return null if empty.
428 * Guaranteed to return an integer or null; non-numeric input will
429 * typically return null.
431 * @param string $name
434 public function getIntOrNull( $name ) {
435 $val = $this->getVal( $name );
436 return is_numeric( $val )
442 * Fetch a floating point value from the input or return $default if not set.
443 * Guaranteed to return a float; non-numeric input will typically
447 * @param string $name
448 * @param float $default
451 public function getFloat( $name, $default = 0.0 ) {
452 return floatval( $this->getVal( $name, $default ) );
456 * Fetch a boolean value from the input or return $default if not set.
457 * Guaranteed to return true or false, with normal PHP semantics for
458 * boolean interpretation of strings.
460 * @param string $name
461 * @param bool $default
464 public function getBool( $name, $default = false ) {
465 return (bool)$this->getVal( $name, $default );
469 * Fetch a boolean value from the input or return $default if not set.
470 * Unlike getBool, the string "false" will result in boolean false, which is
471 * useful when interpreting information sent from JavaScript.
473 * @param string $name
474 * @param bool $default
477 public function getFuzzyBool( $name, $default = false ) {
478 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
482 * Return true if the named value is set in the input, whatever that
483 * value is (even "0"). Return false if the named value is not set.
484 * Example use is checking for the presence of check boxes in forms.
486 * @param string $name
489 public function getCheck( $name ) {
490 # Checkboxes and buttons are only present when clicked
491 # Presence connotes truth, absence false
492 return $this->getVal( $name, null ) !== null;
496 * Fetch a text string from the given array or return $default if it's not
497 * set. Carriage returns are stripped from the text, and with some language
498 * modules there is an input transliteration applied. This should generally
499 * be used for form "<textarea>" and "<input>" fields. Used for
500 * user-supplied freeform text input (for which input transformations may
501 * be required - e.g. Esperanto x-coding).
503 * @param string $name
504 * @param string $default Optional
507 public function getText( $name, $default = '' ) {
509 $val = $this->getVal( $name, $default );
510 return str_replace( "\r\n", "\n",
511 $wgContLang->recodeInput( $val ) );
515 * Extracts the given named values into an array.
516 * If no arguments are given, returns all input values.
517 * No transformation is performed on the values.
521 public function getValues() {
522 $names = func_get_args();
523 if ( count( $names ) == 0 ) {
524 $names = array_keys( $this->data
);
528 foreach ( $names as $name ) {
529 $value = $this->getGPCVal( $this->data
, $name, null );
530 if ( !is_null( $value ) ) {
531 $retVal[$name] = $value;
538 * Returns the names of all input values excluding those in $exclude.
540 * @param array $exclude
543 public function getValueNames( $exclude = array() ) {
544 return array_diff( array_keys( $this->getValues() ), $exclude );
548 * Get the values passed in the query string.
549 * No transformation is performed on the values.
553 public function getQueryValues() {
558 * Return the contents of the Query with no decoding. Use when you need to
559 * know exactly what was sent, e.g. for an OAuth signature over the elements.
563 public function getRawQueryString() {
564 return $_SERVER['QUERY_STRING'];
568 * Return the contents of the POST with no decoding. Use when you need to
569 * know exactly what was sent, e.g. for an OAuth signature over the elements.
573 public function getRawPostString() {
574 if ( !$this->wasPosted() ) {
577 return $this->getRawInput();
581 * Return the raw request body, with no processing. Cached since some methods
582 * disallow reading the stream more than once. As stated in the php docs, this
583 * does not work with enctype="multipart/form-data".
587 public function getRawInput() {
588 static $input = null;
589 if ( $input === null ) {
590 $input = file_get_contents( 'php://input' );
596 * Get the HTTP method used for this request.
600 public function getMethod() {
601 return isset( $_SERVER['REQUEST_METHOD'] ) ?
$_SERVER['REQUEST_METHOD'] : 'GET';
605 * Returns true if the present request was reached by a POST operation,
606 * false otherwise (GET, HEAD, or command-line).
608 * Note that values retrieved by the object may come from the
609 * GET URL etc even on a POST request.
613 public function wasPosted() {
614 return $this->getMethod() == 'POST';
618 * Returns true if there is a session cookie set.
619 * This does not necessarily mean that the user is logged in!
621 * If you want to check for an open session, use session_id()
622 * instead; that will also tell you if the session was opened
623 * during the current request (in which case the cookie will
624 * be sent back to the client at the end of the script run).
628 public function checkSessionCookie() {
629 return isset( $_COOKIE[session_name()] );
633 * Get a cookie from the $_COOKIE jar
635 * @param string $key The name of the cookie
636 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
637 * @param mixed $default What to return if the value isn't found
638 * @return mixed Cookie value or $default if the cookie not set
640 public function getCookie( $key, $prefix = null, $default = null ) {
641 if ( $prefix === null ) {
642 global $wgCookiePrefix;
643 $prefix = $wgCookiePrefix;
645 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
649 * Return the path and query string portion of the request URI.
650 * This will be suitable for use as a relative link in HTML output.
652 * @throws MWException
655 public function getRequestURL() {
656 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
657 $base = $_SERVER['REQUEST_URI'];
658 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
659 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
661 // Probably IIS; doesn't set REQUEST_URI
662 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
663 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
664 $base = $_SERVER['SCRIPT_NAME'];
665 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
666 $base .= '?' . $_SERVER['QUERY_STRING'];
669 // This shouldn't happen!
670 throw new MWException( "Web server doesn't provide either " .
671 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
672 "of your web server configuration to http://bugzilla.wikimedia.org/" );
674 // User-agents should not send a fragment with the URI, but
675 // if they do, and the web server passes it on to us, we
676 // need to strip it or we get false-positive redirect loops
677 // or weird output URLs
678 $hash = strpos( $base, '#' );
679 if ( $hash !== false ) {
680 $base = substr( $base, 0, $hash );
683 if ( $base[0] == '/' ) {
684 // More than one slash will look like it is protocol relative
685 return preg_replace( '!^/+!', '/', $base );
687 // We may get paths with a host prepended; strip it.
688 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
693 * Return the request URI with the canonical service and hostname, path,
694 * and query string. This will be suitable for use as an absolute link
695 * in HTML or other output.
697 * If $wgServer is protocol-relative, this will return a fully
698 * qualified URL with the protocol that was used for this request.
702 public function getFullRequestURL() {
703 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
707 * Take an arbitrary query and rewrite the present URL to include it
708 * @deprecated Use appendQueryValue/appendQueryArray instead
709 * @param string $query Query string fragment; do not include initial '?'
712 public function appendQuery( $query ) {
713 wfDeprecated( __METHOD__
, '1.25' );
714 return $this->appendQueryArray( wfCgiToArray( $query ) );
719 * @param string $value
720 * @param bool $onlyquery [deprecated]
723 public function appendQueryValue( $key, $value, $onlyquery = true ) {
724 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
728 * Appends or replaces value of query variables.
730 * @param array $array Array of values to replace/add to query
731 * @param bool $onlyquery Whether to only return the query string and not the complete URL [deprecated]
734 public function appendQueryArray( $array, $onlyquery = true ) {
736 $newquery = $this->getQueryValues();
737 unset( $newquery['title'] );
738 $newquery = array_merge( $newquery, $array );
739 $query = wfArrayToCgi( $newquery );
741 wfDeprecated( __METHOD__
, '1.25' );
742 return $wgTitle->getLocalURL( $query );
749 * Check for limit and offset parameters on the input, and return sensible
750 * defaults if not given. The limit must be positive and is capped at 5000.
751 * Offset must be positive but is not capped.
753 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
754 * @param string $optionname To specify an option other than rclimit to pull from.
755 * @return array First element is limit, second is offset
757 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
760 $limit = $this->getInt( 'limit', 0 );
764 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
765 $limit = $wgUser->getIntOption( $optionname );
770 if ( $limit > 5000 ) {
771 $limit = 5000; # We have *some* limits...
774 $offset = $this->getInt( 'offset', 0 );
779 return array( $limit, $offset );
783 * Return the path to the temporary file where PHP has stored the upload.
786 * @return string|null String or null if no such file.
788 public function getFileTempname( $key ) {
789 $file = new WebRequestUpload( $this, $key );
790 return $file->getTempName();
794 * Return the upload error or 0
799 public function getUploadError( $key ) {
800 $file = new WebRequestUpload( $this, $key );
801 return $file->getError();
805 * Return the original filename of the uploaded file, as reported by
806 * the submitting user agent. HTML-style character entities are
807 * interpreted and normalized to Unicode normalization form C, in part
808 * to deal with weird input from Safari with non-ASCII filenames.
810 * Other than this the name is not verified for being a safe filename.
813 * @return string|null String or null if no such file.
815 public function getFileName( $key ) {
816 $file = new WebRequestUpload( $this, $key );
817 return $file->getName();
821 * Return a WebRequestUpload object corresponding to the key
824 * @return WebRequestUpload
826 public function getUpload( $key ) {
827 return new WebRequestUpload( $this, $key );
831 * Return a handle to WebResponse style object, for setting cookies,
832 * headers and other stuff, for Request being worked on.
834 * @return WebResponse
836 public function response() {
837 /* Lazy initialization of response object for this request */
838 if ( !is_object( $this->response
) ) {
839 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
840 $this->response
= new $class();
842 return $this->response
;
846 * Initialise the header list
848 private function initHeaders() {
849 if ( count( $this->headers
) ) {
853 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
854 if ( $apacheHeaders ) {
855 foreach ( $apacheHeaders as $tempName => $tempValue ) {
856 $this->headers
[strtoupper( $tempName )] = $tempValue;
859 foreach ( $_SERVER as $name => $value ) {
860 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
861 $name = str_replace( '_', '-', substr( $name, 5 ) );
862 $this->headers
[$name] = $value;
863 } elseif ( $name === 'CONTENT_LENGTH' ) {
864 $this->headers
['CONTENT-LENGTH'] = $value;
871 * Get an array containing all request headers
873 * @return array Mapping header name to its value
875 public function getAllHeaders() {
876 $this->initHeaders();
877 return $this->headers
;
881 * Get a request header, or false if it isn't set
882 * @param string $name Case-insensitive header name
884 * @return string|bool False on failure
886 public function getHeader( $name ) {
887 $this->initHeaders();
888 $name = strtoupper( $name );
889 if ( isset( $this->headers
[$name] ) ) {
890 return $this->headers
[$name];
897 * Get data from $_SESSION
899 * @param string $key Name of key in $_SESSION
902 public function getSessionData( $key ) {
903 if ( !isset( $_SESSION[$key] ) ) {
906 return $_SESSION[$key];
912 * @param string $key Name of key in $_SESSION
915 public function setSessionData( $key, $data ) {
916 $_SESSION[$key] = $data;
920 * Check if Internet Explorer will detect an incorrect cache extension in
921 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
922 * message or redirect to a safer URL. Returns true if the URL is OK, and
923 * false if an error message has been shown and the request should be aborted.
925 * @param array $extWhitelist
929 public function checkUrlExtension( $extWhitelist = array() ) {
930 global $wgScriptExtension;
931 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
932 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
933 if ( !$this->wasPosted() ) {
934 $newUrl = IEUrlExtension
::fixUrlForIE6(
935 $this->getFullRequestURL(), $extWhitelist );
936 if ( $newUrl !== false ) {
937 $this->doSecurityRedirect( $newUrl );
941 throw new HttpError( 403,
942 'Invalid file extension found in the path info or query string.' );
948 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
949 * IE 6. Returns true if it was successful, false otherwise.
954 protected function doSecurityRedirect( $url ) {
955 header( 'Location: ' . $url );
956 header( 'Content-Type: text/html' );
957 $encUrl = htmlspecialchars( $url );
961 <title>Security redirect</title>
964 <h1>Security redirect</h1>
966 We can't serve non-HTML content from the URL you have requested
, because
967 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
969 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
970 URL you have requested
, except that
"&*" is appended
. This prevents Internet
971 Explorer from seeing a bogus file extension
.
981 * Parse the Accept-Language header sent by the client into an array
983 * @return array Array( languageCode => q-value ) sorted by q-value in
984 * descending order then appearing time in the header in ascending order.
985 * May contain the "language" '*', which applies to languages other than those explicitly listed.
986 * This is aligned with rfc2616 section 14.4
987 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
989 public function getAcceptLang() {
990 // Modified version of code found at
991 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
992 $acceptLang = $this->getHeader( 'Accept-Language' );
993 if ( !$acceptLang ) {
997 // Return the language codes in lower case
998 $acceptLang = strtolower( $acceptLang );
1000 // Break up string into pieces (languages and q factors)
1003 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1008 if ( !count( $lang_parse[1] ) ) {
1012 $langcodes = $lang_parse[1];
1013 $qvalues = $lang_parse[4];
1014 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1016 // Set default q factor to 1
1017 foreach ( $indices as $index ) {
1018 if ( $qvalues[$index] === '' ) {
1019 $qvalues[$index] = 1;
1020 } elseif ( $qvalues[$index] == 0 ) {
1021 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1025 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1026 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1028 // Create a list like "en" => 0.8
1029 $langs = array_combine( $langcodes, $qvalues );
1035 * Fetch the raw IP from the request
1039 * @throws MWException
1042 protected function getRawIP() {
1043 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1047 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1048 throw new MWException( __METHOD__
1049 . " : Could not determine the remote IP address due to multiple values." );
1051 $ipchain = $_SERVER['REMOTE_ADDR'];
1054 return IP
::canonicalize( $ipchain );
1058 * Work out the IP address based on various globals
1059 * For trusted proxies, use the XFF client IP (first of the chain)
1063 * @throws MWException
1066 public function getIP() {
1067 global $wgUsePrivateIPs;
1069 # Return cached result
1070 if ( $this->ip
!== null ) {
1074 # collect the originating ips
1075 $ip = $this->getRawIP();
1077 throw new MWException( 'Unable to determine IP.' );
1081 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1082 if ( $forwardedFor !== false ) {
1083 $isConfigured = IP
::isConfiguredProxy( $ip );
1084 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1085 $ipchain = array_reverse( $ipchain );
1086 array_unshift( $ipchain, $ip );
1088 # Step through XFF list and find the last address in the list which is a
1089 # trusted server. Set $ip to the IP address given by that trusted server,
1090 # unless the address is not sensible (e.g. private). However, prefer private
1091 # IP addresses over proxy servers controlled by this site (more sensible).
1092 # Note that some XFF values might be "unknown" with Squid/Varnish.
1093 foreach ( $ipchain as $i => $curIP ) {
1094 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1095 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1096 ||
!IP
::isTrustedProxy( $curIP )
1098 break; // IP is not valid/trusted or does not point to anything
1101 IP
::isPublic( $ipchain[$i +
1] ) ||
1103 IP
::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1105 // Follow the next IP according to the proxy
1106 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1107 if ( !$nextIP && $isConfigured ) {
1108 // We have not yet made it past CDN/proxy servers of this site,
1109 // so either they are misconfigured or there is some IP spoofing.
1110 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1113 // keep traversing the chain
1120 # Allow extensions to improve our guess
1121 wfRunHooks( 'GetIP', array( &$ip ) );
1124 throw new MWException( "Unable to determine IP." );
1127 wfDebug( "IP: $ip\n" );
1137 public function setIP( $ip ) {
1143 * Object to access the $_FILES array
1145 class WebRequestUpload
{
1147 protected $doesExist;
1148 protected $fileInfo;
1151 * Constructor. Should only be called by WebRequest
1153 * @param WebRequest $request The associated request
1154 * @param string $key Key in $_FILES array (name of form field)
1156 public function __construct( $request, $key ) {
1157 $this->request
= $request;
1158 $this->doesExist
= isset( $_FILES[$key] );
1159 if ( $this->doesExist
) {
1160 $this->fileInfo
= $_FILES[$key];
1165 * Return whether a file with this name was uploaded.
1169 public function exists() {
1170 return $this->doesExist
;
1174 * Return the original filename of the uploaded file
1176 * @return string|null Filename or null if non-existent
1178 public function getName() {
1179 if ( !$this->exists() ) {
1184 $name = $this->fileInfo
['name'];
1186 # Safari sends filenames in HTML-encoded Unicode form D...
1187 # Horrid and evil! Let's try to make some kind of sense of it.
1188 $name = Sanitizer
::decodeCharReferences( $name );
1189 $name = $wgContLang->normalize( $name );
1190 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1195 * Return the file size of the uploaded file
1197 * @return int File size or zero if non-existent
1199 public function getSize() {
1200 if ( !$this->exists() ) {
1204 return $this->fileInfo
['size'];
1208 * Return the path to the temporary file
1210 * @return string|null Path or null if non-existent
1212 public function getTempName() {
1213 if ( !$this->exists() ) {
1217 return $this->fileInfo
['tmp_name'];
1221 * Return the upload error. See link for explanation
1222 * http://www.php.net/manual/en/features.file-upload.errors.php
1224 * @return int One of the UPLOAD_ constants, 0 if non-existent
1226 public function getError() {
1227 if ( !$this->exists() ) {
1228 return 0; # UPLOAD_ERR_OK
1231 return $this->fileInfo
['error'];
1235 * Returns whether this upload failed because of overflow of a maximum set
1240 public function isIniSizeOverflow() {
1241 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1242 # PHP indicated that upload_max_filesize is exceeded
1246 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1247 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1248 # post_max_size is exceeded
1257 * WebRequest clone which takes values from a provided array.
1261 class FauxRequest
extends WebRequest
{
1262 private $wasPosted = false;
1263 private $session = array();
1266 * @param array $data Array of *non*-urlencoded key => value pairs, the
1267 * fake GET/POST values
1268 * @param bool $wasPosted Whether to treat the data as POST
1269 * @param array|null $session Session array or null
1270 * @param string $protocol 'http' or 'https'
1271 * @throws MWException
1273 public function __construct( $data = array(), $wasPosted = false,
1274 $session = null, $protocol = 'http'
1276 if ( is_array( $data ) ) {
1277 $this->data
= $data;
1279 throw new MWException( "FauxRequest() got bogus data" );
1281 $this->wasPosted
= $wasPosted;
1283 $this->session
= $session;
1285 $this->protocol
= $protocol;
1289 * @param string $method
1290 * @throws MWException
1292 private function notImplemented( $method ) {
1293 throw new MWException( "{$method}() not implemented" );
1297 * @param string $name
1298 * @param string $default
1301 public function getText( $name, $default = '' ) {
1302 # Override; don't recode since we're using internal data
1303 return (string)$this->getVal( $name, $default );
1309 public function getValues() {
1316 public function getQueryValues() {
1317 if ( $this->wasPosted
) {
1324 public function getMethod() {
1325 return $this->wasPosted ?
'POST' : 'GET';
1331 public function wasPosted() {
1332 return $this->wasPosted
;
1335 public function getCookie( $key, $prefix = null, $default = null ) {
1339 public function checkSessionCookie() {
1343 public function getRequestURL() {
1344 $this->notImplemented( __METHOD__
);
1347 public function getProtocol() {
1348 return $this->protocol
;
1352 * @param string $name The name of the header to get (case insensitive).
1353 * @return bool|string
1355 public function getHeader( $name ) {
1356 $name = strtoupper( $name );
1357 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1361 * @param string $name
1362 * @param string $val
1364 public function setHeader( $name, $val ) {
1365 $name = strtoupper( $name );
1366 $this->headers
[$name] = $val;
1370 * @param string $key
1371 * @return array|null
1373 public function getSessionData( $key ) {
1374 if ( isset( $this->session
[$key] ) ) {
1375 return $this->session
[$key];
1381 * @param string $key
1382 * @param array $data
1384 public function setSessionData( $key, $data ) {
1385 $this->session
[$key] = $data;
1389 * @return array|mixed|null
1391 public function getSessionArray() {
1392 return $this->session
;
1396 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1399 public function getRawQueryString() {
1404 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1407 public function getRawPostString() {
1412 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1415 public function getRawInput() {
1420 * @param array $extWhitelist
1423 public function checkUrlExtension( $extWhitelist = array() ) {
1430 protected function getRawIP() {
1436 * Similar to FauxRequest, but only fakes URL parameters and method
1437 * (POST or GET) and use the base request for the remaining stuff
1438 * (cookies, session and headers).
1443 class DerivativeRequest
extends FauxRequest
{
1447 * @param WebRequest $base
1448 * @param array $data Array of *non*-urlencoded key => value pairs, the
1449 * fake GET/POST values
1450 * @param bool $wasPosted Whether to treat the data as POST
1452 public function __construct( WebRequest
$base, $data, $wasPosted = false ) {
1453 $this->base
= $base;
1454 parent
::__construct( $data, $wasPosted );
1457 public function getCookie( $key, $prefix = null, $default = null ) {
1458 return $this->base
->getCookie( $key, $prefix, $default );
1461 public function checkSessionCookie() {
1462 return $this->base
->checkSessionCookie();
1465 public function getHeader( $name ) {
1466 return $this->base
->getHeader( $name );
1469 public function getAllHeaders() {
1470 return $this->base
->getAllHeaders();
1473 public function getSessionData( $key ) {
1474 return $this->base
->getSessionData( $key );
1477 public function setSessionData( $key, $data ) {
1478 $this->base
->setSessionData( $key, $data );
1481 public function getAcceptLang() {
1482 return $this->base
->getAcceptLang();
1485 public function getIP() {
1486 return $this->base
->getIP();
1489 public function getProtocol() {
1490 return $this->base
->getProtocol();