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 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
81 // And also by Apache 2.x, double slashes are converted to single slashes.
82 // So we will use REQUEST_URI if possible.
84 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
85 // Slurp out the path portion to examine...
86 $url = $_SERVER['REQUEST_URI'];
87 if ( !preg_match( '!^https?://!', $url ) ) {
88 $url = 'http://unused' . $url;
90 $a = parse_url( $url );
92 $path = isset( $a['path'] ) ?
$a['path'] : '';
95 if( $path == $wgScript && $want !== 'all' ) {
96 // Script inside a rewrite path?
97 // Abort to keep from breaking...
101 $router = new PathRouter
;
103 // Raw PATH_INFO style
104 $router->add( "$wgScript/$1" );
106 if( isset( $_SERVER['SCRIPT_NAME'] )
107 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] ) )
109 # Check for SCRIPT_NAME, we handle index.php explicitly
110 # But we do have some other .php files such as img_auth.php
111 # Don't let root article paths clober the parsing for them
112 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
115 global $wgArticlePath;
116 if( $wgArticlePath ) {
117 $router->add( $wgArticlePath );
120 global $wgActionPaths;
121 if( $wgActionPaths ) {
122 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
125 global $wgVariantArticlePath, $wgContLang;
126 if( $wgVariantArticlePath ) {
127 $router->add( $wgVariantArticlePath,
128 array( 'variant' => '$2'),
129 array( '$2' => $wgContLang->getVariants() )
133 wfRunHooks( 'WebRequestPathInfoRouter', array( $router ) );
135 $matches = $router->parse( $path );
137 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
139 // http://bugs.php.net/bug.php?id=31892
140 // Also reported when ini_get('cgi.fix_pathinfo')==false
141 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
143 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
144 // Regular old PATH_INFO yay
145 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
152 * Work out an appropriate URL prefix containing scheme and host, based on
153 * information detected from $_SERVER
157 public static function detectServer() {
158 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
160 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
163 foreach ( $varNames as $varName ) {
164 if ( !isset( $_SERVER[$varName] ) ) {
167 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
169 // Invalid, do not use
173 if ( $parts[1] === false ) {
174 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
175 $port = $_SERVER['SERVER_PORT'];
176 } // else leave it as $stdPort
183 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
189 public static function detectProtocolAndStdPort() {
190 return ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ?
array( 'https', 443 ) : array( 'http', 80 );
196 public static function detectProtocol() {
197 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
202 * Check for title, action, and/or variant data in the URL
203 * and interpolate it into the GET variables.
204 * This should only be run after $wgContLang is available,
205 * as we may need the list of language variants to determine
206 * available variant URLs.
208 public function interpolateTitle() {
209 global $wgUsePathInfo;
211 // bug 16019: title interpolation on API queries is useless and sometimes harmful
212 if ( defined( 'MW_API' ) ) {
216 if ( $wgUsePathInfo ) {
217 $matches = self
::getPathInfo( 'title' );
218 foreach( $matches as $key => $val) {
219 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
225 * URL rewriting function; tries to extract page title and,
226 * optionally, one other fixed parameter value from a URL path.
228 * @param $path string: the URL path given from the client
229 * @param $bases array: one or more URLs, optionally with $1 at the end
230 * @param $key string: if provided, the matching key in $bases will be
231 * passed on as the value of this URL parameter
232 * @return array of URL variables to interpolate; empty if no match
234 static function extractTitle( $path, $bases, $key = false ) {
235 foreach( (array)$bases as $keyValue => $base ) {
236 // Find the part after $wgArticlePath
237 $base = str_replace( '$1', '', $base );
238 $baseLen = strlen( $base );
239 if( substr( $path, 0, $baseLen ) == $base ) {
240 $raw = substr( $path, $baseLen );
242 $matches = array( 'title' => rawurldecode( $raw ) );
244 $matches[$key] = $keyValue;
254 * Recursively strips slashes from the given array;
255 * used for undoing the evil that is magic_quotes_gpc.
257 * @param $arr array: will be modified
258 * @param $topLevel bool Specifies if the array passed is from the top
259 * level of the source. In PHP5 magic_quotes only escapes the first level
260 * of keys that belong to an array.
261 * @return array the original array
262 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
264 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
266 foreach( $arr as $key => $val ) {
267 if( is_array( $val ) ) {
268 $cleanKey = $topLevel ?
stripslashes( $key ) : $key;
269 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
271 $cleanKey = stripslashes( $key );
272 $clean[$cleanKey] = stripslashes( $val );
280 * If magic_quotes_gpc option is on, run the global arrays
281 * through fix_magic_quotes to strip out the stupid slashes.
282 * WARNING: This should only be done once! Running a second
283 * time could damage the values.
285 private function checkMagicQuotes() {
286 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
287 && get_magic_quotes_gpc();
288 if( $mustFixQuotes ) {
289 $this->fix_magic_quotes( $_COOKIE );
290 $this->fix_magic_quotes( $_ENV );
291 $this->fix_magic_quotes( $_GET );
292 $this->fix_magic_quotes( $_POST );
293 $this->fix_magic_quotes( $_REQUEST );
294 $this->fix_magic_quotes( $_SERVER );
299 * Recursively normalizes UTF-8 strings in the given array.
301 * @param $data string|array
302 * @return array|string cleaned-up version of the given
305 function normalizeUnicode( $data ) {
306 if( is_array( $data ) ) {
307 foreach( $data as $key => $val ) {
308 $data[$key] = $this->normalizeUnicode( $val );
312 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
318 * Fetch a value from the given array or return $default if it's not set.
321 * @param $name String
322 * @param $default Mixed
325 private function getGPCVal( $arr, $name, $default ) {
326 # PHP is so nice to not touch input data, except sometimes:
327 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
328 # Work around PHP *feature* to avoid *bugs* elsewhere.
329 $name = strtr( $name, '.', '_' );
330 if( isset( $arr[$name] ) ) {
333 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
334 # Check for alternate/legacy character encoding.
335 if( isset( $wgContLang ) ) {
336 $data = $wgContLang->checkTitleEncoding( $data );
339 $data = $this->normalizeUnicode( $data );
348 * Fetch a scalar from the input or return $default if it's not set.
349 * Returns a string. Arrays are discarded. Useful for
350 * non-freeform text inputs (e.g. predefined internal text keys
351 * selected by a drop-down menu). For freeform input, see getText().
353 * @param $name String
354 * @param $default String: optional default (or NULL)
357 public function getVal( $name, $default = null ) {
358 $val = $this->getGPCVal( $this->data
, $name, $default );
359 if( is_array( $val ) ) {
362 if( is_null( $val ) ) {
370 * Set an arbitrary value into our get/post data.
372 * @param $key String: key name to use
373 * @param $value Mixed: value to set
374 * @return Mixed: old value if one was present, null otherwise
376 public function setVal( $key, $value ) {
377 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
378 $this->data
[$key] = $value;
384 * Unset an arbitrary value from our get/post data.
386 * @param $key String: key name to use
387 * @return Mixed: old value if one was present, null otherwise
389 public function unsetVal( $key ) {
390 if ( !isset( $this->data
[$key] ) ) {
393 $ret = $this->data
[$key];
394 unset( $this->data
[$key] );
400 * Fetch an array from the input or return $default if it's not set.
401 * If source was scalar, will return an array with a single element.
402 * If no source and no default, returns NULL.
404 * @param $name String
405 * @param $default Array: optional default (or NULL)
408 public function getArray( $name, $default = null ) {
409 $val = $this->getGPCVal( $this->data
, $name, $default );
410 if( is_null( $val ) ) {
418 * Fetch an array of integers, or return $default if it's not set.
419 * If source was scalar, will return an array with a single element.
420 * If no source and no default, returns NULL.
421 * If an array is returned, contents are guaranteed to be integers.
423 * @param $name String
424 * @param $default Array: option default (or NULL)
425 * @return Array of ints
427 public function getIntArray( $name, $default = null ) {
428 $val = $this->getArray( $name, $default );
429 if( is_array( $val ) ) {
430 $val = array_map( 'intval', $val );
436 * Fetch an integer value from the input or return $default if not set.
437 * Guaranteed to return an integer; non-numeric input will typically
440 * @param $name String
441 * @param $default Integer
444 public function getInt( $name, $default = 0 ) {
445 return intval( $this->getVal( $name, $default ) );
449 * Fetch an integer value from the input or return null if empty.
450 * Guaranteed to return an integer or null; non-numeric input will
451 * typically return null.
453 * @param $name String
456 public function getIntOrNull( $name ) {
457 $val = $this->getVal( $name );
458 return is_numeric( $val )
464 * Fetch a boolean value from the input or return $default if not set.
465 * Guaranteed to return true or false, with normal PHP semantics for
466 * boolean interpretation of strings.
468 * @param $name String
469 * @param $default Boolean
472 public function getBool( $name, $default = false ) {
473 return (bool)$this->getVal( $name, $default );
477 * Fetch a boolean value from the input or return $default if not set.
478 * Unlike getBool, the string "false" will result in boolean false, which is
479 * useful when interpreting information sent from JavaScript.
481 * @param $name String
482 * @param $default Boolean
485 public function getFuzzyBool( $name, $default = false ) {
486 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
490 * Return true if the named value is set in the input, whatever that
491 * value is (even "0"). Return false if the named value is not set.
492 * Example use is checking for the presence of check boxes in forms.
494 * @param $name String
497 public function getCheck( $name ) {
498 # Checkboxes and buttons are only present when clicked
499 # Presence connotes truth, abscense false
500 $val = $this->getVal( $name, null );
501 return isset( $val );
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 user-supplied
509 * freeform text input (for which input transformations may be required - e.g.
510 * 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 * Returns true if the present request was reached by a POST operation,
568 * false otherwise (GET, HEAD, or command-line).
570 * Note that values retrieved by the object may come from the
571 * GET URL etc even on a POST request.
575 public function wasPosted() {
576 return isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] == 'POST';
580 * Returns true if there is a session cookie set.
581 * This does not necessarily mean that the user is logged in!
583 * If you want to check for an open session, use session_id()
584 * instead; that will also tell you if the session was opened
585 * during the current request (in which case the cookie will
586 * be sent back to the client at the end of the script run).
590 public function checkSessionCookie() {
591 return isset( $_COOKIE[ session_name() ] );
595 * Get a cookie from the $_COOKIE jar
597 * @param $key String: the name of the cookie
598 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
599 * @param $default Mixed: what to return if the value isn't found
600 * @return Mixed: cookie value or $default if the cookie not set
602 public function getCookie( $key, $prefix = null, $default = null ) {
603 if( $prefix === null ) {
604 global $wgCookiePrefix;
605 $prefix = $wgCookiePrefix;
607 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
611 * Return the path and query string portion of the request URI.
612 * This will be suitable for use as a relative link in HTML output.
616 public function getRequestURL() {
617 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
618 $base = $_SERVER['REQUEST_URI'];
619 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
620 // Probably IIS; doesn't set REQUEST_URI
621 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
622 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
623 $base = $_SERVER['SCRIPT_NAME'];
624 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
625 $base .= '?' . $_SERVER['QUERY_STRING'];
628 // This shouldn't happen!
629 throw new MWException( "Web server doesn't provide either " .
630 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
631 "of your web server configuration to http://bugzilla.wikimedia.org/" );
633 // User-agents should not send a fragment with the URI, but
634 // if they do, and the web server passes it on to us, we
635 // need to strip it or we get false-positive redirect loops
636 // or weird output URLs
637 $hash = strpos( $base, '#' );
638 if( $hash !== false ) {
639 $base = substr( $base, 0, $hash );
641 if( $base[0] == '/' ) {
644 // We may get paths with a host prepended; strip it.
645 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
650 * Return the request URI with the canonical service and hostname, path,
651 * and query string. This will be suitable for use as an absolute link
652 * in HTML or other output.
654 * If $wgServer is protocol-relative, this will return a fully
655 * qualified URL with the protocol that was used for this request.
659 public function getFullRequestURL() {
660 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
664 * Take an arbitrary query and rewrite the present URL to include it
665 * @param $query String: query string fragment; do not include initial '?'
669 public function appendQuery( $query ) {
670 return $this->appendQueryArray( wfCgiToArray( $query ) );
674 * HTML-safe version of appendQuery().
676 * @param $query String: query string fragment; do not include initial '?'
679 public function escapeAppendQuery( $query ) {
680 return htmlspecialchars( $this->appendQuery( $query ) );
686 * @param $onlyquery bool
689 public function appendQueryValue( $key, $value, $onlyquery = false ) {
690 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
694 * Appends or replaces value of query variables.
696 * @param $array Array of values to replace/add to query
697 * @param $onlyquery Bool: whether to only return the query string and not
701 public function appendQueryArray( $array, $onlyquery = false ) {
703 $newquery = $this->getQueryValues();
704 unset( $newquery['title'] );
705 $newquery = array_merge( $newquery, $array );
706 $query = wfArrayToCGI( $newquery );
707 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
711 * Check for limit and offset parameters on the input, and return sensible
712 * defaults if not given. The limit must be positive and is capped at 5000.
713 * Offset must be positive but is not capped.
715 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
716 * @param $optionname String: to specify an option other than rclimit to pull from.
717 * @return array first element is limit, second is offset
719 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
722 $limit = $this->getInt( 'limit', 0 );
726 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
727 $limit = (int)$wgUser->getOption( $optionname );
732 if( $limit > 5000 ) {
733 $limit = 5000; # We have *some* limits...
736 $offset = $this->getInt( 'offset', 0 );
741 return array( $limit, $offset );
745 * Return the path to the temporary file where PHP has stored the upload.
747 * @param $key String:
748 * @return string or NULL if no such file.
750 public function getFileTempname( $key ) {
751 $file = new WebRequestUpload( $this, $key );
752 return $file->getTempName();
756 * Return the size of the upload, or 0.
758 * @deprecated since 1.17
759 * @param $key String:
762 public function getFileSize( $key ) {
763 wfDeprecated( __METHOD__
, '1.17' );
764 $file = new WebRequestUpload( $this, $key );
765 return $file->getSize();
769 * Return the upload error or 0
771 * @param $key String:
774 public function getUploadError( $key ) {
775 $file = new WebRequestUpload( $this, $key );
776 return $file->getError();
780 * Return the original filename of the uploaded file, as reported by
781 * the submitting user agent. HTML-style character entities are
782 * interpreted and normalized to Unicode normalization form C, in part
783 * to deal with weird input from Safari with non-ASCII filenames.
785 * Other than this the name is not verified for being a safe filename.
787 * @param $key String:
788 * @return string or NULL if no such file.
790 public function getFileName( $key ) {
791 $file = new WebRequestUpload( $this, $key );
792 return $file->getName();
796 * Return a WebRequestUpload object corresponding to the key
799 * @return WebRequestUpload
801 public function getUpload( $key ) {
802 return new WebRequestUpload( $this, $key );
806 * Return a handle to WebResponse style object, for setting cookies,
807 * headers and other stuff, for Request being worked on.
809 * @return WebResponse
811 public function response() {
812 /* Lazy initialization of response object for this request */
813 if ( !is_object( $this->response
) ) {
814 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
815 $this->response
= new $class();
817 return $this->response
;
821 * Initialise the header list
823 private function initHeaders() {
824 if ( count( $this->headers
) ) {
828 if ( function_exists( 'apache_request_headers' ) ) {
829 foreach ( apache_request_headers() as $tempName => $tempValue ) {
830 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
833 foreach ( $_SERVER as $name => $value ) {
834 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
835 $name = str_replace( '_', '-', substr( $name, 5 ) );
836 $this->headers
[$name] = $value;
837 } elseif ( $name === 'CONTENT_LENGTH' ) {
838 $this->headers
['CONTENT-LENGTH'] = $value;
845 * Get an array containing all request headers
847 * @return Array mapping header name to its value
849 public function getAllHeaders() {
850 $this->initHeaders();
851 return $this->headers
;
855 * Get a request header, or false if it isn't set
856 * @param $name String: case-insensitive header name
858 * @return string|bool False on failure
860 public function getHeader( $name ) {
861 $this->initHeaders();
862 $name = strtoupper( $name );
863 if ( isset( $this->headers
[$name] ) ) {
864 return $this->headers
[$name];
871 * Get data from $_SESSION
873 * @param $key String: name of key in $_SESSION
876 public function getSessionData( $key ) {
877 if( !isset( $_SESSION[$key] ) ) {
880 return $_SESSION[$key];
886 * @param $key String: name of key in $_SESSION
889 public function setSessionData( $key, $data ) {
890 $_SESSION[$key] = $data;
894 * Check if Internet Explorer will detect an incorrect cache extension in
895 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
896 * message or redirect to a safer URL. Returns true if the URL is OK, and
897 * false if an error message has been shown and the request should be aborted.
899 * @param $extWhitelist array
902 public function checkUrlExtension( $extWhitelist = array() ) {
903 global $wgScriptExtension;
904 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
905 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
906 if ( !$this->wasPosted() ) {
907 $newUrl = IEUrlExtension
::fixUrlForIE6(
908 $this->getFullRequestURL(), $extWhitelist );
909 if ( $newUrl !== false ) {
910 $this->doSecurityRedirect( $newUrl );
914 throw new HttpError( 403,
915 'Invalid file extension found in the path info or query string.' );
921 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
922 * IE 6. Returns true if it was successful, false otherwise.
927 protected function doSecurityRedirect( $url ) {
928 header( 'Location: ' . $url );
929 header( 'Content-Type: text/html' );
930 $encUrl = htmlspecialchars( $url );
934 <title>Security redirect</title>
937 <h1>Security redirect</h1>
939 We can't serve non-HTML content from the URL you have requested
, because
940 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
942 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the URL you have requested
, except that
943 "&*" is appended
. This prevents Internet Explorer from seeing a bogus file
954 * Returns true if the PATH_INFO ends with an extension other than a script
955 * extension. This could confuse IE for scripts that send arbitrary data which
956 * is not HTML but may be detected as such.
958 * Various past attempts to use the URL to make this check have generally
959 * run up against the fact that CGI does not provide a standard method to
960 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
961 * but only by prefixing it with the script name and maybe some other stuff,
962 * the extension is not mangled. So this should be a reasonably portable
963 * way to perform this security check.
965 * Also checks for anything that looks like a file extension at the end of
966 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
967 * if there was no dot before the question mark (bug 28235).
969 * @deprecated Use checkUrlExtension().
971 * @param $extWhitelist array
975 public function isPathInfoBad( $extWhitelist = array() ) {
976 wfDeprecated( __METHOD__
, '1.17' );
977 global $wgScriptExtension;
978 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
979 return IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist );
983 * Parse the Accept-Language header sent by the client into an array
984 * @return array array( languageCode => q-value ) sorted by q-value in descending order
985 * May contain the "language" '*', which applies to languages other than those explicitly listed.
986 * This is aligned with rfc2616 section 14.4
988 public function getAcceptLang() {
989 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
990 $acceptLang = $this->getHeader( 'Accept-Language' );
991 if ( !$acceptLang ) {
995 // Return the language codes in lower case
996 $acceptLang = strtolower( $acceptLang );
998 // Break up string into pieces (languages and q factors)
1000 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})?)?)?/',
1001 $acceptLang, $lang_parse );
1003 if ( !count( $lang_parse[1] ) ) {
1007 // Create a list like "en" => 0.8
1008 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
1009 // Set default q factor to 1
1010 foreach ( $langs as $lang => $val ) {
1011 if ( $val === '' ) {
1013 } elseif ( $val == 0 ) {
1014 unset($langs[$lang]);
1019 arsort( $langs, SORT_NUMERIC
);
1024 * Fetch the raw IP from the request
1030 protected function getRawIP() {
1031 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1032 return IP
::canonicalize( $_SERVER['REMOTE_ADDR'] );
1039 * Work out the IP address based on various globals
1040 * For trusted proxies, use the XFF client IP (first of the chain)
1046 public function getIP() {
1047 global $wgUsePrivateIPs;
1049 # Return cached result
1050 if ( $this->ip
!== null ) {
1054 # collect the originating ips
1055 $ip = $this->getRawIP();
1058 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1059 if ( $forwardedFor !== false ) {
1060 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1061 $ipchain = array_reverse( $ipchain );
1063 array_unshift( $ipchain, $ip );
1066 # Step through XFF list and find the last address in the list which is a trusted server
1067 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1068 foreach ( $ipchain as $i => $curIP ) {
1069 $curIP = IP
::canonicalize( $curIP );
1070 if ( wfIsTrustedProxy( $curIP ) ) {
1071 if ( isset( $ipchain[$i +
1] ) ) {
1072 if ( $wgUsePrivateIPs || IP
::isPublic( $ipchain[$i +
1 ] ) ) {
1073 $ip = $ipchain[$i +
1];
1082 # Allow extensions to improve our guess
1083 wfRunHooks( 'GetIP', array( &$ip ) );
1086 throw new MWException( "Unable to determine IP" );
1089 wfDebug( "IP: $ip\n" );
1096 * Object to access the $_FILES array
1098 class WebRequestUpload
{
1100 protected $doesExist;
1101 protected $fileInfo;
1104 * Constructor. Should only be called by WebRequest
1106 * @param $request WebRequest The associated request
1107 * @param $key string Key in $_FILES array (name of form field)
1109 public function __construct( $request, $key ) {
1110 $this->request
= $request;
1111 $this->doesExist
= isset( $_FILES[$key] );
1112 if ( $this->doesExist
) {
1113 $this->fileInfo
= $_FILES[$key];
1118 * Return whether a file with this name was uploaded.
1122 public function exists() {
1123 return $this->doesExist
;
1127 * Return the original filename of the uploaded file
1129 * @return mixed Filename or null if non-existent
1131 public function getName() {
1132 if ( !$this->exists() ) {
1137 $name = $this->fileInfo
['name'];
1139 # Safari sends filenames in HTML-encoded Unicode form D...
1140 # Horrid and evil! Let's try to make some kind of sense of it.
1141 $name = Sanitizer
::decodeCharReferences( $name );
1142 $name = $wgContLang->normalize( $name );
1143 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1148 * Return the file size of the uploaded file
1150 * @return int File size or zero if non-existent
1152 public function getSize() {
1153 if ( !$this->exists() ) {
1157 return $this->fileInfo
['size'];
1161 * Return the path to the temporary file
1163 * @return mixed Path or null if non-existent
1165 public function getTempName() {
1166 if ( !$this->exists() ) {
1170 return $this->fileInfo
['tmp_name'];
1174 * Return the upload error. See link for explanation
1175 * http://www.php.net/manual/en/features.file-upload.errors.php
1177 * @return int One of the UPLOAD_ constants, 0 if non-existent
1179 public function getError() {
1180 if ( !$this->exists() ) {
1181 return 0; # UPLOAD_ERR_OK
1184 return $this->fileInfo
['error'];
1188 * Returns whether this upload failed because of overflow of a maximum set
1193 public function isIniSizeOverflow() {
1194 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1195 # PHP indicated that upload_max_filesize is exceeded
1199 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1200 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1201 # post_max_size is exceeded
1210 * WebRequest clone which takes values from a provided array.
1214 class FauxRequest
extends WebRequest
{
1215 private $wasPosted = false;
1216 private $session = array();
1219 * @param $data Array of *non*-urlencoded key => value pairs, the
1220 * fake GET/POST values
1221 * @param $wasPosted Bool: whether to treat the data as POST
1222 * @param $session Mixed: session array or null
1224 public function __construct( $data = array(), $wasPosted = false, $session = null ) {
1225 if( is_array( $data ) ) {
1226 $this->data
= $data;
1228 throw new MWException( "FauxRequest() got bogus data" );
1230 $this->wasPosted
= $wasPosted;
1232 $this->session
= $session;
1236 * @param $method string
1237 * @throws MWException
1239 private function notImplemented( $method ) {
1240 throw new MWException( "{$method}() not implemented" );
1244 * @param $name string
1245 * @param $default string
1248 public function getText( $name, $default = '' ) {
1249 # Override; don't recode since we're using internal data
1250 return (string)$this->getVal( $name, $default );
1256 public function getValues() {
1263 public function getQueryValues() {
1264 if ( $this->wasPosted
) {
1274 public function wasPosted() {
1275 return $this->wasPosted
;
1278 public function checkSessionCookie() {
1282 public function getRequestURL() {
1283 $this->notImplemented( __METHOD__
);
1288 * @return bool|string
1290 public function getHeader( $name ) {
1291 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1295 * @param $name string
1296 * @param $val string
1298 public function setHeader( $name, $val ) {
1299 $this->headers
[$name] = $val;
1306 public function getSessionData( $key ) {
1307 if( isset( $this->session
[$key] ) )
1308 return $this->session
[$key];
1315 public function setSessionData( $key, $data ) {
1316 $this->session
[$key] = $data;
1320 * @return array|Mixed|null
1322 public function getSessionArray() {
1323 return $this->session
;
1327 * @param array $extWhitelist
1330 public function isPathInfoBad( $extWhitelist = array() ) {
1335 * @param array $extWhitelist
1338 public function checkUrlExtension( $extWhitelist = array() ) {
1345 protected function getRawIP() {
1351 * Similar to FauxRequest, but only fakes URL parameters and method
1352 * (POST or GET) and use the base request for the remaining stuff
1353 * (cookies, session and headers).
1358 class DerivativeRequest
extends FauxRequest
{
1361 public function __construct( WebRequest
$base, $data, $wasPosted = false ) {
1362 $this->base
= $base;
1363 parent
::__construct( $data, $wasPosted );
1366 public function getCookie( $key, $prefix = null, $default = null ) {
1367 return $this->base
->getCookie( $key, $prefix, $default );
1370 public function checkSessionCookie() {
1371 return $this->base
->checkSessionCookie();
1374 public function getHeader( $name ) {
1375 return $this->base
->getHeader( $name );
1378 public function getAllHeaders() {
1379 return $this->base
->getAllHeaders();
1382 public function getSessionData( $key ) {
1383 return $this->base
->getSessionData( $key );
1386 public function setSessionData( $key, $data ) {
1387 return $this->base
->setSessionData( $key, $data );
1390 public function getAcceptLang() {
1391 return $this->base
->getAcceptLang();
1394 public function getIP() {
1395 return $this->base
->getIP();