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 * Check for title, action, and/or variant data in the URL
129 * and interpolate it into the GET variables.
130 * This should only be run after $wgContLang is available,
131 * as we may need the list of language variants to determine
132 * available variant URLs.
134 public function interpolateTitle() {
135 global $wgUsePathInfo;
137 // bug 16019: title interpolation on API queries is useless and sometimes harmful
138 if ( defined( 'MW_API' ) ) {
142 if ( $wgUsePathInfo ) {
143 $matches = self
::getPathInfo( 'title' );
144 foreach( $matches as $key => $val) {
145 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
151 * Internal URL rewriting function; tries to extract page title and,
152 * optionally, one other fixed parameter value from a URL path.
154 * @param $path string: the URL path given from the client
155 * @param $bases array: one or more URLs, optionally with $1 at the end
156 * @param $key string: if provided, the matching key in $bases will be
157 * passed on as the value of this URL parameter
158 * @return array of URL variables to interpolate; empty if no match
160 private static function extractTitle( $path, $bases, $key=false ) {
161 foreach( (array)$bases as $keyValue => $base ) {
162 // Find the part after $wgArticlePath
163 $base = str_replace( '$1', '', $base );
164 $baseLen = strlen( $base );
165 if( substr( $path, 0, $baseLen ) == $base ) {
166 $raw = substr( $path, $baseLen );
168 $matches = array( 'title' => rawurldecode( $raw ) );
170 $matches[$key] = $keyValue;
180 * Recursively strips slashes from the given array;
181 * used for undoing the evil that is magic_quotes_gpc.
183 * @param $arr array: will be modified
184 * @return array the original array
186 private function &fix_magic_quotes( &$arr ) {
187 foreach( $arr as $key => $val ) {
188 if( is_array( $val ) ) {
189 $this->fix_magic_quotes( $arr[$key] );
191 $arr[$key] = stripslashes( $val );
198 * If magic_quotes_gpc option is on, run the global arrays
199 * through fix_magic_quotes to strip out the stupid slashes.
200 * WARNING: This should only be done once! Running a second
201 * time could damage the values.
203 private function checkMagicQuotes() {
204 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
205 && get_magic_quotes_gpc();
206 if( $mustFixQuotes ) {
207 $this->fix_magic_quotes( $_COOKIE );
208 $this->fix_magic_quotes( $_ENV );
209 $this->fix_magic_quotes( $_GET );
210 $this->fix_magic_quotes( $_POST );
211 $this->fix_magic_quotes( $_REQUEST );
212 $this->fix_magic_quotes( $_SERVER );
217 * Recursively normalizes UTF-8 strings in the given array.
219 * @param $data string or array
220 * @return cleaned-up version of the given
223 function normalizeUnicode( $data ) {
224 if( is_array( $data ) ) {
225 foreach( $data as $key => $val ) {
226 $data[$key] = $this->normalizeUnicode( $val );
230 $data = $wgContLang->normalize( $data );
236 * Fetch a value from the given array or return $default if it's not set.
239 * @param $name String
240 * @param $default Mixed
243 private function getGPCVal( $arr, $name, $default ) {
244 # PHP is so nice to not touch input data, except sometimes:
245 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
246 # Work around PHP *feature* to avoid *bugs* elsewhere.
247 $name = strtr( $name, '.', '_' );
248 if( isset( $arr[$name] ) ) {
251 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
252 # Check for alternate/legacy character encoding.
253 if( isset( $wgContLang ) ) {
254 $data = $wgContLang->checkTitleEncoding( $data );
257 $data = $this->normalizeUnicode( $data );
266 * Fetch a scalar from the input or return $default if it's not set.
267 * Returns a string. Arrays are discarded. Useful for
268 * non-freeform text inputs (e.g. predefined internal text keys
269 * selected by a drop-down menu). For freeform input, see getText().
271 * @param $name String
272 * @param $default String: optional default (or NULL)
275 public function getVal( $name, $default = null ) {
276 $val = $this->getGPCVal( $this->data
, $name, $default );
277 if( is_array( $val ) ) {
280 if( is_null( $val ) ) {
288 * Set an aribtrary value into our get/post data.
290 * @param $key String: key name to use
291 * @param $value Mixed: value to set
292 * @return Mixed: old value if one was present, null otherwise
294 public function setVal( $key, $value ) {
295 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
296 $this->data
[$key] = $value;
301 * Fetch an array from the input or return $default if it's not set.
302 * If source was scalar, will return an array with a single element.
303 * If no source and no default, returns NULL.
305 * @param $name String
306 * @param $default Array: optional default (or NULL)
309 public function getArray( $name, $default = null ) {
310 $val = $this->getGPCVal( $this->data
, $name, $default );
311 if( is_null( $val ) ) {
319 * Fetch an array of integers, or return $default if it's not set.
320 * If source was scalar, will return an array with a single element.
321 * If no source and no default, returns NULL.
322 * If an array is returned, contents are guaranteed to be integers.
324 * @param $name String
325 * @param $default Array: option default (or NULL)
326 * @return Array of ints
328 public function getIntArray( $name, $default = null ) {
329 $val = $this->getArray( $name, $default );
330 if( is_array( $val ) ) {
331 $val = array_map( 'intval', $val );
337 * Fetch an integer value from the input or return $default if not set.
338 * Guaranteed to return an integer; non-numeric input will typically
341 * @param $name String
342 * @param $default Integer
345 public function getInt( $name, $default = 0 ) {
346 return intval( $this->getVal( $name, $default ) );
350 * Fetch an integer value from the input or return null if empty.
351 * Guaranteed to return an integer or null; non-numeric input will
352 * typically return null.
354 * @param $name String
357 public function getIntOrNull( $name ) {
358 $val = $this->getVal( $name );
359 return is_numeric( $val )
365 * Fetch a boolean value from the input or return $default if not set.
366 * Guaranteed to return true or false, with normal PHP semantics for
367 * boolean interpretation of strings.
369 * @param $name String
370 * @param $default Boolean
373 public function getBool( $name, $default = false ) {
374 return (bool)$this->getVal( $name, $default );
378 * Fetch a boolean value from the input or return $default if not set.
379 * Unlike getBool, the string "false" will result in boolean false, which is
380 * useful when interpreting information sent from JavaScript.
382 * @param $name String
383 * @param $default Boolean
386 public function getFuzzyBool( $name, $default = false ) {
387 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
391 * Return true if the named value is set in the input, whatever that
392 * value is (even "0"). Return false if the named value is not set.
393 * Example use is checking for the presence of check boxes in forms.
395 * @param $name String
398 public function getCheck( $name ) {
399 # Checkboxes and buttons are only present when clicked
400 # Presence connotes truth, abscense false
401 $val = $this->getVal( $name, null );
402 return isset( $val );
406 * Fetch a text string from the given array or return $default if it's not
407 * set. Carriage returns are stripped from the text, and with some language
408 * modules there is an input transliteration applied. This should generally
409 * be used for form <textarea> and <input> fields. Used for user-supplied
410 * freeform text input (for which input transformations may be required - e.g.
411 * Esperanto x-coding).
413 * @param $name String
414 * @param $default String: optional
417 public function getText( $name, $default = '' ) {
419 $val = $this->getVal( $name, $default );
420 return str_replace( "\r\n", "\n",
421 $wgContLang->recodeInput( $val ) );
425 * Extracts the given named values into an array.
426 * If no arguments are given, returns all input values.
427 * No transformation is performed on the values.
429 public function getValues() {
430 $names = func_get_args();
431 if ( count( $names ) == 0 ) {
432 $names = array_keys( $this->data
);
436 foreach ( $names as $name ) {
437 $value = $this->getVal( $name );
438 if ( !is_null( $value ) ) {
439 $retVal[$name] = $value;
446 * Get the values passed in the query string.
447 * No transformation is performed on the values.
451 public function getQueryValues() {
456 * Returns true if the present request was reached by a POST operation,
457 * false otherwise (GET, HEAD, or command-line).
459 * Note that values retrieved by the object may come from the
460 * GET URL etc even on a POST request.
464 public function wasPosted() {
465 return $_SERVER['REQUEST_METHOD'] == 'POST';
469 * Returns true if there is a session cookie set.
470 * This does not necessarily mean that the user is logged in!
472 * If you want to check for an open session, use session_id()
473 * instead; that will also tell you if the session was opened
474 * during the current request (in which case the cookie will
475 * be sent back to the client at the end of the script run).
479 public function checkSessionCookie() {
480 return isset( $_COOKIE[ session_name() ] );
484 * Get a cookie from the $_COOKIE jar
486 * @param $key String: the name of the cookie
487 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
488 * @param $default Mixed: what to return if the value isn't found
489 * @return Mixed: cookie value or $default if the cookie not set
491 public function getCookie( $key, $prefix = null, $default = null ) {
492 if( $prefix === null ) {
493 global $wgCookiePrefix;
494 $prefix = $wgCookiePrefix;
496 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
500 * Return the path portion of the request URI.
504 public function getRequestURL() {
505 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
506 $base = $_SERVER['REQUEST_URI'];
507 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
508 // Probably IIS; doesn't set REQUEST_URI
509 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
510 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
511 $base = $_SERVER['SCRIPT_NAME'];
512 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
513 $base .= '?' . $_SERVER['QUERY_STRING'];
516 // This shouldn't happen!
517 throw new MWException( "Web server doesn't provide either " .
518 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
519 "of your web server configuration to http://bugzilla.wikimedia.org/" );
521 // User-agents should not send a fragment with the URI, but
522 // if they do, and the web server passes it on to us, we
523 // need to strip it or we get false-positive redirect loops
524 // or weird output URLs
525 $hash = strpos( $base, '#' );
526 if( $hash !== false ) {
527 $base = substr( $base, 0, $hash );
529 if( $base[0] == '/' ) {
532 // We may get paths with a host prepended; strip it.
533 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
538 * Return the request URI with the canonical service and hostname.
542 public function getFullRequestURL() {
544 return $wgServer . $this->getRequestURL();
548 * Take an arbitrary query and rewrite the present URL to include it
549 * @param $query String: query string fragment; do not include initial '?'
553 public function appendQuery( $query ) {
554 return $this->appendQueryArray( wfCgiToArray( $query ) );
558 * HTML-safe version of appendQuery().
560 * @param $query String: query string fragment; do not include initial '?'
563 public function escapeAppendQuery( $query ) {
564 return htmlspecialchars( $this->appendQuery( $query ) );
567 public function appendQueryValue( $key, $value, $onlyquery = false ) {
568 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
572 * Appends or replaces value of query variables.
574 * @param $array Array of values to replace/add to query
575 * @param $onlyquery Bool: whether to only return the query string and not
579 public function appendQueryArray( $array, $onlyquery = false ) {
581 $newquery = $this->getQueryValues();
582 unset( $newquery['title'] );
583 $newquery = array_merge( $newquery, $array );
584 $query = wfArrayToCGI( $newquery );
585 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
589 * Check for limit and offset parameters on the input, and return sensible
590 * defaults if not given. The limit must be positive and is capped at 5000.
591 * Offset must be positive but is not capped.
593 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
594 * @param $optionname String: to specify an option other than rclimit to pull from.
595 * @return array first element is limit, second is offset
597 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
600 $limit = $this->getInt( 'limit', 0 );
604 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
605 $limit = (int)$wgUser->getOption( $optionname );
610 if( $limit > 5000 ) {
611 $limit = 5000; # We have *some* limits...
614 $offset = $this->getInt( 'offset', 0 );
619 return array( $limit, $offset );
623 * Return the path to the temporary file where PHP has stored the upload.
625 * @param $key String:
626 * @return string or NULL if no such file.
628 public function getFileTempname( $key ) {
629 $file = new WebRequestUpload( $this, $key );
630 return $file->getTempName();
634 * Return the size of the upload, or 0.
636 * @deprecated since 1.17
637 * @param $key String:
640 public function getFileSize( $key ) {
641 $file = new WebRequestUpload( $this, $key );
642 return $file->getSize();
646 * Return the upload error or 0
648 * @param $key String:
651 public function getUploadError( $key ) {
652 $file = new WebRequestUpload( $this, $key );
653 return $file->getError();
657 * Return the original filename of the uploaded file, as reported by
658 * the submitting user agent. HTML-style character entities are
659 * interpreted and normalized to Unicode normalization form C, in part
660 * to deal with weird input from Safari with non-ASCII filenames.
662 * Other than this the name is not verified for being a safe filename.
664 * @param $key String:
665 * @return string or NULL if no such file.
667 public function getFileName( $key ) {
668 $file = new WebRequestUpload( $this, $key );
669 return $file->getName();
673 * Return a WebRequestUpload object corresponding to the key
676 * @return WebRequestUpload
678 public function getUpload( $key ) {
679 return new WebRequestUpload( $this, $key );
683 * Return a handle to WebResponse style object, for setting cookies,
684 * headers and other stuff, for Request being worked on.
686 * @return WebResponse
688 public function response() {
689 /* Lazy initialization of response object for this request */
690 if ( !is_object( $this->response
) ) {
691 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
692 $this->response
= new $class();
694 return $this->response
;
698 * Initialise the header list
700 private function initHeaders() {
701 if ( count( $this->headers
) ) {
705 if ( function_exists( 'apache_request_headers' ) ) {
706 foreach ( apache_request_headers() as $tempName => $tempValue ) {
707 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
711 foreach ( $_SERVER as $name => $value ) {
712 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
713 $name = str_replace( '_', '-', substr( $name, 5 ) );
714 $this->headers
[$name] = $value;
715 } elseif ( $name === 'CONTENT_LENGTH' ) {
716 $this->headers
['CONTENT-LENGTH'] = $value;
723 * Get an array containing all request headers
725 * @return Array mapping header name to its value
727 public function getAllHeaders() {
728 $this->initHeaders();
729 return $this->headers
;
733 * Get a request header, or false if it isn't set
734 * @param $name String: case-insensitive header name
736 public function getHeader( $name ) {
737 $this->initHeaders();
738 $name = strtoupper( $name );
739 if ( isset( $this->headers
[$name] ) ) {
740 return $this->headers
[$name];
747 * Get data from $_SESSION
749 * @param $key String: name of key in $_SESSION
752 public function getSessionData( $key ) {
753 if( !isset( $_SESSION[$key] ) ) {
756 return $_SESSION[$key];
762 * @param $key String: name of key in $_SESSION
765 public function setSessionData( $key, $data ) {
766 $_SESSION[$key] = $data;
770 * Returns true if the PATH_INFO ends with an extension other than a script
771 * extension. This could confuse IE for scripts that send arbitrary data which
772 * is not HTML but may be detected as such.
774 * Various past attempts to use the URL to make this check have generally
775 * run up against the fact that CGI does not provide a standard method to
776 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
777 * but only by prefixing it with the script name and maybe some other stuff,
778 * the extension is not mangled. So this should be a reasonably portable
779 * way to perform this security check.
781 * Also checks for anything that looks like a file extension at the end of
782 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
783 * if there was no dot before the question mark (bug 28235).
785 public function isPathInfoBad() {
786 global $wgScriptExtension;
788 if ( $this->isQueryStringBad() ) {
792 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
795 $pi = $_SERVER['PATH_INFO'];
796 $dotPos = strrpos( $pi, '.' );
797 if ( $dotPos === false ) {
800 $ext = substr( $pi, $dotPos );
801 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
805 * Determine what extension IE6 will infer from a certain query string.
806 * If the URL has an extension before the question mark, IE6 will use
807 * that and ignore the query string, but per the comment at
808 * isPathInfoBad() we don't have a reliable way to determine the URL,
809 * so isPathInfoBad() just passes in the query string for $url.
810 * All entry points have safe extensions (php, php5) anyway, so
811 * checking the query string is possibly overly paranoid but never
814 * The criteria for finding an extension are as follows:
815 * - a possible extension is a dot followed by one or more characters not
817 * - if we find a possible extension followed by the end of the string or
818 * a #, that's our extension
819 * - if we find a possible extension followed by a ?, that's our extension
820 * - UNLESS it's exe, dll or cgi, in which case we ignore it and continue
821 * searching for another possible extension
822 * - if we find a possible extension followed by a dot or another illegal
823 * character, we ignore it and continue searching
825 * @param $url string URL
826 * @return mixed Detected extension (string), or false if none found
828 public static function findIE6Extension( $url ) {
830 $hashPos = strpos( $url, '#' );
831 if ( $hashPos !== false ) {
832 $urlLength = $hashPos;
834 $urlLength = strlen( $url );
836 $remainingLength = $urlLength;
837 while ( $remainingLength > 0 ) {
838 // Skip ahead to the next dot
839 $pos +
= strcspn( $url, '.', $pos, $remainingLength );
840 if ( $pos >= $urlLength ) {
841 // End of string, we're done
845 // We found a dot. Skip past it
847 $remainingLength = $urlLength - $pos;
849 // Check for illegal characters in our prospective extension,
850 // or for another dot
851 $nextPos = $pos +
strcspn( $url, "<>\\\"/:|?*.", $pos, $remainingLength );
852 if ( $nextPos >= $urlLength ) {
853 // No illegal character or next dot
854 // We have our extension
855 return substr( $url, $pos, $urlLength - $pos );
857 if ( $url[$nextPos] === '?' ) {
858 // We've found a legal extension followed by a question mark
859 // If the extension is NOT exe, dll or cgi, return it
860 $extension = substr( $url, $pos, $nextPos - $pos );
861 if ( strcasecmp( $extension, 'exe' ) && strcasecmp( $extension, 'dll' ) &&
862 strcasecmp( $extension, 'cgi' ) )
866 // Else continue looking
868 // We found an illegal character or another dot
869 // Skip to that character and continue the loop
871 $remainingLength = $urlLength - $pos;
877 * Check for a bad query string, which IE 6 will use as a potentially
878 * insecure cache file extension. See bug 28235. Returns true if the
879 * request should be disallowed.
881 public function isQueryStringBad() {
882 if ( !isset( $_SERVER['QUERY_STRING'] ) ) {
886 $extension = self
::findIE6Extension( $_SERVER['QUERY_STRING'] );
887 if ( $extension === '' ) {
891 return (bool)preg_match( '/^[a-zA-Z0-9_-]+$/', $extension );
895 * Parse the Accept-Language header sent by the client into an array
896 * @return array( languageCode => q-value ) sorted by q-value in descending order
897 * May contain the "language" '*', which applies to languages other than those explicitly listed.
898 * This is aligned with rfc2616 section 14.4
900 public function getAcceptLang() {
901 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
902 $acceptLang = $this->getHeader( 'Accept-Language' );
903 if ( !$acceptLang ) {
907 // Return the language codes in lower case
908 $acceptLang = strtolower( $acceptLang );
910 // Break up string into pieces (languages and q factors)
912 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
913 $acceptLang, $lang_parse );
915 if ( !count( $lang_parse[1] ) ) {
919 // Create a list like "en" => 0.8
920 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
921 // Set default q factor to 1
922 foreach ( $langs as $lang => $val ) {
925 } else if ( $val == 0 ) {
926 unset($langs[$lang]);
931 arsort( $langs, SORT_NUMERIC
);
937 * Object to access the $_FILES array
939 class WebRequestUpload
{
941 protected $doesExist;
945 * Constructor. Should only be called by WebRequest
947 * @param $request WebRequest The associated request
948 * @param $key string Key in $_FILES array (name of form field)
950 public function __construct( $request, $key ) {
951 $this->request
= $request;
952 $this->doesExist
= isset( $_FILES[$key] );
953 if ( $this->doesExist
) {
954 $this->fileInfo
= $_FILES[$key];
959 * Return whether a file with this name was uploaded.
963 public function exists() {
964 return $this->doesExist
;
968 * Return the original filename of the uploaded file
970 * @return mixed Filename or null if non-existent
972 public function getName() {
973 if ( !$this->exists() ) {
978 $name = $this->fileInfo
['name'];
980 # Safari sends filenames in HTML-encoded Unicode form D...
981 # Horrid and evil! Let's try to make some kind of sense of it.
982 $name = Sanitizer
::decodeCharReferences( $name );
983 $name = $wgContLang->normalize( $name );
984 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
989 * Return the file size of the uploaded file
991 * @return int File size or zero if non-existent
993 public function getSize() {
994 if ( !$this->exists() ) {
998 return $this->fileInfo
['size'];
1002 * Return the path to the temporary file
1004 * @return mixed Path or null if non-existent
1006 public function getTempName() {
1007 if ( !$this->exists() ) {
1011 return $this->fileInfo
['tmp_name'];
1015 * Return the upload error. See link for explanation
1016 * http://www.php.net/manual/en/features.file-upload.errors.php
1018 * @return int One of the UPLOAD_ constants, 0 if non-existent
1020 public function getError() {
1021 if ( !$this->exists() ) {
1022 return 0; # UPLOAD_ERR_OK
1025 return $this->fileInfo
['error'];
1029 * Returns whether this upload failed because of overflow of a maximum set
1034 public function isIniSizeOverflow() {
1035 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1036 # PHP indicated that upload_max_filesize is exceeded
1040 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1041 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1042 # post_max_size is exceeded
1051 * WebRequest clone which takes values from a provided array.
1055 class FauxRequest
extends WebRequest
{
1056 private $wasPosted = false;
1057 private $session = array();
1060 * @param $data Array of *non*-urlencoded key => value pairs, the
1061 * fake GET/POST values
1062 * @param $wasPosted Bool: whether to treat the data as POST
1063 * @param $session Mixed: session array or null
1065 public function __construct( $data, $wasPosted = false, $session = null ) {
1066 if( is_array( $data ) ) {
1067 $this->data
= $data;
1069 throw new MWException( "FauxRequest() got bogus data" );
1071 $this->wasPosted
= $wasPosted;
1073 $this->session
= $session;
1076 private function notImplemented( $method ) {
1077 throw new MWException( "{$method}() not implemented" );
1080 public function getText( $name, $default = '' ) {
1081 # Override; don't recode since we're using internal data
1082 return (string)$this->getVal( $name, $default );
1085 public function getValues() {
1089 public function getQueryValues() {
1090 if ( $this->wasPosted
) {
1097 public function wasPosted() {
1098 return $this->wasPosted
;
1101 public function checkSessionCookie() {
1105 public function getRequestURL() {
1106 $this->notImplemented( __METHOD__
);
1109 public function getHeader( $name ) {
1110 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1113 public function setHeader( $name, $val ) {
1114 $this->headers
[$name] = $val;
1117 public function getSessionData( $key ) {
1118 if( isset( $this->session
[$key] ) )
1119 return $this->session
[$key];
1122 public function setSessionData( $key, $data ) {
1123 $this->session
[$key] = $data;
1126 public function getSessionArray() {
1127 return $this->session
;
1130 public function isPathInfoBad() {