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
47 public function __construct() {
48 /// @todo FIXME: This preemptive de-quoting can interfere with other web libraries
49 /// and increases our memory footprint. It would be cleaner to do on
50 /// demand; but currently we have no wrapper for $_SERVER etc.
51 $this->checkMagicQuotes();
53 // POST overrides GET data
54 // We don't use $_REQUEST here to avoid interference from cookies...
55 $this->data
= $_POST +
$_GET;
59 * Extract the PATH_INFO variable even when it isn't a reasonable
60 * value. On some large webhosts, PATH_INFO includes the script
61 * path as well as everything after it.
63 * @param $want string: If this is not 'all', then the function
64 * will return an empty array if it determines that the URL is
65 * inside a rewrite path.
67 * @return Array: 'title' key is the title of the article.
69 static public function getPathInfo( $want = 'all' ) {
70 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
71 // And also by Apache 2.x, double slashes are converted to single slashes.
72 // So we will use REQUEST_URI if possible.
74 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
75 // Slurp out the path portion to examine...
76 $url = $_SERVER['REQUEST_URI'];
77 if ( !preg_match( '!^https?://!', $url ) ) {
78 $url = 'http://unused' . $url;
80 $a = parse_url( $url );
82 $path = isset( $a['path'] ) ?
$a['path'] : '';
85 if( $path == $wgScript && $want !== 'all' ) {
86 // Script inside a rewrite path?
87 // Abort to keep from breaking...
90 // Raw PATH_INFO style
91 $matches = self
::extractTitle( $path, "$wgScript/$1" );
93 global $wgArticlePath;
94 if( !$matches && $wgArticlePath ) {
95 $matches = self
::extractTitle( $path, $wgArticlePath );
98 global $wgActionPaths;
99 if( !$matches && $wgActionPaths ) {
100 $matches = self
::extractTitle( $path, $wgActionPaths, 'action' );
103 global $wgVariantArticlePath, $wgContLang;
104 if( !$matches && $wgVariantArticlePath ) {
105 $variantPaths = array();
106 foreach( $wgContLang->getVariants() as $variant ) {
107 $variantPaths[$variant] =
108 str_replace( '$2', $variant, $wgVariantArticlePath );
110 $matches = self
::extractTitle( $path, $variantPaths, 'variant' );
113 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
115 // http://bugs.php.net/bug.php?id=31892
116 // Also reported when ini_get('cgi.fix_pathinfo')==false
117 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
119 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
120 // Regular old PATH_INFO yay
121 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
128 * Work out an appropriate URL prefix containing scheme and host, based on
129 * information detected from $_SERVER
133 public static function detectServer() {
134 if ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') {
142 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
145 foreach ( $varNames as $varName ) {
146 if ( !isset( $_SERVER[$varName] ) ) {
149 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
151 // Invalid, do not use
155 if ( $parts[1] === false ) {
156 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
157 $port = $_SERVER['SERVER_PORT'];
158 } // else leave it as $stdPort
165 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
169 * Check for title, action, and/or variant data in the URL
170 * and interpolate it into the GET variables.
171 * This should only be run after $wgContLang is available,
172 * as we may need the list of language variants to determine
173 * available variant URLs.
175 public function interpolateTitle() {
176 global $wgUsePathInfo;
178 // bug 16019: title interpolation on API queries is useless and sometimes harmful
179 if ( defined( 'MW_API' ) ) {
183 if ( $wgUsePathInfo ) {
184 $matches = self
::getPathInfo( 'title' );
185 foreach( $matches as $key => $val) {
186 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
192 * Internal URL rewriting function; tries to extract page title and,
193 * optionally, one other fixed parameter value from a URL path.
195 * @param $path string: the URL path given from the client
196 * @param $bases array: one or more URLs, optionally with $1 at the end
197 * @param $key string: if provided, the matching key in $bases will be
198 * passed on as the value of this URL parameter
199 * @return array of URL variables to interpolate; empty if no match
201 private static function extractTitle( $path, $bases, $key = false ) {
202 foreach( (array)$bases as $keyValue => $base ) {
203 // Find the part after $wgArticlePath
204 $base = str_replace( '$1', '', $base );
205 $baseLen = strlen( $base );
206 if( substr( $path, 0, $baseLen ) == $base ) {
207 $raw = substr( $path, $baseLen );
209 $matches = array( 'title' => rawurldecode( $raw ) );
211 $matches[$key] = $keyValue;
221 * Recursively strips slashes from the given array;
222 * used for undoing the evil that is magic_quotes_gpc.
224 * @param $arr array: will be modified
225 * @return array the original array
227 private function &fix_magic_quotes( &$arr ) {
228 foreach( $arr as $key => $val ) {
229 if( is_array( $val ) ) {
230 $this->fix_magic_quotes( $arr[$key] );
232 $arr[$key] = stripslashes( $val );
239 * If magic_quotes_gpc option is on, run the global arrays
240 * through fix_magic_quotes to strip out the stupid slashes.
241 * WARNING: This should only be done once! Running a second
242 * time could damage the values.
244 private function checkMagicQuotes() {
245 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
246 && get_magic_quotes_gpc();
247 if( $mustFixQuotes ) {
248 $this->fix_magic_quotes( $_COOKIE );
249 $this->fix_magic_quotes( $_ENV );
250 $this->fix_magic_quotes( $_GET );
251 $this->fix_magic_quotes( $_POST );
252 $this->fix_magic_quotes( $_REQUEST );
253 $this->fix_magic_quotes( $_SERVER );
258 * Recursively normalizes UTF-8 strings in the given array.
260 * @param $data string or array
261 * @return cleaned-up version of the given
264 function normalizeUnicode( $data ) {
265 if( is_array( $data ) ) {
266 foreach( $data as $key => $val ) {
267 $data[$key] = $this->normalizeUnicode( $val );
271 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
277 * Fetch a value from the given array or return $default if it's not set.
280 * @param $name String
281 * @param $default Mixed
284 private function getGPCVal( $arr, $name, $default ) {
285 # PHP is so nice to not touch input data, except sometimes:
286 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
287 # Work around PHP *feature* to avoid *bugs* elsewhere.
288 $name = strtr( $name, '.', '_' );
289 if( isset( $arr[$name] ) ) {
292 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
293 # Check for alternate/legacy character encoding.
294 if( isset( $wgContLang ) ) {
295 $data = $wgContLang->checkTitleEncoding( $data );
298 $data = $this->normalizeUnicode( $data );
307 * Fetch a scalar from the input or return $default if it's not set.
308 * Returns a string. Arrays are discarded. Useful for
309 * non-freeform text inputs (e.g. predefined internal text keys
310 * selected by a drop-down menu). For freeform input, see getText().
312 * @param $name String
313 * @param $default String: optional default (or NULL)
316 public function getVal( $name, $default = null ) {
317 $val = $this->getGPCVal( $this->data
, $name, $default );
318 if( is_array( $val ) ) {
321 if( is_null( $val ) ) {
329 * Set an arbitrary value into our get/post data.
331 * @param $key String: key name to use
332 * @param $value Mixed: value to set
333 * @return Mixed: old value if one was present, null otherwise
335 public function setVal( $key, $value ) {
336 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
337 $this->data
[$key] = $value;
342 * Fetch an array from the input or return $default if it's not set.
343 * If source was scalar, will return an array with a single element.
344 * If no source and no default, returns NULL.
346 * @param $name String
347 * @param $default Array: optional default (or NULL)
350 public function getArray( $name, $default = null ) {
351 $val = $this->getGPCVal( $this->data
, $name, $default );
352 if( is_null( $val ) ) {
360 * Fetch an array of integers, or return $default if it's not set.
361 * If source was scalar, will return an array with a single element.
362 * If no source and no default, returns NULL.
363 * If an array is returned, contents are guaranteed to be integers.
365 * @param $name String
366 * @param $default Array: option default (or NULL)
367 * @return Array of ints
369 public function getIntArray( $name, $default = null ) {
370 $val = $this->getArray( $name, $default );
371 if( is_array( $val ) ) {
372 $val = array_map( 'intval', $val );
378 * Fetch an integer value from the input or return $default if not set.
379 * Guaranteed to return an integer; non-numeric input will typically
382 * @param $name String
383 * @param $default Integer
386 public function getInt( $name, $default = 0 ) {
387 return intval( $this->getVal( $name, $default ) );
391 * Fetch an integer value from the input or return null if empty.
392 * Guaranteed to return an integer or null; non-numeric input will
393 * typically return null.
395 * @param $name String
398 public function getIntOrNull( $name ) {
399 $val = $this->getVal( $name );
400 return is_numeric( $val )
406 * Fetch a boolean value from the input or return $default if not set.
407 * Guaranteed to return true or false, with normal PHP semantics for
408 * boolean interpretation of strings.
410 * @param $name String
411 * @param $default Boolean
414 public function getBool( $name, $default = false ) {
415 return (bool)$this->getVal( $name, $default );
419 * Fetch a boolean value from the input or return $default if not set.
420 * Unlike getBool, the string "false" will result in boolean false, which is
421 * useful when interpreting information sent from JavaScript.
423 * @param $name String
424 * @param $default Boolean
427 public function getFuzzyBool( $name, $default = false ) {
428 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
432 * Return true if the named value is set in the input, whatever that
433 * value is (even "0"). Return false if the named value is not set.
434 * Example use is checking for the presence of check boxes in forms.
436 * @param $name String
439 public function getCheck( $name ) {
440 # Checkboxes and buttons are only present when clicked
441 # Presence connotes truth, abscense false
442 $val = $this->getVal( $name, null );
443 return isset( $val );
447 * Fetch a text string from the given array or return $default if it's not
448 * set. Carriage returns are stripped from the text, and with some language
449 * modules there is an input transliteration applied. This should generally
450 * be used for form <textarea> and <input> fields. Used for user-supplied
451 * freeform text input (for which input transformations may be required - e.g.
452 * Esperanto x-coding).
454 * @param $name String
455 * @param $default String: optional
458 public function getText( $name, $default = '' ) {
460 $val = $this->getVal( $name, $default );
461 return str_replace( "\r\n", "\n",
462 $wgContLang->recodeInput( $val ) );
466 * Extracts the given named values into an array.
467 * If no arguments are given, returns all input values.
468 * No transformation is performed on the values.
472 public function getValues() {
473 $names = func_get_args();
474 if ( count( $names ) == 0 ) {
475 $names = array_keys( $this->data
);
479 foreach ( $names as $name ) {
480 $value = $this->getVal( $name );
481 if ( !is_null( $value ) ) {
482 $retVal[$name] = $value;
489 * Get the values passed in the query string.
490 * No transformation is performed on the values.
494 public function getQueryValues() {
499 * Returns true if the present request was reached by a POST operation,
500 * false otherwise (GET, HEAD, or command-line).
502 * Note that values retrieved by the object may come from the
503 * GET URL etc even on a POST request.
507 public function wasPosted() {
508 return $_SERVER['REQUEST_METHOD'] == 'POST';
512 * Returns true if there is a session cookie set.
513 * This does not necessarily mean that the user is logged in!
515 * If you want to check for an open session, use session_id()
516 * instead; that will also tell you if the session was opened
517 * during the current request (in which case the cookie will
518 * be sent back to the client at the end of the script run).
522 public function checkSessionCookie() {
523 return isset( $_COOKIE[ session_name() ] );
527 * Get a cookie from the $_COOKIE jar
529 * @param $key String: the name of the cookie
530 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
531 * @param $default Mixed: what to return if the value isn't found
532 * @return Mixed: cookie value or $default if the cookie not set
534 public function getCookie( $key, $prefix = null, $default = null ) {
535 if( $prefix === null ) {
536 global $wgCookiePrefix;
537 $prefix = $wgCookiePrefix;
539 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
543 * Return the path and query string portion of the request URI.
544 * This will be suitable for use as a relative link in HTML output.
548 public function getRequestURL() {
549 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
550 $base = $_SERVER['REQUEST_URI'];
551 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
552 // Probably IIS; doesn't set REQUEST_URI
553 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
554 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
555 $base = $_SERVER['SCRIPT_NAME'];
556 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
557 $base .= '?' . $_SERVER['QUERY_STRING'];
560 // This shouldn't happen!
561 throw new MWException( "Web server doesn't provide either " .
562 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
563 "of your web server configuration to http://bugzilla.wikimedia.org/" );
565 // User-agents should not send a fragment with the URI, but
566 // if they do, and the web server passes it on to us, we
567 // need to strip it or we get false-positive redirect loops
568 // or weird output URLs
569 $hash = strpos( $base, '#' );
570 if( $hash !== false ) {
571 $base = substr( $base, 0, $hash );
573 if( $base[0] == '/' ) {
576 // We may get paths with a host prepended; strip it.
577 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
582 * Return the request URI with the canonical service and hostname, path,
583 * and query string. This will be suitable for use as an absolute link
584 * in HTML or other output.
588 public function getFullRequestURL() {
590 return $wgServer . $this->getRequestURL();
594 * Take an arbitrary query and rewrite the present URL to include it
595 * @param $query String: query string fragment; do not include initial '?'
599 public function appendQuery( $query ) {
600 return $this->appendQueryArray( wfCgiToArray( $query ) );
604 * HTML-safe version of appendQuery().
606 * @param $query String: query string fragment; do not include initial '?'
609 public function escapeAppendQuery( $query ) {
610 return htmlspecialchars( $this->appendQuery( $query ) );
616 * @param $onlyquery bool
619 public function appendQueryValue( $key, $value, $onlyquery = false ) {
620 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
624 * Appends or replaces value of query variables.
626 * @param $array Array of values to replace/add to query
627 * @param $onlyquery Bool: whether to only return the query string and not
631 public function appendQueryArray( $array, $onlyquery = false ) {
633 $newquery = $this->getQueryValues();
634 unset( $newquery['title'] );
635 $newquery = array_merge( $newquery, $array );
636 $query = wfArrayToCGI( $newquery );
637 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
641 * Check for limit and offset parameters on the input, and return sensible
642 * defaults if not given. The limit must be positive and is capped at 5000.
643 * Offset must be positive but is not capped.
645 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
646 * @param $optionname String: to specify an option other than rclimit to pull from.
647 * @return array first element is limit, second is offset
649 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
652 $limit = $this->getInt( 'limit', 0 );
656 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
657 $limit = (int)$wgUser->getOption( $optionname );
662 if( $limit > 5000 ) {
663 $limit = 5000; # We have *some* limits...
666 $offset = $this->getInt( 'offset', 0 );
671 return array( $limit, $offset );
675 * Return the path to the temporary file where PHP has stored the upload.
677 * @param $key String:
678 * @return string or NULL if no such file.
680 public function getFileTempname( $key ) {
681 $file = new WebRequestUpload( $this, $key );
682 return $file->getTempName();
686 * Return the size of the upload, or 0.
688 * @deprecated since 1.17
689 * @param $key String:
692 public function getFileSize( $key ) {
693 $file = new WebRequestUpload( $this, $key );
694 return $file->getSize();
698 * Return the upload error or 0
700 * @param $key String:
703 public function getUploadError( $key ) {
704 $file = new WebRequestUpload( $this, $key );
705 return $file->getError();
709 * Return the original filename of the uploaded file, as reported by
710 * the submitting user agent. HTML-style character entities are
711 * interpreted and normalized to Unicode normalization form C, in part
712 * to deal with weird input from Safari with non-ASCII filenames.
714 * Other than this the name is not verified for being a safe filename.
716 * @param $key String:
717 * @return string or NULL if no such file.
719 public function getFileName( $key ) {
720 $file = new WebRequestUpload( $this, $key );
721 return $file->getName();
725 * Return a WebRequestUpload object corresponding to the key
728 * @return WebRequestUpload
730 public function getUpload( $key ) {
731 return new WebRequestUpload( $this, $key );
735 * Return a handle to WebResponse style object, for setting cookies,
736 * headers and other stuff, for Request being worked on.
738 * @return WebResponse
740 public function response() {
741 /* Lazy initialization of response object for this request */
742 if ( !is_object( $this->response
) ) {
743 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
744 $this->response
= new $class();
746 return $this->response
;
750 * Initialise the header list
752 private function initHeaders() {
753 if ( count( $this->headers
) ) {
757 if ( function_exists( 'apache_request_headers' ) ) {
758 foreach ( apache_request_headers() as $tempName => $tempValue ) {
759 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
762 foreach ( $_SERVER as $name => $value ) {
763 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
764 $name = str_replace( '_', '-', substr( $name, 5 ) );
765 $this->headers
[$name] = $value;
766 } elseif ( $name === 'CONTENT_LENGTH' ) {
767 $this->headers
['CONTENT-LENGTH'] = $value;
774 * Get an array containing all request headers
776 * @return Array mapping header name to its value
778 public function getAllHeaders() {
779 $this->initHeaders();
780 return $this->headers
;
784 * Get a request header, or false if it isn't set
785 * @param $name String: case-insensitive header name
787 * @return string|false
789 public function getHeader( $name ) {
790 $this->initHeaders();
791 $name = strtoupper( $name );
792 if ( isset( $this->headers
[$name] ) ) {
793 return $this->headers
[$name];
800 * Get data from $_SESSION
802 * @param $key String: name of key in $_SESSION
805 public function getSessionData( $key ) {
806 if( !isset( $_SESSION[$key] ) ) {
809 return $_SESSION[$key];
815 * @param $key String: name of key in $_SESSION
818 public function setSessionData( $key, $data ) {
819 $_SESSION[$key] = $data;
823 * Check if Internet Explorer will detect an incorrect cache extension in
824 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
825 * message or redirect to a safer URL. Returns true if the URL is OK, and
826 * false if an error message has been shown and the request should be aborted.
828 * @param $extWhitelist array
831 public function checkUrlExtension( $extWhitelist = array() ) {
832 global $wgScriptExtension;
833 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
834 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
835 if ( !$this->wasPosted() ) {
836 $newUrl = IEUrlExtension
::fixUrlForIE6(
837 $this->getFullRequestURL(), $extWhitelist );
838 if ( $newUrl !== false ) {
839 $this->doSecurityRedirect( $newUrl );
843 wfHttpError( 403, 'Forbidden',
844 'Invalid file extension found in the path info or query string.' );
852 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
853 * IE 6. Returns true if it was successful, false otherwise.
858 protected function doSecurityRedirect( $url ) {
859 header( 'Location: ' . $url );
860 header( 'Content-Type: text/html' );
861 $encUrl = htmlspecialchars( $url );
865 <title>Security redirect</title>
868 <h1>Security redirect</h1>
870 We can't serve non-HTML content from the URL you have requested
, because
871 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
873 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the URL you have requested
, except that
874 "&*" is appended
. This prevents Internet Explorer from seeing a bogus file
885 * Returns true if the PATH_INFO ends with an extension other than a script
886 * extension. This could confuse IE for scripts that send arbitrary data which
887 * is not HTML but may be detected as such.
889 * Various past attempts to use the URL to make this check have generally
890 * run up against the fact that CGI does not provide a standard method to
891 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
892 * but only by prefixing it with the script name and maybe some other stuff,
893 * the extension is not mangled. So this should be a reasonably portable
894 * way to perform this security check.
896 * Also checks for anything that looks like a file extension at the end of
897 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
898 * if there was no dot before the question mark (bug 28235).
900 * @deprecated Use checkUrlExtension().
902 public function isPathInfoBad( $extWhitelist = array() ) {
903 global $wgScriptExtension;
904 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
905 return IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist );
909 * Parse the Accept-Language header sent by the client into an array
910 * @return array( languageCode => q-value ) sorted by q-value in descending order
911 * May contain the "language" '*', which applies to languages other than those explicitly listed.
912 * This is aligned with rfc2616 section 14.4
914 public function getAcceptLang() {
915 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
916 $acceptLang = $this->getHeader( 'Accept-Language' );
917 if ( !$acceptLang ) {
921 // Return the language codes in lower case
922 $acceptLang = strtolower( $acceptLang );
924 // Break up string into pieces (languages and q factors)
926 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
927 $acceptLang, $lang_parse );
929 if ( !count( $lang_parse[1] ) ) {
933 // Create a list like "en" => 0.8
934 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
935 // Set default q factor to 1
936 foreach ( $langs as $lang => $val ) {
939 } elseif ( $val == 0 ) {
940 unset($langs[$lang]);
945 arsort( $langs, SORT_NUMERIC
);
951 * Object to access the $_FILES array
953 class WebRequestUpload
{
955 protected $doesExist;
959 * Constructor. Should only be called by WebRequest
961 * @param $request WebRequest The associated request
962 * @param $key string Key in $_FILES array (name of form field)
964 public function __construct( $request, $key ) {
965 $this->request
= $request;
966 $this->doesExist
= isset( $_FILES[$key] );
967 if ( $this->doesExist
) {
968 $this->fileInfo
= $_FILES[$key];
973 * Return whether a file with this name was uploaded.
977 public function exists() {
978 return $this->doesExist
;
982 * Return the original filename of the uploaded file
984 * @return mixed Filename or null if non-existent
986 public function getName() {
987 if ( !$this->exists() ) {
992 $name = $this->fileInfo
['name'];
994 # Safari sends filenames in HTML-encoded Unicode form D...
995 # Horrid and evil! Let's try to make some kind of sense of it.
996 $name = Sanitizer
::decodeCharReferences( $name );
997 $name = $wgContLang->normalize( $name );
998 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1003 * Return the file size of the uploaded file
1005 * @return int File size or zero if non-existent
1007 public function getSize() {
1008 if ( !$this->exists() ) {
1012 return $this->fileInfo
['size'];
1016 * Return the path to the temporary file
1018 * @return mixed Path or null if non-existent
1020 public function getTempName() {
1021 if ( !$this->exists() ) {
1025 return $this->fileInfo
['tmp_name'];
1029 * Return the upload error. See link for explanation
1030 * http://www.php.net/manual/en/features.file-upload.errors.php
1032 * @return int One of the UPLOAD_ constants, 0 if non-existent
1034 public function getError() {
1035 if ( !$this->exists() ) {
1036 return 0; # UPLOAD_ERR_OK
1039 return $this->fileInfo
['error'];
1043 * Returns whether this upload failed because of overflow of a maximum set
1048 public function isIniSizeOverflow() {
1049 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1050 # PHP indicated that upload_max_filesize is exceeded
1054 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1055 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1056 # post_max_size is exceeded
1065 * WebRequest clone which takes values from a provided array.
1069 class FauxRequest
extends WebRequest
{
1070 private $wasPosted = false;
1071 private $session = array();
1074 * @param $data Array of *non*-urlencoded key => value pairs, the
1075 * fake GET/POST values
1076 * @param $wasPosted Bool: whether to treat the data as POST
1077 * @param $session Mixed: session array or null
1079 public function __construct( $data, $wasPosted = false, $session = null ) {
1080 if( is_array( $data ) ) {
1081 $this->data
= $data;
1083 throw new MWException( "FauxRequest() got bogus data" );
1085 $this->wasPosted
= $wasPosted;
1087 $this->session
= $session;
1090 private function notImplemented( $method ) {
1091 throw new MWException( "{$method}() not implemented" );
1094 public function getText( $name, $default = '' ) {
1095 # Override; don't recode since we're using internal data
1096 return (string)$this->getVal( $name, $default );
1099 public function getValues() {
1103 public function getQueryValues() {
1104 if ( $this->wasPosted
) {
1111 public function wasPosted() {
1112 return $this->wasPosted
;
1115 public function checkSessionCookie() {
1119 public function getRequestURL() {
1120 $this->notImplemented( __METHOD__
);
1123 public function getHeader( $name ) {
1124 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1127 public function setHeader( $name, $val ) {
1128 $this->headers
[$name] = $val;
1131 public function getSessionData( $key ) {
1132 if( isset( $this->session
[$key] ) )
1133 return $this->session
[$key];
1136 public function setSessionData( $key, $data ) {
1137 $this->session
[$key] = $data;
1140 public function getSessionArray() {
1141 return $this->session
;
1144 public function isPathInfoBad( $extWhitelist = array() ) {
1148 public function checkUrlExtension( $extWhitelist = array() ) {