Followup r81034, remove the global statements
[mediawiki.git] / includes / WebRequest.php
blob1c2e22e464ccd0a7b60abceea88d25d6e1072ddf
1 <?php
2 /**
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
23 * @file
26 /**
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
34 * input.
36 * @ingroup HTTP
38 class WebRequest {
39 protected $data, $headers = array();
41 /**
42 * Lazy-init response object
43 * @var WebResponse
45 private $response;
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;
58 /**
59 * Check for title, action, and/or variant data in the URL
60 * and interpolate it into the GET variables.
61 * This should only be run after $wgContLang is available,
62 * as we may need the list of language variants to determine
63 * available variant URLs.
65 public function interpolateTitle() {
66 global $wgUsePathInfo;
68 // bug 16019: title interpolation on API queries is useless and sometimes harmful
69 if ( defined( 'MW_API' ) ) {
70 return;
73 if ( $wgUsePathInfo ) {
74 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
75 // And also by Apache 2.x, double slashes are converted to single slashes.
76 // So we will use REQUEST_URI if possible.
77 $matches = array();
79 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
80 // Slurp out the path portion to examine...
81 $url = $_SERVER['REQUEST_URI'];
82 if ( !preg_match( '!^https?://!', $url ) ) {
83 $url = 'http://unused' . $url;
85 $a = parse_url( $url );
86 if( $a ) {
87 $path = isset( $a['path'] ) ? $a['path'] : '';
89 global $wgScript;
90 if( $path == $wgScript ) {
91 // Script inside a rewrite path?
92 // Abort to keep from breaking...
93 return;
95 // Raw PATH_INFO style
96 $matches = $this->extractTitle( $path, "$wgScript/$1" );
98 global $wgArticlePath;
99 if( !$matches && $wgArticlePath ) {
100 $matches = $this->extractTitle( $path, $wgArticlePath );
103 global $wgActionPaths;
104 if( !$matches && $wgActionPaths ) {
105 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
108 global $wgVariantArticlePath, $wgContLang;
109 if( !$matches && $wgVariantArticlePath ) {
110 $variantPaths = array();
111 foreach( $wgContLang->getVariants() as $variant ) {
112 $variantPaths[$variant] =
113 str_replace( '$2', $variant, $wgVariantArticlePath );
115 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
118 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
119 // Mangled PATH_INFO
120 // http://bugs.php.net/bug.php?id=31892
121 // Also reported when ini_get('cgi.fix_pathinfo')==false
122 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
124 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
125 // Regular old PATH_INFO yay
126 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
128 foreach( $matches as $key => $val) {
129 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
135 * Internal URL rewriting function; tries to extract page title and,
136 * optionally, one other fixed parameter value from a URL path.
138 * @param $path string: the URL path given from the client
139 * @param $bases array: one or more URLs, optionally with $1 at the end
140 * @param $key string: if provided, the matching key in $bases will be
141 * passed on as the value of this URL parameter
142 * @return array of URL variables to interpolate; empty if no match
144 private function extractTitle( $path, $bases, $key=false ) {
145 foreach( (array)$bases as $keyValue => $base ) {
146 // Find the part after $wgArticlePath
147 $base = str_replace( '$1', '', $base );
148 $baseLen = strlen( $base );
149 if( substr( $path, 0, $baseLen ) == $base ) {
150 $raw = substr( $path, $baseLen );
151 if( $raw !== '' ) {
152 $matches = array( 'title' => rawurldecode( $raw ) );
153 if( $key ) {
154 $matches[$key] = $keyValue;
156 return $matches;
160 return array();
164 * Recursively strips slashes from the given array;
165 * used for undoing the evil that is magic_quotes_gpc.
167 * @param $arr array: will be modified
168 * @return array the original array
170 private function &fix_magic_quotes( &$arr ) {
171 foreach( $arr as $key => $val ) {
172 if( is_array( $val ) ) {
173 $this->fix_magic_quotes( $arr[$key] );
174 } else {
175 $arr[$key] = stripslashes( $val );
178 return $arr;
182 * If magic_quotes_gpc option is on, run the global arrays
183 * through fix_magic_quotes to strip out the stupid slashes.
184 * WARNING: This should only be done once! Running a second
185 * time could damage the values.
187 private function checkMagicQuotes() {
188 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
189 && get_magic_quotes_gpc();
190 if( $mustFixQuotes ) {
191 $this->fix_magic_quotes( $_COOKIE );
192 $this->fix_magic_quotes( $_ENV );
193 $this->fix_magic_quotes( $_GET );
194 $this->fix_magic_quotes( $_POST );
195 $this->fix_magic_quotes( $_REQUEST );
196 $this->fix_magic_quotes( $_SERVER );
201 * Recursively normalizes UTF-8 strings in the given array.
203 * @param $data string or array
204 * @return cleaned-up version of the given
205 * @private
207 function normalizeUnicode( $data ) {
208 if( is_array( $data ) ) {
209 foreach( $data as $key => $val ) {
210 $data[$key] = $this->normalizeUnicode( $val );
212 } else {
213 global $wgContLang;
214 $data = $wgContLang->normalize( $data );
216 return $data;
220 * Fetch a value from the given array or return $default if it's not set.
222 * @param $arr Array
223 * @param $name String
224 * @param $default Mixed
225 * @return mixed
227 private function getGPCVal( $arr, $name, $default ) {
228 # PHP is so nice to not touch input data, except sometimes:
229 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
230 # Work around PHP *feature* to avoid *bugs* elsewhere.
231 $name = strtr( $name, '.', '_' );
232 if( isset( $arr[$name] ) ) {
233 global $wgContLang;
234 $data = $arr[$name];
235 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
236 # Check for alternate/legacy character encoding.
237 if( isset( $wgContLang ) ) {
238 $data = $wgContLang->checkTitleEncoding( $data );
241 $data = $this->normalizeUnicode( $data );
242 return $data;
243 } else {
244 taint( $default );
245 return $default;
250 * Fetch a scalar from the input or return $default if it's not set.
251 * Returns a string. Arrays are discarded. Useful for
252 * non-freeform text inputs (e.g. predefined internal text keys
253 * selected by a drop-down menu). For freeform input, see getText().
255 * @param $name String
256 * @param $default String: optional default (or NULL)
257 * @return String
259 public function getVal( $name, $default = null ) {
260 $val = $this->getGPCVal( $this->data, $name, $default );
261 if( is_array( $val ) ) {
262 $val = $default;
264 if( is_null( $val ) ) {
265 return $val;
266 } else {
267 return (string)$val;
272 * Set an aribtrary value into our get/post data.
274 * @param $key String: key name to use
275 * @param $value Mixed: value to set
276 * @return Mixed: old value if one was present, null otherwise
278 public function setVal( $key, $value ) {
279 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
280 $this->data[$key] = $value;
281 return $ret;
285 * Fetch an array from the input or return $default if it's not set.
286 * If source was scalar, will return an array with a single element.
287 * If no source and no default, returns NULL.
289 * @param $name String
290 * @param $default Array: optional default (or NULL)
291 * @return Array
293 public function getArray( $name, $default = null ) {
294 $val = $this->getGPCVal( $this->data, $name, $default );
295 if( is_null( $val ) ) {
296 return null;
297 } else {
298 return (array)$val;
303 * Fetch an array of integers, or return $default if it's not set.
304 * If source was scalar, will return an array with a single element.
305 * If no source and no default, returns NULL.
306 * If an array is returned, contents are guaranteed to be integers.
308 * @param $name String
309 * @param $default Array: option default (or NULL)
310 * @return Array of ints
312 public function getIntArray( $name, $default = null ) {
313 $val = $this->getArray( $name, $default );
314 if( is_array( $val ) ) {
315 $val = array_map( 'intval', $val );
317 return $val;
321 * Fetch an integer value from the input or return $default if not set.
322 * Guaranteed to return an integer; non-numeric input will typically
323 * return 0.
325 * @param $name String
326 * @param $default Integer
327 * @return Integer
329 public function getInt( $name, $default = 0 ) {
330 return intval( $this->getVal( $name, $default ) );
334 * Fetch an integer value from the input or return null if empty.
335 * Guaranteed to return an integer or null; non-numeric input will
336 * typically return null.
338 * @param $name String
339 * @return Integer
341 public function getIntOrNull( $name ) {
342 $val = $this->getVal( $name );
343 return is_numeric( $val )
344 ? intval( $val )
345 : null;
349 * Fetch a boolean value from the input or return $default if not set.
350 * Guaranteed to return true or false, with normal PHP semantics for
351 * boolean interpretation of strings.
353 * @param $name String
354 * @param $default Boolean
355 * @return Boolean
357 public function getBool( $name, $default = false ) {
358 return (bool)$this->getVal( $name, $default );
362 * Fetch a boolean value from the input or return $default if not set.
363 * Unlike getBool, the string "false" will result in boolean false, which is
364 * useful when interpreting information sent from JavaScript.
366 * @param $name String
367 * @param $default Boolean
368 * @return Boolean
370 public function getFuzzyBool( $name, $default = false ) {
371 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
375 * Return true if the named value is set in the input, whatever that
376 * value is (even "0"). Return false if the named value is not set.
377 * Example use is checking for the presence of check boxes in forms.
379 * @param $name String
380 * @return Boolean
382 public function getCheck( $name ) {
383 # Checkboxes and buttons are only present when clicked
384 # Presence connotes truth, abscense false
385 $val = $this->getVal( $name, null );
386 return isset( $val );
390 * Fetch a text string from the given array or return $default if it's not
391 * set. Carriage returns are stripped from the text, and with some language
392 * modules there is an input transliteration applied. This should generally
393 * be used for form <textarea> and <input> fields. Used for user-supplied
394 * freeform text input (for which input transformations may be required - e.g.
395 * Esperanto x-coding).
397 * @param $name String
398 * @param $default String: optional
399 * @return String
401 public function getText( $name, $default = '' ) {
402 global $wgContLang;
403 $val = $this->getVal( $name, $default );
404 return str_replace( "\r\n", "\n",
405 $wgContLang->recodeInput( $val ) );
409 * Extracts the given named values into an array.
410 * If no arguments are given, returns all input values.
411 * No transformation is performed on the values.
413 public function getValues() {
414 $names = func_get_args();
415 if ( count( $names ) == 0 ) {
416 $names = array_keys( $this->data );
419 $retVal = array();
420 foreach ( $names as $name ) {
421 $value = $this->getVal( $name );
422 if ( !is_null( $value ) ) {
423 $retVal[$name] = $value;
426 return $retVal;
430 * Returns true if the present request was reached by a POST operation,
431 * false otherwise (GET, HEAD, or command-line).
433 * Note that values retrieved by the object may come from the
434 * GET URL etc even on a POST request.
436 * @return Boolean
438 public function wasPosted() {
439 return $_SERVER['REQUEST_METHOD'] == 'POST';
443 * Returns true if there is a session cookie set.
444 * This does not necessarily mean that the user is logged in!
446 * If you want to check for an open session, use session_id()
447 * instead; that will also tell you if the session was opened
448 * during the current request (in which case the cookie will
449 * be sent back to the client at the end of the script run).
451 * @return Boolean
453 public function checkSessionCookie() {
454 return isset( $_COOKIE[ session_name() ] );
458 * Get a cookie from the $_COOKIE jar
460 * @param $key String: the name of the cookie
461 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
462 * @param $default Mixed: what to return if the value isn't found
463 * @return Mixed: cookie value or $default if the cookie not set
465 public function getCookie( $key, $prefix = null, $default = null ) {
466 if( $prefix === null ) {
467 global $wgCookiePrefix;
468 $prefix = $wgCookiePrefix;
470 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
474 * Return the path portion of the request URI.
476 * @return String
478 public function getRequestURL() {
479 if( isset( $_SERVER['REQUEST_URI']) && strlen($_SERVER['REQUEST_URI']) ) {
480 $base = $_SERVER['REQUEST_URI'];
481 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
482 // Probably IIS; doesn't set REQUEST_URI
483 $base = $_SERVER['SCRIPT_NAME'];
484 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
485 $base .= '?' . $_SERVER['QUERY_STRING'];
487 } else {
488 // This shouldn't happen!
489 throw new MWException( "Web server doesn't provide either " .
490 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
491 "web server configuration to http://bugzilla.wikimedia.org/" );
493 // User-agents should not send a fragment with the URI, but
494 // if they do, and the web server passes it on to us, we
495 // need to strip it or we get false-positive redirect loops
496 // or weird output URLs
497 $hash = strpos( $base, '#' );
498 if( $hash !== false ) {
499 $base = substr( $base, 0, $hash );
501 if( $base{0} == '/' ) {
502 return $base;
503 } else {
504 // We may get paths with a host prepended; strip it.
505 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
510 * Return the request URI with the canonical service and hostname.
512 * @return String
514 public function getFullRequestURL() {
515 global $wgServer;
516 return $wgServer . $this->getRequestURL();
520 * Take an arbitrary query and rewrite the present URL to include it
521 * @param $query String: query string fragment; do not include initial '?'
523 * @return String
525 public function appendQuery( $query ) {
526 global $wgTitle;
527 $basequery = '';
528 foreach( $_GET as $var => $val ) {
529 if ( $var == 'title' ) {
530 continue;
532 if ( is_array( $val ) ) {
533 /* This will happen given a request like
534 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
536 continue;
538 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
540 $basequery .= '&' . $query;
542 # Trim the extra &
543 $basequery = substr( $basequery, 1 );
544 return $wgTitle->getLocalURL( $basequery );
548 * HTML-safe version of appendQuery().
550 * @param $query String: query string fragment; do not include initial '?'
551 * @return String
553 public function escapeAppendQuery( $query ) {
554 return htmlspecialchars( $this->appendQuery( $query ) );
557 public function appendQueryValue( $key, $value, $onlyquery = false ) {
558 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
562 * Appends or replaces value of query variables.
564 * @param $array Array of values to replace/add to query
565 * @param $onlyquery Bool: whether to only return the query string and not
566 * the complete URL
567 * @return String
569 public function appendQueryArray( $array, $onlyquery = false ) {
570 global $wgTitle;
571 $newquery = $_GET;
572 unset( $newquery['title'] );
573 $newquery = array_merge( $newquery, $array );
574 $query = wfArrayToCGI( $newquery );
575 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
579 * Check for limit and offset parameters on the input, and return sensible
580 * defaults if not given. The limit must be positive and is capped at 5000.
581 * Offset must be positive but is not capped.
583 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
584 * @param $optionname String: to specify an option other than rclimit to pull from.
585 * @return array first element is limit, second is offset
587 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
588 global $wgUser;
590 $limit = $this->getInt( 'limit', 0 );
591 if( $limit < 0 ) {
592 $limit = 0;
594 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
595 $limit = (int)$wgUser->getOption( $optionname );
597 if( $limit <= 0 ) {
598 $limit = $deflimit;
600 if( $limit > 5000 ) {
601 $limit = 5000; # We have *some* limits...
604 $offset = $this->getInt( 'offset', 0 );
605 if( $offset < 0 ) {
606 $offset = 0;
609 return array( $limit, $offset );
613 * Return the path to the temporary file where PHP has stored the upload.
615 * @param $key String:
616 * @return string or NULL if no such file.
618 public function getFileTempname( $key ) {
619 $file = new WebRequestUpload( $this, $key );
620 return $file->getTempName();
624 * Return the size of the upload, or 0.
626 * @deprecated
627 * @param $key String:
628 * @return integer
630 public function getFileSize( $key ) {
631 $file = new WebRequestUpload( $this, $key );
632 return $file->getSize();
636 * Return the upload error or 0
638 * @param $key String:
639 * @return integer
641 public function getUploadError( $key ) {
642 $file = new WebRequestUpload( $this, $key );
643 return $file->getError();
647 * Return the original filename of the uploaded file, as reported by
648 * the submitting user agent. HTML-style character entities are
649 * interpreted and normalized to Unicode normalization form C, in part
650 * to deal with weird input from Safari with non-ASCII filenames.
652 * Other than this the name is not verified for being a safe filename.
654 * @param $key String:
655 * @return string or NULL if no such file.
657 public function getFileName( $key ) {
658 $file = new WebRequestUpload( $this, $key );
659 return $file->getName();
663 * Return a WebRequestUpload object corresponding to the key
665 * @param @key string
666 * @return WebRequestUpload
668 public function getUpload( $key ) {
669 return new WebRequestUpload( $this, $key );
673 * Return a handle to WebResponse style object, for setting cookies,
674 * headers and other stuff, for Request being worked on.
676 * @return WebResponse
678 public function response() {
679 /* Lazy initialization of response object for this request */
680 if ( !is_object( $this->response ) ) {
681 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
682 $this->response = new $class();
684 return $this->response;
688 * Get a request header, or false if it isn't set
689 * @param $name String: case-insensitive header name
691 public function getHeader( $name ) {
692 $name = strtoupper( $name );
693 if ( function_exists( 'apache_request_headers' ) ) {
694 if ( !$this->headers ) {
695 foreach ( apache_request_headers() as $tempName => $tempValue ) {
696 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
699 if ( isset( $this->headers[$name] ) ) {
700 return $this->headers[$name];
701 } else {
702 return false;
704 } else {
705 $name = 'HTTP_' . str_replace( '-', '_', $name );
706 if ( $name === 'HTTP_CONTENT_LENGTH' && !isset( $_SERVER[$name] ) ) {
707 $name = 'CONTENT_LENGTH';
709 if ( isset( $_SERVER[$name] ) ) {
710 return $_SERVER[$name];
711 } else {
712 return false;
718 * Get data from $_SESSION
720 * @param $key String: name of key in $_SESSION
721 * @return Mixed
723 public function getSessionData( $key ) {
724 if( !isset( $_SESSION[$key] ) ) {
725 return null;
727 return $_SESSION[$key];
731 * Set session data
733 * @param $key String: name of key in $_SESSION
734 * @param $data Mixed
736 public function setSessionData( $key, $data ) {
737 $_SESSION[$key] = $data;
741 * Returns true if the PATH_INFO ends with an extension other than a script
742 * extension. This could confuse IE for scripts that send arbitrary data which
743 * is not HTML but may be detected as such.
745 * Various past attempts to use the URL to make this check have generally
746 * run up against the fact that CGI does not provide a standard method to
747 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
748 * but only by prefixing it with the script name and maybe some other stuff,
749 * the extension is not mangled. So this should be a reasonably portable
750 * way to perform this security check.
752 public function isPathInfoBad() {
753 global $wgScriptExtension;
755 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
756 return false;
758 $pi = $_SERVER['PATH_INFO'];
759 $dotPos = strrpos( $pi, '.' );
760 if ( $dotPos === false ) {
761 return false;
763 $ext = substr( $pi, $dotPos );
764 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
768 * Parse the Accept-Language header sent by the client into an array
769 * @return array( languageCode => q-value ) sorted by q-value in descending order
770 * May contain the "language" '*', which applies to languages other than those explicitly listed.
771 * This is aligned with rfc2616 section 14.4
773 public function getAcceptLang() {
774 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
775 $acceptLang = $this->getHeader( 'Accept-Language' );
776 if ( !$acceptLang ) {
777 return array();
780 // Return the language codes in lower case
781 $acceptLang = strtolower( $acceptLang );
783 // Break up string into pieces (languages and q factors)
784 $lang_parse = null;
785 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
786 $acceptLang, $lang_parse );
788 if ( !count( $lang_parse[1] ) ) {
789 return array();
792 // Create a list like "en" => 0.8
793 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
794 // Set default q factor to 1
795 foreach ( $langs as $lang => $val ) {
796 if ( $val === '' ) {
797 $langs[$lang] = 1;
798 } else if ( $val == 0 ) {
799 unset($langs[$lang]);
803 // Sort list
804 arsort( $langs, SORT_NUMERIC );
805 return $langs;
810 * Object to access the $_FILES array
812 class WebRequestUpload {
813 protected $request;
814 protected $doesExist;
815 protected $fileInfo;
818 * Constructor. Should only be called by WebRequest
820 * @param $request WebRequest The associated request
821 * @param $key string Key in $_FILES array (name of form field)
823 public function __construct( $request, $key ) {
824 $this->request = $request;
825 $this->doesExist = isset( $_FILES[$key] );
826 if ( $this->doesExist ) {
827 $this->fileInfo = $_FILES[$key];
832 * Return whether a file with this name was uploaded.
834 * @return bool
836 public function exists() {
837 return $this->doesExist;
841 * Return the original filename of the uploaded file
843 * @return mixed Filename or null if non-existent
845 public function getName() {
846 if ( !$this->exists() ) {
847 return null;
850 global $wgContLang;
851 $name = $this->fileInfo['name'];
853 # Safari sends filenames in HTML-encoded Unicode form D...
854 # Horrid and evil! Let's try to make some kind of sense of it.
855 $name = Sanitizer::decodeCharReferences( $name );
856 $name = $wgContLang->normalize( $name );
857 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
858 return $name;
862 * Return the file size of the uploaded file
864 * @return int File size or zero if non-existent
866 public function getSize() {
867 if ( !$this->exists() ) {
868 return 0;
871 return $this->fileInfo['size'];
875 * Return the path to the temporary file
877 * @return mixed Path or null if non-existent
879 public function getTempName() {
880 if ( !$this->exists() ) {
881 return null;
884 return $this->fileInfo['tmp_name'];
888 * Return the upload error. See link for explanation
889 * http://www.php.net/manual/en/features.file-upload.errors.php
891 * @return int One of the UPLOAD_ constants, 0 if non-existent
893 public function getError() {
894 if ( !$this->exists() ) {
895 return 0; # UPLOAD_ERR_OK
898 return $this->fileInfo['error'];
902 * Returns whether this upload failed because of overflow of a maximum set
903 * in php.ini
905 * @return bool
907 public function isIniSizeOverflow() {
908 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
909 # PHP indicated that upload_max_filesize is exceeded
910 return true;
913 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
914 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
915 # post_max_size is exceeded
916 return true;
919 return false;
924 * WebRequest clone which takes values from a provided array.
926 * @ingroup HTTP
928 class FauxRequest extends WebRequest {
929 private $wasPosted = false;
930 private $session = array();
933 * @param $data Array of *non*-urlencoded key => value pairs, the
934 * fake GET/POST values
935 * @param $wasPosted Bool: whether to treat the data as POST
936 * @param $session Mixed: session array or null
938 public function __construct( $data, $wasPosted = false, $session = null ) {
939 if( is_array( $data ) ) {
940 $this->data = $data;
941 } else {
942 throw new MWException( "FauxRequest() got bogus data" );
944 $this->wasPosted = $wasPosted;
945 if( $session )
946 $this->session = $session;
949 private function notImplemented( $method ) {
950 throw new MWException( "{$method}() not implemented" );
953 public function getText( $name, $default = '' ) {
954 # Override; don't recode since we're using internal data
955 return (string)$this->getVal( $name, $default );
958 public function getValues() {
959 return $this->data;
962 public function wasPosted() {
963 return $this->wasPosted;
966 public function checkSessionCookie() {
967 return false;
970 public function getRequestURL() {
971 $this->notImplemented( __METHOD__ );
974 public function appendQuery( $query ) {
975 global $wgTitle;
976 $basequery = '';
977 foreach( $this->data as $var => $val ) {
978 if ( $var == 'title' ) {
979 continue;
981 if ( is_array( $val ) ) {
982 /* This will happen given a request like
983 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
985 continue;
987 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
989 $basequery .= '&' . $query;
991 # Trim the extra &
992 $basequery = substr( $basequery, 1 );
993 return $wgTitle->getLocalURL( $basequery );
996 public function getHeader( $name ) {
997 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1000 public function setHeader( $name, $val ) {
1001 $this->headers[$name] = $val;
1004 public function getSessionData( $key ) {
1005 if( isset( $this->session[$key] ) )
1006 return $this->session[$key];
1009 public function setSessionData( $key, $data ) {
1010 $this->session[$key] = $data;
1013 public function isPathInfoBad() {
1014 return false;