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...
96 // Raw PATH_INFO style
97 $matches = self
::extractTitle( $path, "$wgScript/$1" );
99 global $wgArticlePath;
100 if( !$matches && $wgArticlePath ) {
101 $matches = self
::extractTitle( $path, $wgArticlePath );
104 global $wgActionPaths;
105 if( !$matches && $wgActionPaths ) {
106 $matches = self
::extractTitle( $path, $wgActionPaths, 'action' );
109 global $wgVariantArticlePath, $wgContLang;
110 if( !$matches && $wgVariantArticlePath ) {
111 $variantPaths = array();
112 foreach( $wgContLang->getVariants() as $variant ) {
113 $variantPaths[$variant] =
114 str_replace( '$2', $variant, $wgVariantArticlePath );
116 $matches = self
::extractTitle( $path, $variantPaths, 'variant' );
119 wfRunHooks( 'WebRequestGetPathInfoRequestURI', array( $path, &$matches ) );
121 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
123 // http://bugs.php.net/bug.php?id=31892
124 // Also reported when ini_get('cgi.fix_pathinfo')==false
125 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
127 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
128 // Regular old PATH_INFO yay
129 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
136 * Work out an appropriate URL prefix containing scheme and host, based on
137 * information detected from $_SERVER
141 public static function detectServer() {
142 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
144 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
147 foreach ( $varNames as $varName ) {
148 if ( !isset( $_SERVER[$varName] ) ) {
151 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
153 // Invalid, do not use
157 if ( $parts[1] === false ) {
158 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
159 $port = $_SERVER['SERVER_PORT'];
160 } // else leave it as $stdPort
167 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
173 public static function detectProtocolAndStdPort() {
174 return ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ?
array( 'https', 443 ) : array( 'http', 80 );
180 public static function detectProtocol() {
181 list( $proto, $stdPort ) = self
::detectProtocolAndStdPort();
186 * Check for title, action, and/or variant data in the URL
187 * and interpolate it into the GET variables.
188 * This should only be run after $wgContLang is available,
189 * as we may need the list of language variants to determine
190 * available variant URLs.
192 public function interpolateTitle() {
193 global $wgUsePathInfo;
195 // bug 16019: title interpolation on API queries is useless and sometimes harmful
196 if ( defined( 'MW_API' ) ) {
200 if ( $wgUsePathInfo ) {
201 $matches = self
::getPathInfo( 'title' );
202 foreach( $matches as $key => $val) {
203 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
209 * URL rewriting function; tries to extract page title and,
210 * optionally, one other fixed parameter value from a URL path.
212 * @param $path string: the URL path given from the client
213 * @param $bases array: one or more URLs, optionally with $1 at the end
214 * @param $key string: if provided, the matching key in $bases will be
215 * passed on as the value of this URL parameter
216 * @return array of URL variables to interpolate; empty if no match
218 static function extractTitle( $path, $bases, $key = false ) {
219 foreach( (array)$bases as $keyValue => $base ) {
220 // Find the part after $wgArticlePath
221 $base = str_replace( '$1', '', $base );
222 $baseLen = strlen( $base );
223 if( substr( $path, 0, $baseLen ) == $base ) {
224 $raw = substr( $path, $baseLen );
226 $matches = array( 'title' => rawurldecode( $raw ) );
228 $matches[$key] = $keyValue;
238 * Recursively strips slashes from the given array;
239 * used for undoing the evil that is magic_quotes_gpc.
241 * @param $arr array: will be modified
242 * @param $topLevel bool Specifies if the array passed is from the top
243 * level of the source. In PHP5 magic_quotes only escapes the first level
244 * of keys that belong to an array.
245 * @return array the original array
246 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
248 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
250 foreach( $arr as $key => $val ) {
251 if( is_array( $val ) ) {
252 $cleanKey = $topLevel ?
stripslashes( $key ) : $key;
253 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
255 $cleanKey = stripslashes( $key );
256 $clean[$cleanKey] = stripslashes( $val );
264 * If magic_quotes_gpc option is on, run the global arrays
265 * through fix_magic_quotes to strip out the stupid slashes.
266 * WARNING: This should only be done once! Running a second
267 * time could damage the values.
269 private function checkMagicQuotes() {
270 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
271 && get_magic_quotes_gpc();
272 if( $mustFixQuotes ) {
273 $this->fix_magic_quotes( $_COOKIE );
274 $this->fix_magic_quotes( $_ENV );
275 $this->fix_magic_quotes( $_GET );
276 $this->fix_magic_quotes( $_POST );
277 $this->fix_magic_quotes( $_REQUEST );
278 $this->fix_magic_quotes( $_SERVER );
283 * Recursively normalizes UTF-8 strings in the given array.
285 * @param $data string or array
286 * @return cleaned-up version of the given
289 function normalizeUnicode( $data ) {
290 if( is_array( $data ) ) {
291 foreach( $data as $key => $val ) {
292 $data[$key] = $this->normalizeUnicode( $val );
296 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
302 * Fetch a value from the given array or return $default if it's not set.
305 * @param $name String
306 * @param $default Mixed
309 private function getGPCVal( $arr, $name, $default ) {
310 # PHP is so nice to not touch input data, except sometimes:
311 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
312 # Work around PHP *feature* to avoid *bugs* elsewhere.
313 $name = strtr( $name, '.', '_' );
314 if( isset( $arr[$name] ) ) {
317 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
318 # Check for alternate/legacy character encoding.
319 if( isset( $wgContLang ) ) {
320 $data = $wgContLang->checkTitleEncoding( $data );
323 $data = $this->normalizeUnicode( $data );
332 * Fetch a scalar from the input or return $default if it's not set.
333 * Returns a string. Arrays are discarded. Useful for
334 * non-freeform text inputs (e.g. predefined internal text keys
335 * selected by a drop-down menu). For freeform input, see getText().
337 * @param $name String
338 * @param $default String: optional default (or NULL)
341 public function getVal( $name, $default = null ) {
342 $val = $this->getGPCVal( $this->data
, $name, $default );
343 if( is_array( $val ) ) {
346 if( is_null( $val ) ) {
354 * Set an arbitrary value into our get/post data.
356 * @param $key String: key name to use
357 * @param $value Mixed: value to set
358 * @return Mixed: old value if one was present, null otherwise
360 public function setVal( $key, $value ) {
361 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
362 $this->data
[$key] = $value;
367 * Fetch an array from the input or return $default if it's not set.
368 * If source was scalar, will return an array with a single element.
369 * If no source and no default, returns NULL.
371 * @param $name String
372 * @param $default Array: optional default (or NULL)
375 public function getArray( $name, $default = null ) {
376 $val = $this->getGPCVal( $this->data
, $name, $default );
377 if( is_null( $val ) ) {
385 * Fetch an array of integers, or return $default if it's not set.
386 * If source was scalar, will return an array with a single element.
387 * If no source and no default, returns NULL.
388 * If an array is returned, contents are guaranteed to be integers.
390 * @param $name String
391 * @param $default Array: option default (or NULL)
392 * @return Array of ints
394 public function getIntArray( $name, $default = null ) {
395 $val = $this->getArray( $name, $default );
396 if( is_array( $val ) ) {
397 $val = array_map( 'intval', $val );
403 * Fetch an integer value from the input or return $default if not set.
404 * Guaranteed to return an integer; non-numeric input will typically
407 * @param $name String
408 * @param $default Integer
411 public function getInt( $name, $default = 0 ) {
412 return intval( $this->getVal( $name, $default ) );
416 * Fetch an integer value from the input or return null if empty.
417 * Guaranteed to return an integer or null; non-numeric input will
418 * typically return null.
420 * @param $name String
423 public function getIntOrNull( $name ) {
424 $val = $this->getVal( $name );
425 return is_numeric( $val )
431 * Fetch a boolean value from the input or return $default if not set.
432 * Guaranteed to return true or false, with normal PHP semantics for
433 * boolean interpretation of strings.
435 * @param $name String
436 * @param $default Boolean
439 public function getBool( $name, $default = false ) {
440 return (bool)$this->getVal( $name, $default );
444 * Fetch a boolean value from the input or return $default if not set.
445 * Unlike getBool, the string "false" will result in boolean false, which is
446 * useful when interpreting information sent from JavaScript.
448 * @param $name String
449 * @param $default Boolean
452 public function getFuzzyBool( $name, $default = false ) {
453 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
457 * Return true if the named value is set in the input, whatever that
458 * value is (even "0"). Return false if the named value is not set.
459 * Example use is checking for the presence of check boxes in forms.
461 * @param $name String
464 public function getCheck( $name ) {
465 # Checkboxes and buttons are only present when clicked
466 # Presence connotes truth, abscense false
467 $val = $this->getVal( $name, null );
468 return isset( $val );
472 * Fetch a text string from the given array or return $default if it's not
473 * set. Carriage returns are stripped from the text, and with some language
474 * modules there is an input transliteration applied. This should generally
475 * be used for form <textarea> and <input> fields. Used for user-supplied
476 * freeform text input (for which input transformations may be required - e.g.
477 * Esperanto x-coding).
479 * @param $name String
480 * @param $default String: optional
483 public function getText( $name, $default = '' ) {
485 $val = $this->getVal( $name, $default );
486 return str_replace( "\r\n", "\n",
487 $wgContLang->recodeInput( $val ) );
491 * Extracts the given named values into an array.
492 * If no arguments are given, returns all input values.
493 * No transformation is performed on the values.
497 public function getValues() {
498 $names = func_get_args();
499 if ( count( $names ) == 0 ) {
500 $names = array_keys( $this->data
);
504 foreach ( $names as $name ) {
505 $value = $this->getVal( $name );
506 if ( !is_null( $value ) ) {
507 $retVal[$name] = $value;
514 * Returns the names of all input values excluding those in $exclude.
516 * @param $exclude Array
519 public function getValueNames( $exclude = array() ) {
520 return array_diff( array_keys( $this->getValues() ), $exclude );
524 * Get the values passed in the query string.
525 * No transformation is performed on the values.
529 public function getQueryValues() {
534 * Returns true if the present request was reached by a POST operation,
535 * false otherwise (GET, HEAD, or command-line).
537 * Note that values retrieved by the object may come from the
538 * GET URL etc even on a POST request.
542 public function wasPosted() {
543 return isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] == 'POST';
547 * Returns true if there is a session cookie set.
548 * This does not necessarily mean that the user is logged in!
550 * If you want to check for an open session, use session_id()
551 * instead; that will also tell you if the session was opened
552 * during the current request (in which case the cookie will
553 * be sent back to the client at the end of the script run).
557 public function checkSessionCookie() {
558 return isset( $_COOKIE[ session_name() ] );
562 * Get a cookie from the $_COOKIE jar
564 * @param $key String: the name of the cookie
565 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
566 * @param $default Mixed: what to return if the value isn't found
567 * @return Mixed: cookie value or $default if the cookie not set
569 public function getCookie( $key, $prefix = null, $default = null ) {
570 if( $prefix === null ) {
571 global $wgCookiePrefix;
572 $prefix = $wgCookiePrefix;
574 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
578 * Return the path and query string portion of the request URI.
579 * This will be suitable for use as a relative link in HTML output.
583 public function getRequestURL() {
584 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
585 $base = $_SERVER['REQUEST_URI'];
586 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
587 // Probably IIS; doesn't set REQUEST_URI
588 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
589 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
590 $base = $_SERVER['SCRIPT_NAME'];
591 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
592 $base .= '?' . $_SERVER['QUERY_STRING'];
595 // This shouldn't happen!
596 throw new MWException( "Web server doesn't provide either " .
597 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
598 "of your web server configuration to http://bugzilla.wikimedia.org/" );
600 // User-agents should not send a fragment with the URI, but
601 // if they do, and the web server passes it on to us, we
602 // need to strip it or we get false-positive redirect loops
603 // or weird output URLs
604 $hash = strpos( $base, '#' );
605 if( $hash !== false ) {
606 $base = substr( $base, 0, $hash );
608 if( $base[0] == '/' ) {
611 // We may get paths with a host prepended; strip it.
612 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
617 * Return the request URI with the canonical service and hostname, path,
618 * and query string. This will be suitable for use as an absolute link
619 * in HTML or other output.
621 * If $wgServer is protocol-relative, this will return a fully
622 * qualified URL with the protocol that was used for this request.
626 public function getFullRequestURL() {
627 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
631 * Take an arbitrary query and rewrite the present URL to include it
632 * @param $query String: query string fragment; do not include initial '?'
636 public function appendQuery( $query ) {
637 return $this->appendQueryArray( wfCgiToArray( $query ) );
641 * HTML-safe version of appendQuery().
643 * @param $query String: query string fragment; do not include initial '?'
646 public function escapeAppendQuery( $query ) {
647 return htmlspecialchars( $this->appendQuery( $query ) );
653 * @param $onlyquery bool
656 public function appendQueryValue( $key, $value, $onlyquery = false ) {
657 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
661 * Appends or replaces value of query variables.
663 * @param $array Array of values to replace/add to query
664 * @param $onlyquery Bool: whether to only return the query string and not
668 public function appendQueryArray( $array, $onlyquery = false ) {
670 $newquery = $this->getQueryValues();
671 unset( $newquery['title'] );
672 $newquery = array_merge( $newquery, $array );
673 $query = wfArrayToCGI( $newquery );
674 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
678 * Check for limit and offset parameters on the input, and return sensible
679 * defaults if not given. The limit must be positive and is capped at 5000.
680 * Offset must be positive but is not capped.
682 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
683 * @param $optionname String: to specify an option other than rclimit to pull from.
684 * @return array first element is limit, second is offset
686 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
689 $limit = $this->getInt( 'limit', 0 );
693 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
694 $limit = (int)$wgUser->getOption( $optionname );
699 if( $limit > 5000 ) {
700 $limit = 5000; # We have *some* limits...
703 $offset = $this->getInt( 'offset', 0 );
708 return array( $limit, $offset );
712 * Return the path to the temporary file where PHP has stored the upload.
714 * @param $key String:
715 * @return string or NULL if no such file.
717 public function getFileTempname( $key ) {
718 $file = new WebRequestUpload( $this, $key );
719 return $file->getTempName();
723 * Return the size of the upload, or 0.
725 * @deprecated since 1.17
726 * @param $key String:
729 public function getFileSize( $key ) {
730 $file = new WebRequestUpload( $this, $key );
731 return $file->getSize();
735 * Return the upload error or 0
737 * @param $key String:
740 public function getUploadError( $key ) {
741 $file = new WebRequestUpload( $this, $key );
742 return $file->getError();
746 * Return the original filename of the uploaded file, as reported by
747 * the submitting user agent. HTML-style character entities are
748 * interpreted and normalized to Unicode normalization form C, in part
749 * to deal with weird input from Safari with non-ASCII filenames.
751 * Other than this the name is not verified for being a safe filename.
753 * @param $key String:
754 * @return string or NULL if no such file.
756 public function getFileName( $key ) {
757 $file = new WebRequestUpload( $this, $key );
758 return $file->getName();
762 * Return a WebRequestUpload object corresponding to the key
765 * @return WebRequestUpload
767 public function getUpload( $key ) {
768 return new WebRequestUpload( $this, $key );
772 * Return a handle to WebResponse style object, for setting cookies,
773 * headers and other stuff, for Request being worked on.
775 * @return WebResponse
777 public function response() {
778 /* Lazy initialization of response object for this request */
779 if ( !is_object( $this->response
) ) {
780 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
781 $this->response
= new $class();
783 return $this->response
;
787 * Initialise the header list
789 private function initHeaders() {
790 if ( count( $this->headers
) ) {
794 if ( function_exists( 'apache_request_headers' ) ) {
795 foreach ( apache_request_headers() as $tempName => $tempValue ) {
796 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
799 foreach ( $_SERVER as $name => $value ) {
800 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
801 $name = str_replace( '_', '-', substr( $name, 5 ) );
802 $this->headers
[$name] = $value;
803 } elseif ( $name === 'CONTENT_LENGTH' ) {
804 $this->headers
['CONTENT-LENGTH'] = $value;
811 * Get an array containing all request headers
813 * @return Array mapping header name to its value
815 public function getAllHeaders() {
816 $this->initHeaders();
817 return $this->headers
;
821 * Get a request header, or false if it isn't set
822 * @param $name String: case-insensitive header name
824 * @return string|false
826 public function getHeader( $name ) {
827 $this->initHeaders();
828 $name = strtoupper( $name );
829 if ( isset( $this->headers
[$name] ) ) {
830 return $this->headers
[$name];
837 * Get data from $_SESSION
839 * @param $key String: name of key in $_SESSION
842 public function getSessionData( $key ) {
843 if( !isset( $_SESSION[$key] ) ) {
846 return $_SESSION[$key];
852 * @param $key String: name of key in $_SESSION
855 public function setSessionData( $key, $data ) {
856 $_SESSION[$key] = $data;
860 * Check if Internet Explorer will detect an incorrect cache extension in
861 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
862 * message or redirect to a safer URL. Returns true if the URL is OK, and
863 * false if an error message has been shown and the request should be aborted.
865 * @param $extWhitelist array
868 public function checkUrlExtension( $extWhitelist = array() ) {
869 global $wgScriptExtension;
870 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
871 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
872 if ( !$this->wasPosted() ) {
873 $newUrl = IEUrlExtension
::fixUrlForIE6(
874 $this->getFullRequestURL(), $extWhitelist );
875 if ( $newUrl !== false ) {
876 $this->doSecurityRedirect( $newUrl );
880 throw new HttpError( 403,
881 'Invalid file extension found in the path info or query string.' );
887 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
888 * IE 6. Returns true if it was successful, false otherwise.
893 protected function doSecurityRedirect( $url ) {
894 header( 'Location: ' . $url );
895 header( 'Content-Type: text/html' );
896 $encUrl = htmlspecialchars( $url );
900 <title>Security redirect</title>
903 <h1>Security redirect</h1>
905 We can't serve non-HTML content from the URL you have requested
, because
906 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
908 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the URL you have requested
, except that
909 "&*" is appended
. This prevents Internet Explorer from seeing a bogus file
920 * Returns true if the PATH_INFO ends with an extension other than a script
921 * extension. This could confuse IE for scripts that send arbitrary data which
922 * is not HTML but may be detected as such.
924 * Various past attempts to use the URL to make this check have generally
925 * run up against the fact that CGI does not provide a standard method to
926 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
927 * but only by prefixing it with the script name and maybe some other stuff,
928 * the extension is not mangled. So this should be a reasonably portable
929 * way to perform this security check.
931 * Also checks for anything that looks like a file extension at the end of
932 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
933 * if there was no dot before the question mark (bug 28235).
935 * @deprecated Use checkUrlExtension().
937 * @param $extWhitelist array
941 public function isPathInfoBad( $extWhitelist = array() ) {
942 global $wgScriptExtension;
943 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
944 return IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist );
948 * Parse the Accept-Language header sent by the client into an array
949 * @return array array( languageCode => q-value ) sorted by q-value in descending order
950 * May contain the "language" '*', which applies to languages other than those explicitly listed.
951 * This is aligned with rfc2616 section 14.4
953 public function getAcceptLang() {
954 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
955 $acceptLang = $this->getHeader( 'Accept-Language' );
956 if ( !$acceptLang ) {
960 // Return the language codes in lower case
961 $acceptLang = strtolower( $acceptLang );
963 // Break up string into pieces (languages and q factors)
965 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})?)?)?/',
966 $acceptLang, $lang_parse );
968 if ( !count( $lang_parse[1] ) ) {
972 // Create a list like "en" => 0.8
973 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
974 // Set default q factor to 1
975 foreach ( $langs as $lang => $val ) {
978 } elseif ( $val == 0 ) {
979 unset($langs[$lang]);
984 arsort( $langs, SORT_NUMERIC
);
989 * Fetch the raw IP from the request
993 protected function getRawIP() {
994 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
995 return IP
::canonicalize( $_SERVER['REMOTE_ADDR'] );
1002 * Work out the IP address based on various globals
1003 * For trusted proxies, use the XFF client IP (first of the chain)
1006 public function getIP() {
1007 global $wgUsePrivateIPs;
1009 # Return cached result
1010 if ( $this->ip
!== null ) {
1014 # collect the originating ips
1015 $ip = $this->getRawIP();
1018 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1019 if ( $forwardedFor !== false ) {
1020 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1021 $ipchain = array_reverse( $ipchain );
1023 array_unshift( $ipchain, $ip );
1026 # Step through XFF list and find the last address in the list which is a trusted server
1027 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1028 foreach ( $ipchain as $i => $curIP ) {
1029 $curIP = IP
::canonicalize( $curIP );
1030 if ( wfIsTrustedProxy( $curIP ) ) {
1031 if ( isset( $ipchain[$i +
1] ) ) {
1032 if ( $wgUsePrivateIPs || IP
::isPublic( $ipchain[$i +
1 ] ) ) {
1033 $ip = $ipchain[$i +
1];
1042 # Allow extensions to improve our guess
1043 wfRunHooks( 'GetIP', array( &$ip ) );
1046 throw new MWException( "Unable to determine IP" );
1049 wfDebug( "IP: $ip\n" );
1056 * Object to access the $_FILES array
1058 class WebRequestUpload
{
1060 protected $doesExist;
1061 protected $fileInfo;
1064 * Constructor. Should only be called by WebRequest
1066 * @param $request WebRequest The associated request
1067 * @param $key string Key in $_FILES array (name of form field)
1069 public function __construct( $request, $key ) {
1070 $this->request
= $request;
1071 $this->doesExist
= isset( $_FILES[$key] );
1072 if ( $this->doesExist
) {
1073 $this->fileInfo
= $_FILES[$key];
1078 * Return whether a file with this name was uploaded.
1082 public function exists() {
1083 return $this->doesExist
;
1087 * Return the original filename of the uploaded file
1089 * @return mixed Filename or null if non-existent
1091 public function getName() {
1092 if ( !$this->exists() ) {
1097 $name = $this->fileInfo
['name'];
1099 # Safari sends filenames in HTML-encoded Unicode form D...
1100 # Horrid and evil! Let's try to make some kind of sense of it.
1101 $name = Sanitizer
::decodeCharReferences( $name );
1102 $name = $wgContLang->normalize( $name );
1103 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1108 * Return the file size of the uploaded file
1110 * @return int File size or zero if non-existent
1112 public function getSize() {
1113 if ( !$this->exists() ) {
1117 return $this->fileInfo
['size'];
1121 * Return the path to the temporary file
1123 * @return mixed Path or null if non-existent
1125 public function getTempName() {
1126 if ( !$this->exists() ) {
1130 return $this->fileInfo
['tmp_name'];
1134 * Return the upload error. See link for explanation
1135 * http://www.php.net/manual/en/features.file-upload.errors.php
1137 * @return int One of the UPLOAD_ constants, 0 if non-existent
1139 public function getError() {
1140 if ( !$this->exists() ) {
1141 return 0; # UPLOAD_ERR_OK
1144 return $this->fileInfo
['error'];
1148 * Returns whether this upload failed because of overflow of a maximum set
1153 public function isIniSizeOverflow() {
1154 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1155 # PHP indicated that upload_max_filesize is exceeded
1159 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1160 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1161 # post_max_size is exceeded
1170 * WebRequest clone which takes values from a provided array.
1174 class FauxRequest
extends WebRequest
{
1175 private $wasPosted = false;
1176 private $session = array();
1179 * @param $data Array of *non*-urlencoded key => value pairs, the
1180 * fake GET/POST values
1181 * @param $wasPosted Bool: whether to treat the data as POST
1182 * @param $session Mixed: session array or null
1184 public function __construct( $data, $wasPosted = false, $session = null ) {
1185 if( is_array( $data ) ) {
1186 $this->data
= $data;
1188 throw new MWException( "FauxRequest() got bogus data" );
1190 $this->wasPosted
= $wasPosted;
1192 $this->session
= $session;
1196 * @param $method string
1197 * @throws MWException
1199 private function notImplemented( $method ) {
1200 throw new MWException( "{$method}() not implemented" );
1204 * @param $name string
1205 * @param $default string
1208 public function getText( $name, $default = '' ) {
1209 # Override; don't recode since we're using internal data
1210 return (string)$this->getVal( $name, $default );
1216 public function getValues() {
1223 public function getQueryValues() {
1224 if ( $this->wasPosted
) {
1234 public function wasPosted() {
1235 return $this->wasPosted
;
1238 public function checkSessionCookie() {
1242 public function getRequestURL() {
1243 $this->notImplemented( __METHOD__
);
1248 * @return bool|string
1250 public function getHeader( $name ) {
1251 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1255 * @param $name string
1256 * @param $val string
1258 public function setHeader( $name, $val ) {
1259 $this->headers
[$name] = $val;
1262 public function getSessionData( $key ) {
1263 if( isset( $this->session
[$key] ) )
1264 return $this->session
[$key];
1267 public function setSessionData( $key, $data ) {
1268 $this->session
[$key] = $data;
1271 public function getSessionArray() {
1272 return $this->session
;
1276 * @param array $extWhitelist
1279 public function isPathInfoBad( $extWhitelist = array() ) {
1284 * @param array $extWhitelist
1287 public function checkUrlExtension( $extWhitelist = array() ) {
1294 protected function getRawIP() {