3 * Deal with importing all those nasssty globals and things
5 * Copyright © 2003 Brion Vibber <brion@pobox.com>
6 * http://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, handling remove of "magic quotes" slashes,
29 * stripping illegal input characters and 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
53 public function __construct() {
54 /// @todo FIXME: This preemptive de-quoting can interfere with other web libraries
55 /// and increases our memory footprint. It would be cleaner to do on
56 /// demand; but currently we have no wrapper for $_SERVER etc.
57 $this->checkMagicQuotes();
59 // POST overrides GET data
60 // We don't use $_REQUEST here to avoid interference from cookies...
61 $this->data
= $_POST +
$_GET;
65 * Extract relevant query arguments from the http request uri's path
66 * to be merged with the normal php provided query arguments.
67 * Tries to use the REQUEST_URI data if available and parses it
68 * according to the wiki's configuration looking for any known pattern.
70 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
71 * provided by the server if any and use that to set a 'title' parameter.
73 * @param $want string: If this is not 'all', then the function
74 * will return an empty array if it determines that the URL is
75 * inside a rewrite path.
77 * @return Array: Any query arguments found in path matches.
79 static public function getPathInfo( $want = 'all' ) {
80 global $wgUsePathInfo;
81 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
82 // And also by Apache 2.x, double slashes are converted to single slashes.
83 // So we will use REQUEST_URI if possible.
85 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
86 // Slurp out the path portion to examine...
87 $url = $_SERVER['REQUEST_URI'];
88 if ( !preg_match( '!^https?://!', $url ) ) {
89 $url = 'http://unused' . $url;
92 $a = parse_url( $url );
95 $path = isset( $a['path'] ) ?
$a['path'] : '';
98 if( $path == $wgScript && $want !== 'all' ) {
99 // Script inside a rewrite path?
100 // Abort to keep from breaking...
104 $router = new PathRouter
;
106 // Raw PATH_INFO style
107 $router->add( "$wgScript/$1" );
109 if( isset( $_SERVER['SCRIPT_NAME'] )
110 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] ) )
112 # Check for SCRIPT_NAME, we handle index.php explicitly
113 # But we do have some other .php files such as img_auth.php
114 # Don't let root article paths clober the parsing for them
115 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
118 global $wgArticlePath;
119 if( $wgArticlePath ) {
120 $router->add( $wgArticlePath );
123 global $wgActionPaths;
124 if( $wgActionPaths ) {
125 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
128 global $wgVariantArticlePath, $wgContLang;
129 if( $wgVariantArticlePath ) {
130 $router->add( $wgVariantArticlePath,
131 array( 'variant' => '$2'),
132 array( '$2' => $wgContLang->getVariants() )
136 wfRunHooks( 'WebRequestPathInfoRouter', array( $router ) );
138 $matches = $router->parse( $path );
140 } elseif ( $wgUsePathInfo ) {
141 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
143 // http://bugs.php.net/bug.php?id=31892
144 // Also reported when ini_get('cgi.fix_pathinfo')==false
145 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
147 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
148 // Regular old PATH_INFO yay
149 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
157 * Work out an appropriate URL prefix containing scheme and host, based on
158 * information detected from $_SERVER
162 public static function detectServer() {
163 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
165 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
168 foreach ( $varNames as $varName ) {
169 if ( !isset( $_SERVER[$varName] ) ) {
172 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
174 // Invalid, do not use
178 if ( $parts[1] === false ) {
179 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
180 $port = $_SERVER['SERVER_PORT'];
181 } // else leave it as $stdPort
188 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
194 public static function detectProtocolAndStdPort() {
195 return ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ?
array( 'https', 443 ) : array( 'http', 80 );
201 public static function detectProtocol() {
202 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
207 * Check for title, action, and/or variant data in the URL
208 * and interpolate it into the GET variables.
209 * This should only be run after $wgContLang is available,
210 * as we may need the list of language variants to determine
211 * available variant URLs.
213 public function interpolateTitle() {
214 // bug 16019: title interpolation on API queries is useless and sometimes harmful
215 if ( defined( 'MW_API' ) ) {
219 $matches = self
::getPathInfo( 'title' );
220 foreach( $matches as $key => $val) {
221 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
226 * URL rewriting function; tries to extract page title and,
227 * optionally, one other fixed parameter value from a URL path.
229 * @param $path string: the URL path given from the client
230 * @param $bases array: one or more URLs, optionally with $1 at the end
231 * @param $key string: if provided, the matching key in $bases will be
232 * passed on as the value of this URL parameter
233 * @return array of URL variables to interpolate; empty if no match
235 static function extractTitle( $path, $bases, $key = false ) {
236 foreach( (array)$bases as $keyValue => $base ) {
237 // Find the part after $wgArticlePath
238 $base = str_replace( '$1', '', $base );
239 $baseLen = strlen( $base );
240 if( substr( $path, 0, $baseLen ) == $base ) {
241 $raw = substr( $path, $baseLen );
243 $matches = array( 'title' => rawurldecode( $raw ) );
245 $matches[$key] = $keyValue;
255 * Recursively strips slashes from the given array;
256 * used for undoing the evil that is magic_quotes_gpc.
258 * @param $arr array: will be modified
259 * @param $topLevel bool Specifies if the array passed is from the top
260 * level of the source. In PHP5 magic_quotes only escapes the first level
261 * of keys that belong to an array.
262 * @return array the original array
263 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
265 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
267 foreach( $arr as $key => $val ) {
268 if( is_array( $val ) ) {
269 $cleanKey = $topLevel ?
stripslashes( $key ) : $key;
270 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
272 $cleanKey = stripslashes( $key );
273 $clean[$cleanKey] = stripslashes( $val );
281 * If magic_quotes_gpc option is on, run the global arrays
282 * through fix_magic_quotes to strip out the stupid slashes.
283 * WARNING: This should only be done once! Running a second
284 * time could damage the values.
286 private function checkMagicQuotes() {
287 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
288 && get_magic_quotes_gpc();
289 if( $mustFixQuotes ) {
290 $this->fix_magic_quotes( $_COOKIE );
291 $this->fix_magic_quotes( $_ENV );
292 $this->fix_magic_quotes( $_GET );
293 $this->fix_magic_quotes( $_POST );
294 $this->fix_magic_quotes( $_REQUEST );
295 $this->fix_magic_quotes( $_SERVER );
300 * Recursively normalizes UTF-8 strings in the given array.
302 * @param $data string|array
303 * @return array|string cleaned-up version of the given
306 function normalizeUnicode( $data ) {
307 if( is_array( $data ) ) {
308 foreach( $data as $key => $val ) {
309 $data[$key] = $this->normalizeUnicode( $val );
313 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
319 * Fetch a value from the given array or return $default if it's not set.
322 * @param $name String
323 * @param $default Mixed
326 private function getGPCVal( $arr, $name, $default ) {
327 # PHP is so nice to not touch input data, except sometimes:
328 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
329 # Work around PHP *feature* to avoid *bugs* elsewhere.
330 $name = strtr( $name, '.', '_' );
331 if( isset( $arr[$name] ) ) {
334 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
335 # Check for alternate/legacy character encoding.
336 if( isset( $wgContLang ) ) {
337 $data = $wgContLang->checkTitleEncoding( $data );
340 $data = $this->normalizeUnicode( $data );
349 * Fetch a scalar from the input or return $default if it's not set.
350 * Returns a string. Arrays are discarded. Useful for
351 * non-freeform text inputs (e.g. predefined internal text keys
352 * selected by a drop-down menu). For freeform input, see getText().
354 * @param $name String
355 * @param $default String: optional default (or NULL)
358 public function getVal( $name, $default = null ) {
359 $val = $this->getGPCVal( $this->data
, $name, $default );
360 if( is_array( $val ) ) {
363 if( is_null( $val ) ) {
371 * Set an arbitrary value into our get/post data.
373 * @param $key String: key name to use
374 * @param $value Mixed: value to set
375 * @return Mixed: old value if one was present, null otherwise
377 public function setVal( $key, $value ) {
378 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
379 $this->data
[$key] = $value;
385 * Unset an arbitrary value from our get/post data.
387 * @param $key String: key name to use
388 * @return Mixed: old value if one was present, null otherwise
390 public function unsetVal( $key ) {
391 if ( !isset( $this->data
[$key] ) ) {
394 $ret = $this->data
[$key];
395 unset( $this->data
[$key] );
401 * Fetch an array from the input or return $default if it's not set.
402 * If source was scalar, will return an array with a single element.
403 * If no source and no default, returns NULL.
405 * @param $name String
406 * @param $default Array: optional default (or NULL)
409 public function getArray( $name, $default = null ) {
410 $val = $this->getGPCVal( $this->data
, $name, $default );
411 if( is_null( $val ) ) {
419 * Fetch an array of integers, or return $default if it's not set.
420 * If source was scalar, will return an array with a single element.
421 * If no source and no default, returns NULL.
422 * If an array is returned, contents are guaranteed to be integers.
424 * @param $name String
425 * @param $default Array: option default (or NULL)
426 * @return Array of ints
428 public function getIntArray( $name, $default = null ) {
429 $val = $this->getArray( $name, $default );
430 if( is_array( $val ) ) {
431 $val = array_map( 'intval', $val );
437 * Fetch an integer value from the input or return $default if not set.
438 * Guaranteed to return an integer; non-numeric input will typically
441 * @param $name String
442 * @param $default Integer
445 public function getInt( $name, $default = 0 ) {
446 return intval( $this->getVal( $name, $default ) );
450 * Fetch an integer value from the input or return null if empty.
451 * Guaranteed to return an integer or null; non-numeric input will
452 * typically return null.
454 * @param $name String
457 public function getIntOrNull( $name ) {
458 $val = $this->getVal( $name );
459 return is_numeric( $val )
465 * Fetch a boolean value from the input or return $default if not set.
466 * Guaranteed to return true or false, with normal PHP semantics for
467 * boolean interpretation of strings.
469 * @param $name String
470 * @param $default Boolean
473 public function getBool( $name, $default = false ) {
474 return (bool)$this->getVal( $name, $default );
478 * Fetch a boolean value from the input or return $default if not set.
479 * Unlike getBool, the string "false" will result in boolean false, which is
480 * useful when interpreting information sent from JavaScript.
482 * @param $name String
483 * @param $default Boolean
486 public function getFuzzyBool( $name, $default = false ) {
487 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
491 * Return true if the named value is set in the input, whatever that
492 * value is (even "0"). Return false if the named value is not set.
493 * Example use is checking for the presence of check boxes in forms.
495 * @param $name String
498 public function getCheck( $name ) {
499 # Checkboxes and buttons are only present when clicked
500 # Presence connotes truth, abscense false
501 return $this->getVal( $name, null ) !== null;
505 * Fetch a text string from the given array or return $default if it's not
506 * set. Carriage returns are stripped from the text, and with some language
507 * modules there is an input transliteration applied. This should generally
508 * be used for form "<textarea>" and "<input>" fields. Used for
509 * user-supplied freeform text input (for which input transformations may
510 * be required - e.g. Esperanto x-coding).
512 * @param $name String
513 * @param $default String: optional
516 public function getText( $name, $default = '' ) {
518 $val = $this->getVal( $name, $default );
519 return str_replace( "\r\n", "\n",
520 $wgContLang->recodeInput( $val ) );
524 * Extracts the given named values into an array.
525 * If no arguments are given, returns all input values.
526 * No transformation is performed on the values.
530 public function getValues() {
531 $names = func_get_args();
532 if ( count( $names ) == 0 ) {
533 $names = array_keys( $this->data
);
537 foreach ( $names as $name ) {
538 $value = $this->getGPCVal( $this->data
, $name, null );
539 if ( !is_null( $value ) ) {
540 $retVal[$name] = $value;
547 * Returns the names of all input values excluding those in $exclude.
549 * @param $exclude Array
552 public function getValueNames( $exclude = array() ) {
553 return array_diff( array_keys( $this->getValues() ), $exclude );
557 * Get the values passed in the query string.
558 * No transformation is performed on the values.
562 public function getQueryValues() {
567 * Get the HTTP method used for this request.
571 public function getMethod() {
572 return isset( $_SERVER['REQUEST_METHOD'] ) ?
$_SERVER['REQUEST_METHOD'] : 'GET';
576 * Returns true if the present request was reached by a POST operation,
577 * false otherwise (GET, HEAD, or command-line).
579 * Note that values retrieved by the object may come from the
580 * GET URL etc even on a POST request.
584 public function wasPosted() {
585 return $this->getMethod() == 'POST';
589 * Returns true if there is a session cookie set.
590 * This does not necessarily mean that the user is logged in!
592 * If you want to check for an open session, use session_id()
593 * instead; that will also tell you if the session was opened
594 * during the current request (in which case the cookie will
595 * be sent back to the client at the end of the script run).
599 public function checkSessionCookie() {
600 return isset( $_COOKIE[ session_name() ] );
604 * Get a cookie from the $_COOKIE jar
606 * @param $key String: the name of the cookie
607 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
608 * @param $default Mixed: what to return if the value isn't found
609 * @return Mixed: cookie value or $default if the cookie not set
611 public function getCookie( $key, $prefix = null, $default = null ) {
612 if( $prefix === null ) {
613 global $wgCookiePrefix;
614 $prefix = $wgCookiePrefix;
616 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
620 * Return the path and query string portion of the request URI.
621 * This will be suitable for use as a relative link in HTML output.
623 * @throws MWException
626 public function getRequestURL() {
627 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
628 $base = $_SERVER['REQUEST_URI'];
629 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
630 // Probably IIS; doesn't set REQUEST_URI
631 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
632 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
633 $base = $_SERVER['SCRIPT_NAME'];
634 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
635 $base .= '?' . $_SERVER['QUERY_STRING'];
638 // This shouldn't happen!
639 throw new MWException( "Web server doesn't provide either " .
640 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
641 "of your web server configuration to http://bugzilla.wikimedia.org/" );
643 // User-agents should not send a fragment with the URI, but
644 // if they do, and the web server passes it on to us, we
645 // need to strip it or we get false-positive redirect loops
646 // or weird output URLs
647 $hash = strpos( $base, '#' );
648 if( $hash !== false ) {
649 $base = substr( $base, 0, $hash );
651 if( $base[0] == '/' ) {
654 // We may get paths with a host prepended; strip it.
655 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
660 * Return the request URI with the canonical service and hostname, path,
661 * and query string. This will be suitable for use as an absolute link
662 * in HTML or other output.
664 * If $wgServer is protocol-relative, this will return a fully
665 * qualified URL with the protocol that was used for this request.
669 public function getFullRequestURL() {
670 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
674 * Take an arbitrary query and rewrite the present URL to include it
675 * @param $query String: query string fragment; do not include initial '?'
679 public function appendQuery( $query ) {
680 return $this->appendQueryArray( wfCgiToArray( $query ) );
684 * HTML-safe version of appendQuery().
685 * @deprecated: Deprecated in 1.20, warnings in 1.21, remove in 1.22.
687 * @param $query String: query string fragment; do not include initial '?'
690 public function escapeAppendQuery( $query ) {
691 return htmlspecialchars( $this->appendQuery( $query ) );
697 * @param $onlyquery bool
700 public function appendQueryValue( $key, $value, $onlyquery = false ) {
701 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
705 * Appends or replaces value of query variables.
707 * @param $array Array of values to replace/add to query
708 * @param $onlyquery Bool: whether to only return the query string and not
712 public function appendQueryArray( $array, $onlyquery = false ) {
714 $newquery = $this->getQueryValues();
715 unset( $newquery['title'] );
716 $newquery = array_merge( $newquery, $array );
717 $query = wfArrayToCGI( $newquery );
718 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
722 * Check for limit and offset parameters on the input, and return sensible
723 * defaults if not given. The limit must be positive and is capped at 5000.
724 * Offset must be positive but is not capped.
726 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
727 * @param $optionname String: to specify an option other than rclimit to pull from.
728 * @return array first element is limit, second is offset
730 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
733 $limit = $this->getInt( 'limit', 0 );
737 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
738 $limit = (int)$wgUser->getOption( $optionname );
743 if( $limit > 5000 ) {
744 $limit = 5000; # We have *some* limits...
747 $offset = $this->getInt( 'offset', 0 );
752 return array( $limit, $offset );
756 * Return the path to the temporary file where PHP has stored the upload.
758 * @param $key String:
759 * @return string or NULL if no such file.
761 public function getFileTempname( $key ) {
762 $file = new WebRequestUpload( $this, $key );
763 return $file->getTempName();
767 * Return the size of the upload, or 0.
769 * @deprecated since 1.17
770 * @param $key String:
773 public function getFileSize( $key ) {
774 wfDeprecated( __METHOD__
, '1.17' );
775 $file = new WebRequestUpload( $this, $key );
776 return $file->getSize();
780 * Return the upload error or 0
782 * @param $key String:
785 public function getUploadError( $key ) {
786 $file = new WebRequestUpload( $this, $key );
787 return $file->getError();
791 * Return the original filename of the uploaded file, as reported by
792 * the submitting user agent. HTML-style character entities are
793 * interpreted and normalized to Unicode normalization form C, in part
794 * to deal with weird input from Safari with non-ASCII filenames.
796 * Other than this the name is not verified for being a safe filename.
798 * @param $key String:
799 * @return string or NULL if no such file.
801 public function getFileName( $key ) {
802 $file = new WebRequestUpload( $this, $key );
803 return $file->getName();
807 * Return a WebRequestUpload object corresponding to the key
810 * @return WebRequestUpload
812 public function getUpload( $key ) {
813 return new WebRequestUpload( $this, $key );
817 * Return a handle to WebResponse style object, for setting cookies,
818 * headers and other stuff, for Request being worked on.
820 * @return WebResponse
822 public function response() {
823 /* Lazy initialization of response object for this request */
824 if ( !is_object( $this->response
) ) {
825 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
826 $this->response
= new $class();
828 return $this->response
;
832 * Initialise the header list
834 private function initHeaders() {
835 if ( count( $this->headers
) ) {
839 if ( function_exists( 'apache_request_headers' ) ) {
840 foreach ( apache_request_headers() as $tempName => $tempValue ) {
841 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
844 foreach ( $_SERVER as $name => $value ) {
845 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
846 $name = str_replace( '_', '-', substr( $name, 5 ) );
847 $this->headers
[$name] = $value;
848 } elseif ( $name === 'CONTENT_LENGTH' ) {
849 $this->headers
['CONTENT-LENGTH'] = $value;
856 * Get an array containing all request headers
858 * @return Array mapping header name to its value
860 public function getAllHeaders() {
861 $this->initHeaders();
862 return $this->headers
;
866 * Get a request header, or false if it isn't set
867 * @param $name String: case-insensitive header name
869 * @return string|bool False on failure
871 public function getHeader( $name ) {
872 $this->initHeaders();
873 $name = strtoupper( $name );
874 if ( isset( $this->headers
[$name] ) ) {
875 return $this->headers
[$name];
882 * Get data from $_SESSION
884 * @param $key String: name of key in $_SESSION
887 public function getSessionData( $key ) {
888 if( !isset( $_SESSION[$key] ) ) {
891 return $_SESSION[$key];
897 * @param $key String: name of key in $_SESSION
900 public function setSessionData( $key, $data ) {
901 $_SESSION[$key] = $data;
905 * Check if Internet Explorer will detect an incorrect cache extension in
906 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
907 * message or redirect to a safer URL. Returns true if the URL is OK, and
908 * false if an error message has been shown and the request should be aborted.
910 * @param $extWhitelist array
914 public function checkUrlExtension( $extWhitelist = array() ) {
915 global $wgScriptExtension;
916 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
917 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
918 if ( !$this->wasPosted() ) {
919 $newUrl = IEUrlExtension
::fixUrlForIE6(
920 $this->getFullRequestURL(), $extWhitelist );
921 if ( $newUrl !== false ) {
922 $this->doSecurityRedirect( $newUrl );
926 throw new HttpError( 403,
927 'Invalid file extension found in the path info or query string.' );
933 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
934 * IE 6. Returns true if it was successful, false otherwise.
939 protected function doSecurityRedirect( $url ) {
940 header( 'Location: ' . $url );
941 header( 'Content-Type: text/html' );
942 $encUrl = htmlspecialchars( $url );
946 <title>Security redirect</title>
949 <h1>Security redirect</h1>
951 We can't serve non-HTML content from the URL you have requested
, because
952 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
954 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the URL you have requested
, except that
955 "&*" is appended
. This prevents Internet Explorer from seeing a bogus file
966 * Returns true if the PATH_INFO ends with an extension other than a script
967 * extension. This could confuse IE for scripts that send arbitrary data which
968 * is not HTML but may be detected as such.
970 * Various past attempts to use the URL to make this check have generally
971 * run up against the fact that CGI does not provide a standard method to
972 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
973 * but only by prefixing it with the script name and maybe some other stuff,
974 * the extension is not mangled. So this should be a reasonably portable
975 * way to perform this security check.
977 * Also checks for anything that looks like a file extension at the end of
978 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
979 * if there was no dot before the question mark (bug 28235).
981 * @deprecated Use checkUrlExtension().
983 * @param $extWhitelist array
987 public function isPathInfoBad( $extWhitelist = array() ) {
988 wfDeprecated( __METHOD__
, '1.17' );
989 global $wgScriptExtension;
990 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
991 return IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist );
995 * Parse the Accept-Language header sent by the client into an array
996 * @return array array( languageCode => q-value ) sorted by q-value in descending order then
997 * appearing time in the header in ascending order.
998 * May contain the "language" '*', which applies to languages other than those explicitly listed.
999 * This is aligned with rfc2616 section 14.4
1000 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1002 public function getAcceptLang() {
1003 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
1004 $acceptLang = $this->getHeader( 'Accept-Language' );
1005 if ( !$acceptLang ) {
1009 // Return the language codes in lower case
1010 $acceptLang = strtolower( $acceptLang );
1012 // Break up string into pieces (languages and q factors)
1014 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1015 $acceptLang, $lang_parse );
1017 if ( !count( $lang_parse[1] ) ) {
1021 $langcodes = $lang_parse[1];
1022 $qvalues = $lang_parse[4];
1023 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1025 // Set default q factor to 1
1026 foreach ( $indices as $index ) {
1027 if ( $qvalues[$index] === '' ) {
1028 $qvalues[$index] = 1;
1029 } elseif ( $qvalues[$index] == 0 ) {
1030 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1034 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1035 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1037 // Create a list like "en" => 0.8
1038 $langs = array_combine( $langcodes, $qvalues );
1044 * Fetch the raw IP from the request
1050 protected function getRawIP() {
1051 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1052 return IP
::canonicalize( $_SERVER['REMOTE_ADDR'] );
1059 * Work out the IP address based on various globals
1060 * For trusted proxies, use the XFF client IP (first of the chain)
1064 * @throws MWException
1067 public function getIP() {
1068 global $wgUsePrivateIPs;
1070 # Return cached result
1071 if ( $this->ip
!== null ) {
1075 # collect the originating ips
1076 $ip = $this->getRawIP();
1079 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1080 if ( $forwardedFor !== false ) {
1081 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1082 $ipchain = array_reverse( $ipchain );
1084 array_unshift( $ipchain, $ip );
1087 # Step through XFF list and find the last address in the list which is a trusted server
1088 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1089 foreach ( $ipchain as $i => $curIP ) {
1090 $curIP = IP
::canonicalize( $curIP );
1091 if ( wfIsTrustedProxy( $curIP ) ) {
1092 if ( isset( $ipchain[$i +
1] ) ) {
1093 if ( $wgUsePrivateIPs || IP
::isPublic( $ipchain[$i +
1 ] ) ) {
1094 $ip = $ipchain[$i +
1];
1103 # Allow extensions to improve our guess
1104 wfRunHooks( 'GetIP', array( &$ip ) );
1107 throw new MWException( "Unable to determine IP" );
1110 wfDebug( "IP: $ip\n" );
1117 * Object to access the $_FILES array
1119 class WebRequestUpload
{
1121 protected $doesExist;
1122 protected $fileInfo;
1125 * Constructor. Should only be called by WebRequest
1127 * @param $request WebRequest The associated request
1128 * @param $key string Key in $_FILES array (name of form field)
1130 public function __construct( $request, $key ) {
1131 $this->request
= $request;
1132 $this->doesExist
= isset( $_FILES[$key] );
1133 if ( $this->doesExist
) {
1134 $this->fileInfo
= $_FILES[$key];
1139 * Return whether a file with this name was uploaded.
1143 public function exists() {
1144 return $this->doesExist
;
1148 * Return the original filename of the uploaded file
1150 * @return mixed Filename or null if non-existent
1152 public function getName() {
1153 if ( !$this->exists() ) {
1158 $name = $this->fileInfo
['name'];
1160 # Safari sends filenames in HTML-encoded Unicode form D...
1161 # Horrid and evil! Let's try to make some kind of sense of it.
1162 $name = Sanitizer
::decodeCharReferences( $name );
1163 $name = $wgContLang->normalize( $name );
1164 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1169 * Return the file size of the uploaded file
1171 * @return int File size or zero if non-existent
1173 public function getSize() {
1174 if ( !$this->exists() ) {
1178 return $this->fileInfo
['size'];
1182 * Return the path to the temporary file
1184 * @return mixed Path or null if non-existent
1186 public function getTempName() {
1187 if ( !$this->exists() ) {
1191 return $this->fileInfo
['tmp_name'];
1195 * Return the upload error. See link for explanation
1196 * http://www.php.net/manual/en/features.file-upload.errors.php
1198 * @return int One of the UPLOAD_ constants, 0 if non-existent
1200 public function getError() {
1201 if ( !$this->exists() ) {
1202 return 0; # UPLOAD_ERR_OK
1205 return $this->fileInfo
['error'];
1209 * Returns whether this upload failed because of overflow of a maximum set
1214 public function isIniSizeOverflow() {
1215 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1216 # PHP indicated that upload_max_filesize is exceeded
1220 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1221 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1222 # post_max_size is exceeded
1231 * WebRequest clone which takes values from a provided array.
1235 class FauxRequest
extends WebRequest
{
1236 private $wasPosted = false;
1237 private $session = array();
1240 * @param $data Array of *non*-urlencoded key => value pairs, the
1241 * fake GET/POST values
1242 * @param $wasPosted Bool: whether to treat the data as POST
1243 * @param $session Mixed: session array or null
1244 * @throws MWException
1246 public function __construct( $data = array(), $wasPosted = false, $session = null ) {
1247 if( is_array( $data ) ) {
1248 $this->data
= $data;
1250 throw new MWException( "FauxRequest() got bogus data" );
1252 $this->wasPosted
= $wasPosted;
1254 $this->session
= $session;
1258 * @param $method string
1259 * @throws MWException
1261 private function notImplemented( $method ) {
1262 throw new MWException( "{$method}() not implemented" );
1266 * @param $name string
1267 * @param $default string
1270 public function getText( $name, $default = '' ) {
1271 # Override; don't recode since we're using internal data
1272 return (string)$this->getVal( $name, $default );
1278 public function getValues() {
1285 public function getQueryValues() {
1286 if ( $this->wasPosted
) {
1293 public function getMethod() {
1294 return $this->wasPosted ?
'POST' : 'GET';
1300 public function wasPosted() {
1301 return $this->wasPosted
;
1304 public function checkSessionCookie() {
1308 public function getRequestURL() {
1309 $this->notImplemented( __METHOD__
);
1314 * @return bool|string
1316 public function getHeader( $name ) {
1317 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1321 * @param $name string
1322 * @param $val string
1324 public function setHeader( $name, $val ) {
1325 $this->headers
[$name] = $val;
1332 public function getSessionData( $key ) {
1333 if( isset( $this->session
[$key] ) )
1334 return $this->session
[$key];
1341 public function setSessionData( $key, $data ) {
1342 $this->session
[$key] = $data;
1346 * @return array|Mixed|null
1348 public function getSessionArray() {
1349 return $this->session
;
1353 * @param array $extWhitelist
1356 public function isPathInfoBad( $extWhitelist = array() ) {
1361 * @param array $extWhitelist
1364 public function checkUrlExtension( $extWhitelist = array() ) {
1371 protected function getRawIP() {
1377 * Similar to FauxRequest, but only fakes URL parameters and method
1378 * (POST or GET) and use the base request for the remaining stuff
1379 * (cookies, session and headers).
1384 class DerivativeRequest
extends FauxRequest
{
1387 public function __construct( WebRequest
$base, $data, $wasPosted = false ) {
1388 $this->base
= $base;
1389 parent
::__construct( $data, $wasPosted );
1392 public function getCookie( $key, $prefix = null, $default = null ) {
1393 return $this->base
->getCookie( $key, $prefix, $default );
1396 public function checkSessionCookie() {
1397 return $this->base
->checkSessionCookie();
1400 public function getHeader( $name ) {
1401 return $this->base
->getHeader( $name );
1404 public function getAllHeaders() {
1405 return $this->base
->getAllHeaders();
1408 public function getSessionData( $key ) {
1409 return $this->base
->getSessionData( $key );
1412 public function setSessionData( $key, $data ) {
1413 $this->base
->setSessionData( $key, $data );
1416 public function getAcceptLang() {
1417 return $this->base
->getAcceptLang();
1420 public function getIP() {
1421 return $this->base
->getIP();