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 the PATH_INFO variable even when it isn't a reasonable
66 * value. On some large webhosts, PATH_INFO includes the script
67 * path as well as everything after it.
69 * @param $want string: If this is not 'all', then the function
70 * will return an empty array if it determines that the URL is
71 * inside a rewrite path.
73 * @return Array: 'title' key is the title of the article.
75 static public function getPathInfo( $want = 'all' ) {
76 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
77 // And also by Apache 2.x, double slashes are converted to single slashes.
78 // So we will use REQUEST_URI if possible.
80 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
81 // Slurp out the path portion to examine...
82 $url = $_SERVER['REQUEST_URI'];
83 if ( !preg_match( '!^https?://!', $url ) ) {
84 $url = 'http://unused' . $url;
86 $a = parse_url( $url );
88 $path = isset( $a['path'] ) ?
$a['path'] : '';
91 if( $path == $wgScript && $want !== 'all' ) {
92 // Script inside a rewrite path?
93 // Abort to keep from breaking...
97 $router = new PathRouter
;
99 // Raw PATH_INFO style
100 $router->add( "$wgScript/$1" );
102 if( isset( $_SERVER['SCRIPT_NAME'] )
103 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] ) )
105 # Check for SCRIPT_NAME, we handle index.php explicitly
106 # But we do have some other .php files such as img_auth.php
107 # Don't let root article paths clober the parsing for them
108 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
111 global $wgArticlePath;
112 if( $wgArticlePath ) {
113 $router->add( $wgArticlePath );
116 global $wgActionPaths;
117 if( $wgActionPaths ) {
118 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
121 global $wgVariantArticlePath, $wgContLang;
122 if( $wgVariantArticlePath ) {
123 /*$variantPaths = array();
124 foreach( $wgContLang->getVariants() as $variant ) {
125 $variantPaths[$variant] =
126 str_replace( '$2', $variant, $wgVariantArticlePath );
128 $router->add( $variantPaths, array( 'parameter' => 'variant' ) );*/
129 // Maybe actually this?
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 ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
142 // http://bugs.php.net/bug.php?id=31892
143 // Also reported when ini_get('cgi.fix_pathinfo')==false
144 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
146 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
147 // Regular old PATH_INFO yay
148 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
155 * Work out an appropriate URL prefix containing scheme and host, based on
156 * information detected from $_SERVER
160 public static function detectServer() {
161 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
163 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
166 foreach ( $varNames as $varName ) {
167 if ( !isset( $_SERVER[$varName] ) ) {
170 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
172 // Invalid, do not use
176 if ( $parts[1] === false ) {
177 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
178 $port = $_SERVER['SERVER_PORT'];
179 } // else leave it as $stdPort
186 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
192 public static function detectProtocolAndStdPort() {
193 return ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ?
array( 'https', 443 ) : array( 'http', 80 );
199 public static function detectProtocol() {
200 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
205 * Check for title, action, and/or variant data in the URL
206 * and interpolate it into the GET variables.
207 * This should only be run after $wgContLang is available,
208 * as we may need the list of language variants to determine
209 * available variant URLs.
211 public function interpolateTitle() {
212 global $wgUsePathInfo;
214 // bug 16019: title interpolation on API queries is useless and sometimes harmful
215 if ( defined( 'MW_API' ) ) {
219 if ( $wgUsePathInfo ) {
220 $matches = self
::getPathInfo( 'title' );
221 foreach( $matches as $key => $val) {
222 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
228 * URL rewriting function; tries to extract page title and,
229 * optionally, one other fixed parameter value from a URL path.
231 * @param $path string: the URL path given from the client
232 * @param $bases array: one or more URLs, optionally with $1 at the end
233 * @param $key string: if provided, the matching key in $bases will be
234 * passed on as the value of this URL parameter
235 * @return array of URL variables to interpolate; empty if no match
237 static function extractTitle( $path, $bases, $key = false ) {
238 foreach( (array)$bases as $keyValue => $base ) {
239 // Find the part after $wgArticlePath
240 $base = str_replace( '$1', '', $base );
241 $baseLen = strlen( $base );
242 if( substr( $path, 0, $baseLen ) == $base ) {
243 $raw = substr( $path, $baseLen );
245 $matches = array( 'title' => rawurldecode( $raw ) );
247 $matches[$key] = $keyValue;
257 * Recursively strips slashes from the given array;
258 * used for undoing the evil that is magic_quotes_gpc.
260 * @param $arr array: will be modified
261 * @param $topLevel bool Specifies if the array passed is from the top
262 * level of the source. In PHP5 magic_quotes only escapes the first level
263 * of keys that belong to an array.
264 * @return array the original array
265 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
267 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
269 foreach( $arr as $key => $val ) {
270 if( is_array( $val ) ) {
271 $cleanKey = $topLevel ?
stripslashes( $key ) : $key;
272 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
274 $cleanKey = stripslashes( $key );
275 $clean[$cleanKey] = stripslashes( $val );
283 * If magic_quotes_gpc option is on, run the global arrays
284 * through fix_magic_quotes to strip out the stupid slashes.
285 * WARNING: This should only be done once! Running a second
286 * time could damage the values.
288 private function checkMagicQuotes() {
289 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
290 && get_magic_quotes_gpc();
291 if( $mustFixQuotes ) {
292 $this->fix_magic_quotes( $_COOKIE );
293 $this->fix_magic_quotes( $_ENV );
294 $this->fix_magic_quotes( $_GET );
295 $this->fix_magic_quotes( $_POST );
296 $this->fix_magic_quotes( $_REQUEST );
297 $this->fix_magic_quotes( $_SERVER );
302 * Recursively normalizes UTF-8 strings in the given array.
304 * @param $data string or array
305 * @return cleaned-up version of the given
308 function normalizeUnicode( $data ) {
309 if( is_array( $data ) ) {
310 foreach( $data as $key => $val ) {
311 $data[$key] = $this->normalizeUnicode( $val );
315 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
321 * Fetch a value from the given array or return $default if it's not set.
324 * @param $name String
325 * @param $default Mixed
328 private function getGPCVal( $arr, $name, $default ) {
329 # PHP is so nice to not touch input data, except sometimes:
330 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
331 # Work around PHP *feature* to avoid *bugs* elsewhere.
332 $name = strtr( $name, '.', '_' );
333 if( isset( $arr[$name] ) ) {
336 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
337 # Check for alternate/legacy character encoding.
338 if( isset( $wgContLang ) ) {
339 $data = $wgContLang->checkTitleEncoding( $data );
342 $data = $this->normalizeUnicode( $data );
351 * Fetch a scalar from the input or return $default if it's not set.
352 * Returns a string. Arrays are discarded. Useful for
353 * non-freeform text inputs (e.g. predefined internal text keys
354 * selected by a drop-down menu). For freeform input, see getText().
356 * @param $name String
357 * @param $default String: optional default (or NULL)
360 public function getVal( $name, $default = null ) {
361 $val = $this->getGPCVal( $this->data
, $name, $default );
362 if( is_array( $val ) ) {
365 if( is_null( $val ) ) {
373 * Set an arbitrary value into our get/post data.
375 * @param $key String: key name to use
376 * @param $value Mixed: value to set
377 * @return Mixed: old value if one was present, null otherwise
379 public function setVal( $key, $value ) {
380 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
381 $this->data
[$key] = $value;
386 * Fetch an array from the input or return $default if it's not set.
387 * If source was scalar, will return an array with a single element.
388 * If no source and no default, returns NULL.
390 * @param $name String
391 * @param $default Array: optional default (or NULL)
394 public function getArray( $name, $default = null ) {
395 $val = $this->getGPCVal( $this->data
, $name, $default );
396 if( is_null( $val ) ) {
404 * Fetch an array of integers, or return $default if it's not set.
405 * If source was scalar, will return an array with a single element.
406 * If no source and no default, returns NULL.
407 * If an array is returned, contents are guaranteed to be integers.
409 * @param $name String
410 * @param $default Array: option default (or NULL)
411 * @return Array of ints
413 public function getIntArray( $name, $default = null ) {
414 $val = $this->getArray( $name, $default );
415 if( is_array( $val ) ) {
416 $val = array_map( 'intval', $val );
422 * Fetch an integer value from the input or return $default if not set.
423 * Guaranteed to return an integer; non-numeric input will typically
426 * @param $name String
427 * @param $default Integer
430 public function getInt( $name, $default = 0 ) {
431 return intval( $this->getVal( $name, $default ) );
435 * Fetch an integer value from the input or return null if empty.
436 * Guaranteed to return an integer or null; non-numeric input will
437 * typically return null.
439 * @param $name String
442 public function getIntOrNull( $name ) {
443 $val = $this->getVal( $name );
444 return is_numeric( $val )
450 * Fetch a boolean value from the input or return $default if not set.
451 * Guaranteed to return true or false, with normal PHP semantics for
452 * boolean interpretation of strings.
454 * @param $name String
455 * @param $default Boolean
458 public function getBool( $name, $default = false ) {
459 return (bool)$this->getVal( $name, $default );
463 * Fetch a boolean value from the input or return $default if not set.
464 * Unlike getBool, the string "false" will result in boolean false, which is
465 * useful when interpreting information sent from JavaScript.
467 * @param $name String
468 * @param $default Boolean
471 public function getFuzzyBool( $name, $default = false ) {
472 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
476 * Return true if the named value is set in the input, whatever that
477 * value is (even "0"). Return false if the named value is not set.
478 * Example use is checking for the presence of check boxes in forms.
480 * @param $name String
483 public function getCheck( $name ) {
484 # Checkboxes and buttons are only present when clicked
485 # Presence connotes truth, abscense false
486 $val = $this->getVal( $name, null );
487 return isset( $val );
491 * Fetch a text string from the given array or return $default if it's not
492 * set. Carriage returns are stripped from the text, and with some language
493 * modules there is an input transliteration applied. This should generally
494 * be used for form <textarea> and <input> fields. Used for user-supplied
495 * freeform text input (for which input transformations may be required - e.g.
496 * Esperanto x-coding).
498 * @param $name String
499 * @param $default String: optional
502 public function getText( $name, $default = '' ) {
504 $val = $this->getVal( $name, $default );
505 return str_replace( "\r\n", "\n",
506 $wgContLang->recodeInput( $val ) );
510 * Extracts the given named values into an array.
511 * If no arguments are given, returns all input values.
512 * No transformation is performed on the values.
516 public function getValues() {
517 $names = func_get_args();
518 if ( count( $names ) == 0 ) {
519 $names = array_keys( $this->data
);
523 foreach ( $names as $name ) {
524 $value = $this->getVal( $name );
525 if ( !is_null( $value ) ) {
526 $retVal[$name] = $value;
533 * Returns the names of all input values excluding those in $exclude.
535 * @param $exclude Array
538 public function getValueNames( $exclude = array() ) {
539 return array_diff( array_keys( $this->getValues() ), $exclude );
543 * Get the values passed in the query string.
544 * No transformation is performed on the values.
548 public function getQueryValues() {
553 * Returns true if the present request was reached by a POST operation,
554 * false otherwise (GET, HEAD, or command-line).
556 * Note that values retrieved by the object may come from the
557 * GET URL etc even on a POST request.
561 public function wasPosted() {
562 return isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] == 'POST';
566 * Returns true if there is a session cookie set.
567 * This does not necessarily mean that the user is logged in!
569 * If you want to check for an open session, use session_id()
570 * instead; that will also tell you if the session was opened
571 * during the current request (in which case the cookie will
572 * be sent back to the client at the end of the script run).
576 public function checkSessionCookie() {
577 return isset( $_COOKIE[ session_name() ] );
581 * Get a cookie from the $_COOKIE jar
583 * @param $key String: the name of the cookie
584 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
585 * @param $default Mixed: what to return if the value isn't found
586 * @return Mixed: cookie value or $default if the cookie not set
588 public function getCookie( $key, $prefix = null, $default = null ) {
589 if( $prefix === null ) {
590 global $wgCookiePrefix;
591 $prefix = $wgCookiePrefix;
593 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
597 * Return the path and query string portion of the request URI.
598 * This will be suitable for use as a relative link in HTML output.
602 public function getRequestURL() {
603 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
604 $base = $_SERVER['REQUEST_URI'];
605 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
606 // Probably IIS; doesn't set REQUEST_URI
607 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
608 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
609 $base = $_SERVER['SCRIPT_NAME'];
610 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
611 $base .= '?' . $_SERVER['QUERY_STRING'];
614 // This shouldn't happen!
615 throw new MWException( "Web server doesn't provide either " .
616 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
617 "of your web server configuration to http://bugzilla.wikimedia.org/" );
619 // User-agents should not send a fragment with the URI, but
620 // if they do, and the web server passes it on to us, we
621 // need to strip it or we get false-positive redirect loops
622 // or weird output URLs
623 $hash = strpos( $base, '#' );
624 if( $hash !== false ) {
625 $base = substr( $base, 0, $hash );
627 if( $base[0] == '/' ) {
630 // We may get paths with a host prepended; strip it.
631 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
636 * Return the request URI with the canonical service and hostname, path,
637 * and query string. This will be suitable for use as an absolute link
638 * in HTML or other output.
640 * If $wgServer is protocol-relative, this will return a fully
641 * qualified URL with the protocol that was used for this request.
645 public function getFullRequestURL() {
646 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
650 * Take an arbitrary query and rewrite the present URL to include it
651 * @param $query String: query string fragment; do not include initial '?'
655 public function appendQuery( $query ) {
656 return $this->appendQueryArray( wfCgiToArray( $query ) );
660 * HTML-safe version of appendQuery().
662 * @param $query String: query string fragment; do not include initial '?'
665 public function escapeAppendQuery( $query ) {
666 return htmlspecialchars( $this->appendQuery( $query ) );
672 * @param $onlyquery bool
675 public function appendQueryValue( $key, $value, $onlyquery = false ) {
676 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
680 * Appends or replaces value of query variables.
682 * @param $array Array of values to replace/add to query
683 * @param $onlyquery Bool: whether to only return the query string and not
687 public function appendQueryArray( $array, $onlyquery = false ) {
689 $newquery = $this->getQueryValues();
690 unset( $newquery['title'] );
691 $newquery = array_merge( $newquery, $array );
692 $query = wfArrayToCGI( $newquery );
693 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
697 * Check for limit and offset parameters on the input, and return sensible
698 * defaults if not given. The limit must be positive and is capped at 5000.
699 * Offset must be positive but is not capped.
701 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
702 * @param $optionname String: to specify an option other than rclimit to pull from.
703 * @return array first element is limit, second is offset
705 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
708 $limit = $this->getInt( 'limit', 0 );
712 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
713 $limit = (int)$wgUser->getOption( $optionname );
718 if( $limit > 5000 ) {
719 $limit = 5000; # We have *some* limits...
722 $offset = $this->getInt( 'offset', 0 );
727 return array( $limit, $offset );
731 * Return the path to the temporary file where PHP has stored the upload.
733 * @param $key String:
734 * @return string or NULL if no such file.
736 public function getFileTempname( $key ) {
737 $file = new WebRequestUpload( $this, $key );
738 return $file->getTempName();
742 * Return the size of the upload, or 0.
744 * @deprecated since 1.17
745 * @param $key String:
748 public function getFileSize( $key ) {
749 $file = new WebRequestUpload( $this, $key );
750 return $file->getSize();
754 * Return the upload error or 0
756 * @param $key String:
759 public function getUploadError( $key ) {
760 $file = new WebRequestUpload( $this, $key );
761 return $file->getError();
765 * Return the original filename of the uploaded file, as reported by
766 * the submitting user agent. HTML-style character entities are
767 * interpreted and normalized to Unicode normalization form C, in part
768 * to deal with weird input from Safari with non-ASCII filenames.
770 * Other than this the name is not verified for being a safe filename.
772 * @param $key String:
773 * @return string or NULL if no such file.
775 public function getFileName( $key ) {
776 $file = new WebRequestUpload( $this, $key );
777 return $file->getName();
781 * Return a WebRequestUpload object corresponding to the key
784 * @return WebRequestUpload
786 public function getUpload( $key ) {
787 return new WebRequestUpload( $this, $key );
791 * Return a handle to WebResponse style object, for setting cookies,
792 * headers and other stuff, for Request being worked on.
794 * @return WebResponse
796 public function response() {
797 /* Lazy initialization of response object for this request */
798 if ( !is_object( $this->response
) ) {
799 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
800 $this->response
= new $class();
802 return $this->response
;
806 * Initialise the header list
808 private function initHeaders() {
809 if ( count( $this->headers
) ) {
813 if ( function_exists( 'apache_request_headers' ) ) {
814 foreach ( apache_request_headers() as $tempName => $tempValue ) {
815 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
818 foreach ( $_SERVER as $name => $value ) {
819 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
820 $name = str_replace( '_', '-', substr( $name, 5 ) );
821 $this->headers
[$name] = $value;
822 } elseif ( $name === 'CONTENT_LENGTH' ) {
823 $this->headers
['CONTENT-LENGTH'] = $value;
830 * Get an array containing all request headers
832 * @return Array mapping header name to its value
834 public function getAllHeaders() {
835 $this->initHeaders();
836 return $this->headers
;
840 * Get a request header, or false if it isn't set
841 * @param $name String: case-insensitive header name
843 * @return string|false
845 public function getHeader( $name ) {
846 $this->initHeaders();
847 $name = strtoupper( $name );
848 if ( isset( $this->headers
[$name] ) ) {
849 return $this->headers
[$name];
856 * Get data from $_SESSION
858 * @param $key String: name of key in $_SESSION
861 public function getSessionData( $key ) {
862 if( !isset( $_SESSION[$key] ) ) {
865 return $_SESSION[$key];
871 * @param $key String: name of key in $_SESSION
874 public function setSessionData( $key, $data ) {
875 $_SESSION[$key] = $data;
879 * Check if Internet Explorer will detect an incorrect cache extension in
880 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
881 * message or redirect to a safer URL. Returns true if the URL is OK, and
882 * false if an error message has been shown and the request should be aborted.
884 * @param $extWhitelist array
887 public function checkUrlExtension( $extWhitelist = array() ) {
888 global $wgScriptExtension;
889 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
890 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
891 if ( !$this->wasPosted() ) {
892 $newUrl = IEUrlExtension
::fixUrlForIE6(
893 $this->getFullRequestURL(), $extWhitelist );
894 if ( $newUrl !== false ) {
895 $this->doSecurityRedirect( $newUrl );
899 throw new HttpError( 403,
900 'Invalid file extension found in the path info or query string.' );
906 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
907 * IE 6. Returns true if it was successful, false otherwise.
912 protected function doSecurityRedirect( $url ) {
913 header( 'Location: ' . $url );
914 header( 'Content-Type: text/html' );
915 $encUrl = htmlspecialchars( $url );
919 <title>Security redirect</title>
922 <h1>Security redirect</h1>
924 We can't serve non-HTML content from the URL you have requested
, because
925 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
927 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the URL you have requested
, except that
928 "&*" is appended
. This prevents Internet Explorer from seeing a bogus file
939 * Returns true if the PATH_INFO ends with an extension other than a script
940 * extension. This could confuse IE for scripts that send arbitrary data which
941 * is not HTML but may be detected as such.
943 * Various past attempts to use the URL to make this check have generally
944 * run up against the fact that CGI does not provide a standard method to
945 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
946 * but only by prefixing it with the script name and maybe some other stuff,
947 * the extension is not mangled. So this should be a reasonably portable
948 * way to perform this security check.
950 * Also checks for anything that looks like a file extension at the end of
951 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
952 * if there was no dot before the question mark (bug 28235).
954 * @deprecated Use checkUrlExtension().
956 * @param $extWhitelist array
960 public function isPathInfoBad( $extWhitelist = array() ) {
961 global $wgScriptExtension;
962 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
963 return IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist );
967 * Parse the Accept-Language header sent by the client into an array
968 * @return array array( languageCode => q-value ) sorted by q-value in descending order
969 * May contain the "language" '*', which applies to languages other than those explicitly listed.
970 * This is aligned with rfc2616 section 14.4
972 public function getAcceptLang() {
973 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
974 $acceptLang = $this->getHeader( 'Accept-Language' );
975 if ( !$acceptLang ) {
979 // Return the language codes in lower case
980 $acceptLang = strtolower( $acceptLang );
982 // Break up string into pieces (languages and q factors)
984 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})?)?)?/',
985 $acceptLang, $lang_parse );
987 if ( !count( $lang_parse[1] ) ) {
991 // Create a list like "en" => 0.8
992 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
993 // Set default q factor to 1
994 foreach ( $langs as $lang => $val ) {
997 } elseif ( $val == 0 ) {
998 unset($langs[$lang]);
1003 arsort( $langs, SORT_NUMERIC
);
1008 * Fetch the raw IP from the request
1012 protected function getRawIP() {
1013 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1014 return IP
::canonicalize( $_SERVER['REMOTE_ADDR'] );
1021 * Work out the IP address based on various globals
1022 * For trusted proxies, use the XFF client IP (first of the chain)
1025 public function getIP() {
1026 global $wgUsePrivateIPs;
1028 # Return cached result
1029 if ( $this->ip
!== null ) {
1033 # collect the originating ips
1034 $ip = $this->getRawIP();
1037 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1038 if ( $forwardedFor !== false ) {
1039 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1040 $ipchain = array_reverse( $ipchain );
1042 array_unshift( $ipchain, $ip );
1045 # Step through XFF list and find the last address in the list which is a trusted server
1046 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1047 foreach ( $ipchain as $i => $curIP ) {
1048 $curIP = IP
::canonicalize( $curIP );
1049 if ( wfIsTrustedProxy( $curIP ) ) {
1050 if ( isset( $ipchain[$i +
1] ) ) {
1051 if ( $wgUsePrivateIPs || IP
::isPublic( $ipchain[$i +
1 ] ) ) {
1052 $ip = $ipchain[$i +
1];
1061 # Allow extensions to improve our guess
1062 wfRunHooks( 'GetIP', array( &$ip ) );
1065 throw new MWException( "Unable to determine IP" );
1068 wfDebug( "IP: $ip\n" );
1075 * Object to access the $_FILES array
1077 class WebRequestUpload
{
1079 protected $doesExist;
1080 protected $fileInfo;
1083 * Constructor. Should only be called by WebRequest
1085 * @param $request WebRequest The associated request
1086 * @param $key string Key in $_FILES array (name of form field)
1088 public function __construct( $request, $key ) {
1089 $this->request
= $request;
1090 $this->doesExist
= isset( $_FILES[$key] );
1091 if ( $this->doesExist
) {
1092 $this->fileInfo
= $_FILES[$key];
1097 * Return whether a file with this name was uploaded.
1101 public function exists() {
1102 return $this->doesExist
;
1106 * Return the original filename of the uploaded file
1108 * @return mixed Filename or null if non-existent
1110 public function getName() {
1111 if ( !$this->exists() ) {
1116 $name = $this->fileInfo
['name'];
1118 # Safari sends filenames in HTML-encoded Unicode form D...
1119 # Horrid and evil! Let's try to make some kind of sense of it.
1120 $name = Sanitizer
::decodeCharReferences( $name );
1121 $name = $wgContLang->normalize( $name );
1122 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1127 * Return the file size of the uploaded file
1129 * @return int File size or zero if non-existent
1131 public function getSize() {
1132 if ( !$this->exists() ) {
1136 return $this->fileInfo
['size'];
1140 * Return the path to the temporary file
1142 * @return mixed Path or null if non-existent
1144 public function getTempName() {
1145 if ( !$this->exists() ) {
1149 return $this->fileInfo
['tmp_name'];
1153 * Return the upload error. See link for explanation
1154 * http://www.php.net/manual/en/features.file-upload.errors.php
1156 * @return int One of the UPLOAD_ constants, 0 if non-existent
1158 public function getError() {
1159 if ( !$this->exists() ) {
1160 return 0; # UPLOAD_ERR_OK
1163 return $this->fileInfo
['error'];
1167 * Returns whether this upload failed because of overflow of a maximum set
1172 public function isIniSizeOverflow() {
1173 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1174 # PHP indicated that upload_max_filesize is exceeded
1178 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1179 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1180 # post_max_size is exceeded
1189 * WebRequest clone which takes values from a provided array.
1193 class FauxRequest
extends WebRequest
{
1194 private $wasPosted = false;
1195 private $session = array();
1198 * @param $data Array of *non*-urlencoded key => value pairs, the
1199 * fake GET/POST values
1200 * @param $wasPosted Bool: whether to treat the data as POST
1201 * @param $session Mixed: session array or null
1203 public function __construct( $data, $wasPosted = false, $session = null ) {
1204 if( is_array( $data ) ) {
1205 $this->data
= $data;
1207 throw new MWException( "FauxRequest() got bogus data" );
1209 $this->wasPosted
= $wasPosted;
1211 $this->session
= $session;
1215 * @param $method string
1216 * @throws MWException
1218 private function notImplemented( $method ) {
1219 throw new MWException( "{$method}() not implemented" );
1223 * @param $name string
1224 * @param $default string
1227 public function getText( $name, $default = '' ) {
1228 # Override; don't recode since we're using internal data
1229 return (string)$this->getVal( $name, $default );
1235 public function getValues() {
1242 public function getQueryValues() {
1243 if ( $this->wasPosted
) {
1253 public function wasPosted() {
1254 return $this->wasPosted
;
1257 public function checkSessionCookie() {
1261 public function getRequestURL() {
1262 $this->notImplemented( __METHOD__
);
1267 * @return bool|string
1269 public function getHeader( $name ) {
1270 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1274 * @param $name string
1275 * @param $val string
1277 public function setHeader( $name, $val ) {
1278 $this->headers
[$name] = $val;
1285 public function getSessionData( $key ) {
1286 if( isset( $this->session
[$key] ) )
1287 return $this->session
[$key];
1294 public function setSessionData( $key, $data ) {
1295 $this->session
[$key] = $data;
1299 * @return array|Mixed|null
1301 public function getSessionArray() {
1302 return $this->session
;
1306 * @param array $extWhitelist
1309 public function isPathInfoBad( $extWhitelist = array() ) {
1314 * @param array $extWhitelist
1317 public function checkUrlExtension( $extWhitelist = array() ) {
1324 protected function getRawIP() {
1330 * Similar to FauxRequest, but only fakes URL parameters and method
1331 * (POST or GET) and use the base request for the remaining stuff
1332 * (cookies, session and headers).
1336 class DerivativeRequest
extends FauxRequest
{
1339 public function __construct( WebRequest
$base, $data, $wasPosted = false ) {
1340 $this->base
= $base;
1341 parent
::__construct( $data, $wasPosted );
1344 public function getCookie( $key, $prefix = null, $default = null ) {
1345 return $this->base
->getCookie( $key, $prefix, $default );
1348 public function checkSessionCookie() {
1349 return $this->base
->checkSessionCookie();
1352 public function getHeader( $name ) {
1353 return $this->base
->getHeader( $name );
1356 public function getAllHeaders() {
1357 return $this->base
->getAllHeaders();
1360 public function getSessionData( $key ) {
1361 return $this->base
->getSessionData( $key );
1364 public function setSessionData( $key, $data ) {
1365 return $this->base
->setSessionData( $key, $data );
1368 public function getAcceptLang() {
1369 return $this->base
->getAcceptLang();
1372 public function getIP() {
1373 return $this->base
->getIP();