Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / includes / WebRequest.php
blob3bdf6452b6ac5a9e1d27ae3941fa9da60640e746
1 <?php
2 /**
3 * Deal with importing all those nasty 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 /**
48 * Cached client IP address
49 * @var String
51 private $ip;
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;
64 /**
65 * Extract relevant query arguments from the http request uri's path
66 * to be merged with the normal php provided query arguments.
67 * Tries to use the REQUEST_URI data if available and parses it
68 * according to the wiki's configuration looking for any known pattern.
70 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
71 * provided by the server if any and use that to set a 'title' parameter.
73 * @param string $want If this is not 'all', then the function
74 * will return an empty array if it determines that the URL is
75 * inside a rewrite path.
77 * @return Array: Any query arguments found in path matches.
79 public static function getPathInfo( $want = 'all' ) {
80 global $wgUsePathInfo;
81 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
82 // And also by Apache 2.x, double slashes are converted to single slashes.
83 // So we will use REQUEST_URI if possible.
84 $matches = array();
85 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
86 // Slurp out the path portion to examine...
87 $url = $_SERVER['REQUEST_URI'];
88 if ( !preg_match( '!^https?://!', $url ) ) {
89 $url = 'http://unused' . $url;
91 wfSuppressWarnings();
92 $a = parse_url( $url );
93 wfRestoreWarnings();
94 if( $a ) {
95 $path = isset( $a['path'] ) ? $a['path'] : '';
97 global $wgScript;
98 if( $path == $wgScript && $want !== 'all' ) {
99 // Script inside a rewrite path?
100 // Abort to keep from breaking...
101 return $matches;
104 $router = new PathRouter;
106 // Raw PATH_INFO style
107 $router->add( "$wgScript/$1" );
109 if( isset( $_SERVER['SCRIPT_NAME'] )
110 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] ) )
112 # Check for SCRIPT_NAME, we handle index.php explicitly
113 # But we do have some other .php files such as img_auth.php
114 # Don't let root article paths clober the parsing for them
115 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
118 global $wgArticlePath;
119 if( $wgArticlePath ) {
120 $router->add( $wgArticlePath );
123 global $wgActionPaths;
124 if( $wgActionPaths ) {
125 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
128 global $wgVariantArticlePath, $wgContLang;
129 if( $wgVariantArticlePath ) {
130 $router->add( $wgVariantArticlePath,
131 array( 'variant' => '$2' ),
132 array( '$2' => $wgContLang->getVariants() )
136 wfRunHooks( 'WebRequestPathInfoRouter', array( $router ) );
138 $matches = $router->parse( $path );
140 } elseif ( $wgUsePathInfo ) {
141 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
142 // Mangled PATH_INFO
143 // http://bugs.php.net/bug.php?id=31892
144 // Also reported when ini_get('cgi.fix_pathinfo')==false
145 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
147 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
148 // Regular old PATH_INFO yay
149 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
153 return $matches;
157 * Work out an appropriate URL prefix containing scheme and host, based on
158 * information detected from $_SERVER
160 * @return string
162 public static function detectServer() {
163 list( $proto, $stdPort ) = self::detectProtocolAndStdPort();
165 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
166 $host = 'localhost';
167 $port = $stdPort;
168 foreach ( $varNames as $varName ) {
169 if ( !isset( $_SERVER[$varName] ) ) {
170 continue;
172 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
173 if ( !$parts ) {
174 // Invalid, do not use
175 continue;
177 $host = $parts[0];
178 if ( $parts[1] === false ) {
179 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
180 $port = $_SERVER['SERVER_PORT'];
181 } // else leave it as $stdPort
182 } else {
183 $port = $parts[1];
185 break;
188 return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
192 * @return array
194 public static function detectProtocolAndStdPort() {
195 if ( ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ||
196 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
197 $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) ) {
198 $arr = array( 'https', 443 );
199 } else {
200 $arr = array( 'http', 80 );
202 return $arr;
206 * @return string
208 public static function detectProtocol() {
209 list( $proto, ) = self::detectProtocolAndStdPort();
210 return $proto;
214 * Check for title, action, and/or variant data in the URL
215 * and interpolate it into the GET variables.
216 * This should only be run after $wgContLang is available,
217 * as we may need the list of language variants to determine
218 * available variant URLs.
220 public function interpolateTitle() {
221 // bug 16019: title interpolation on API queries is useless and sometimes harmful
222 if ( defined( 'MW_API' ) ) {
223 return;
226 $matches = self::getPathInfo( 'title' );
227 foreach( $matches as $key => $val ) {
228 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
233 * URL rewriting function; tries to extract page title and,
234 * optionally, one other fixed parameter value from a URL path.
236 * @param string $path the URL path given from the client
237 * @param array $bases one or more URLs, optionally with $1 at the end
238 * @param string $key if provided, the matching key in $bases will be
239 * passed on as the value of this URL parameter
240 * @return array of URL variables to interpolate; empty if no match
242 static function extractTitle( $path, $bases, $key = false ) {
243 foreach( (array)$bases as $keyValue => $base ) {
244 // Find the part after $wgArticlePath
245 $base = str_replace( '$1', '', $base );
246 $baseLen = strlen( $base );
247 if( substr( $path, 0, $baseLen ) == $base ) {
248 $raw = substr( $path, $baseLen );
249 if( $raw !== '' ) {
250 $matches = array( 'title' => rawurldecode( $raw ) );
251 if( $key ) {
252 $matches[$key] = $keyValue;
254 return $matches;
258 return array();
262 * Recursively strips slashes from the given array;
263 * used for undoing the evil that is magic_quotes_gpc.
265 * @param array $arr will be modified
266 * @param bool $topLevel Specifies if the array passed is from the top
267 * level of the source. In PHP5 magic_quotes only escapes the first level
268 * of keys that belong to an array.
269 * @return array the original array
270 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
272 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
273 $clean = array();
274 foreach( $arr as $key => $val ) {
275 if( is_array( $val ) ) {
276 $cleanKey = $topLevel ? stripslashes( $key ) : $key;
277 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
278 } else {
279 $cleanKey = stripslashes( $key );
280 $clean[$cleanKey] = stripslashes( $val );
283 $arr = $clean;
284 return $arr;
288 * If magic_quotes_gpc option is on, run the global arrays
289 * through fix_magic_quotes to strip out the stupid slashes.
290 * WARNING: This should only be done once! Running a second
291 * time could damage the values.
293 private function checkMagicQuotes() {
294 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
295 && get_magic_quotes_gpc();
296 if( $mustFixQuotes ) {
297 $this->fix_magic_quotes( $_COOKIE );
298 $this->fix_magic_quotes( $_ENV );
299 $this->fix_magic_quotes( $_GET );
300 $this->fix_magic_quotes( $_POST );
301 $this->fix_magic_quotes( $_REQUEST );
302 $this->fix_magic_quotes( $_SERVER );
307 * Recursively normalizes UTF-8 strings in the given array.
309 * @param $data string|array
310 * @return array|string cleaned-up version of the given
311 * @private
313 function normalizeUnicode( $data ) {
314 if( is_array( $data ) ) {
315 foreach( $data as $key => $val ) {
316 $data[$key] = $this->normalizeUnicode( $val );
318 } else {
319 global $wgContLang;
320 $data = isset( $wgContLang ) ? $wgContLang->normalize( $data ) : UtfNormal::cleanUp( $data );
322 return $data;
326 * Fetch a value from the given array or return $default if it's not set.
328 * @param $arr Array
329 * @param $name String
330 * @param $default Mixed
331 * @return mixed
333 private function getGPCVal( $arr, $name, $default ) {
334 # PHP is so nice to not touch input data, except sometimes:
335 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
336 # Work around PHP *feature* to avoid *bugs* elsewhere.
337 $name = strtr( $name, '.', '_' );
338 if( isset( $arr[$name] ) ) {
339 global $wgContLang;
340 $data = $arr[$name];
341 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
342 # Check for alternate/legacy character encoding.
343 if( isset( $wgContLang ) ) {
344 $data = $wgContLang->checkTitleEncoding( $data );
347 $data = $this->normalizeUnicode( $data );
348 return $data;
349 } else {
350 taint( $default );
351 return $default;
356 * Fetch a scalar from the input or return $default if it's not set.
357 * Returns a string. Arrays are discarded. Useful for
358 * non-freeform text inputs (e.g. predefined internal text keys
359 * selected by a drop-down menu). For freeform input, see getText().
361 * @param $name String
362 * @param string $default optional default (or NULL)
363 * @return String
365 public function getVal( $name, $default = null ) {
366 $val = $this->getGPCVal( $this->data, $name, $default );
367 if( is_array( $val ) ) {
368 $val = $default;
370 if( is_null( $val ) ) {
371 return $val;
372 } else {
373 return (string)$val;
378 * Set an arbitrary value into our get/post data.
380 * @param string $key key name to use
381 * @param $value Mixed: value to set
382 * @return Mixed: old value if one was present, null otherwise
384 public function setVal( $key, $value ) {
385 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
386 $this->data[$key] = $value;
387 return $ret;
391 * Unset an arbitrary value from our get/post data.
393 * @param string $key key name to use
394 * @return Mixed: old value if one was present, null otherwise
396 public function unsetVal( $key ) {
397 if ( !isset( $this->data[$key] ) ) {
398 $ret = null;
399 } else {
400 $ret = $this->data[$key];
401 unset( $this->data[$key] );
403 return $ret;
407 * Fetch an array from the input or return $default if it's not set.
408 * If source was scalar, will return an array with a single element.
409 * If no source and no default, returns NULL.
411 * @param $name String
412 * @param array $default optional default (or NULL)
413 * @return Array
415 public function getArray( $name, $default = null ) {
416 $val = $this->getGPCVal( $this->data, $name, $default );
417 if( is_null( $val ) ) {
418 return null;
419 } else {
420 return (array)$val;
425 * Fetch an array of integers, or return $default if it's not set.
426 * If source was scalar, will return an array with a single element.
427 * If no source and no default, returns NULL.
428 * If an array is returned, contents are guaranteed to be integers.
430 * @param $name String
431 * @param array $default option default (or NULL)
432 * @return Array of ints
434 public function getIntArray( $name, $default = null ) {
435 $val = $this->getArray( $name, $default );
436 if( is_array( $val ) ) {
437 $val = array_map( 'intval', $val );
439 return $val;
443 * Fetch an integer value from the input or return $default if not set.
444 * Guaranteed to return an integer; non-numeric input will typically
445 * return 0.
447 * @param $name String
448 * @param $default Integer
449 * @return Integer
451 public function getInt( $name, $default = 0 ) {
452 return intval( $this->getVal( $name, $default ) );
456 * Fetch an integer value from the input or return null if empty.
457 * Guaranteed to return an integer or null; non-numeric input will
458 * typically return null.
460 * @param $name String
461 * @return Integer
463 public function getIntOrNull( $name ) {
464 $val = $this->getVal( $name );
465 return is_numeric( $val )
466 ? intval( $val )
467 : null;
471 * Fetch a boolean value from the input or return $default if not set.
472 * Guaranteed to return true or false, with normal PHP semantics for
473 * boolean interpretation of strings.
475 * @param $name String
476 * @param $default Boolean
477 * @return Boolean
479 public function getBool( $name, $default = false ) {
480 return (bool)$this->getVal( $name, $default );
484 * Fetch a boolean value from the input or return $default if not set.
485 * Unlike getBool, the string "false" will result in boolean false, which is
486 * useful when interpreting information sent from JavaScript.
488 * @param $name String
489 * @param $default Boolean
490 * @return Boolean
492 public function getFuzzyBool( $name, $default = false ) {
493 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
497 * Return true if the named value is set in the input, whatever that
498 * value is (even "0"). Return false if the named value is not set.
499 * Example use is checking for the presence of check boxes in forms.
501 * @param $name String
502 * @return Boolean
504 public function getCheck( $name ) {
505 # Checkboxes and buttons are only present when clicked
506 # Presence connotes truth, absence false
507 return $this->getVal( $name, null ) !== null;
511 * Fetch a text string from the given array or return $default if it's not
512 * set. Carriage returns are stripped from the text, and with some language
513 * modules there is an input transliteration applied. This should generally
514 * be used for form "<textarea>" and "<input>" fields. Used for
515 * user-supplied freeform text input (for which input transformations may
516 * be required - e.g. Esperanto x-coding).
518 * @param $name String
519 * @param string $default optional
520 * @return String
522 public function getText( $name, $default = '' ) {
523 global $wgContLang;
524 $val = $this->getVal( $name, $default );
525 return str_replace( "\r\n", "\n",
526 $wgContLang->recodeInput( $val ) );
530 * Extracts the given named values into an array.
531 * If no arguments are given, returns all input values.
532 * No transformation is performed on the values.
534 * @return array
536 public function getValues() {
537 $names = func_get_args();
538 if ( count( $names ) == 0 ) {
539 $names = array_keys( $this->data );
542 $retVal = array();
543 foreach ( $names as $name ) {
544 $value = $this->getGPCVal( $this->data, $name, null );
545 if ( !is_null( $value ) ) {
546 $retVal[$name] = $value;
549 return $retVal;
553 * Returns the names of all input values excluding those in $exclude.
555 * @param $exclude Array
556 * @return array
558 public function getValueNames( $exclude = array() ) {
559 return array_diff( array_keys( $this->getValues() ), $exclude );
563 * Get the values passed in the query string.
564 * No transformation is performed on the values.
566 * @return Array
568 public function getQueryValues() {
569 return $_GET;
573 * Get the HTTP method used for this request.
575 * @return String
577 public function getMethod() {
578 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
582 * Returns true if the present request was reached by a POST operation,
583 * false otherwise (GET, HEAD, or command-line).
585 * Note that values retrieved by the object may come from the
586 * GET URL etc even on a POST request.
588 * @return Boolean
590 public function wasPosted() {
591 return $this->getMethod() == 'POST';
595 * Returns true if there is a session cookie set.
596 * This does not necessarily mean that the user is logged in!
598 * If you want to check for an open session, use session_id()
599 * instead; that will also tell you if the session was opened
600 * during the current request (in which case the cookie will
601 * be sent back to the client at the end of the script run).
603 * @return Boolean
605 public function checkSessionCookie() {
606 return isset( $_COOKIE[session_name()] );
610 * Get a cookie from the $_COOKIE jar
612 * @param string $key the name of the cookie
613 * @param string $prefix a prefix to use for the cookie name, if not $wgCookiePrefix
614 * @param $default Mixed: what to return if the value isn't found
615 * @return Mixed: cookie value or $default if the cookie not set
617 public function getCookie( $key, $prefix = null, $default = null ) {
618 if( $prefix === null ) {
619 global $wgCookiePrefix;
620 $prefix = $wgCookiePrefix;
622 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
626 * Return the path and query string portion of the request URI.
627 * This will be suitable for use as a relative link in HTML output.
629 * @throws MWException
630 * @return String
632 public function getRequestURL() {
633 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
634 $base = $_SERVER['REQUEST_URI'];
635 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
636 // Probably IIS; doesn't set REQUEST_URI
637 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
638 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
639 $base = $_SERVER['SCRIPT_NAME'];
640 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
641 $base .= '?' . $_SERVER['QUERY_STRING'];
643 } else {
644 // This shouldn't happen!
645 throw new MWException( "Web server doesn't provide either " .
646 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
647 "of your web server configuration to http://bugzilla.wikimedia.org/" );
649 // User-agents should not send a fragment with the URI, but
650 // if they do, and the web server passes it on to us, we
651 // need to strip it or we get false-positive redirect loops
652 // or weird output URLs
653 $hash = strpos( $base, '#' );
654 if( $hash !== false ) {
655 $base = substr( $base, 0, $hash );
658 if( $base[0] == '/' ) {
659 // More than one slash will look like it is protocol relative
660 return preg_replace( '!^/+!', '/', $base );
661 } else {
662 // We may get paths with a host prepended; strip it.
663 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
668 * Return the request URI with the canonical service and hostname, path,
669 * and query string. This will be suitable for use as an absolute link
670 * in HTML or other output.
672 * If $wgServer is protocol-relative, this will return a fully
673 * qualified URL with the protocol that was used for this request.
675 * @return String
677 public function getFullRequestURL() {
678 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
682 * Take an arbitrary query and rewrite the present URL to include it
683 * @param string $query query string fragment; do not include initial '?'
685 * @return String
687 public function appendQuery( $query ) {
688 return $this->appendQueryArray( wfCgiToArray( $query ) );
692 * HTML-safe version of appendQuery().
693 * @deprecated: Deprecated in 1.20, warnings in 1.21, remove in 1.22.
695 * @param string $query query string fragment; do not include initial '?'
696 * @return String
698 public function escapeAppendQuery( $query ) {
699 return htmlspecialchars( $this->appendQuery( $query ) );
703 * @param $key
704 * @param $value
705 * @param $onlyquery bool
706 * @return String
708 public function appendQueryValue( $key, $value, $onlyquery = false ) {
709 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
713 * Appends or replaces value of query variables.
715 * @param array $array of values to replace/add to query
716 * @param bool $onlyquery whether to only return the query string and not
717 * the complete URL
718 * @return String
720 public function appendQueryArray( $array, $onlyquery = false ) {
721 global $wgTitle;
722 $newquery = $this->getQueryValues();
723 unset( $newquery['title'] );
724 $newquery = array_merge( $newquery, $array );
725 $query = wfArrayToCgi( $newquery );
726 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
730 * Check for limit and offset parameters on the input, and return sensible
731 * defaults if not given. The limit must be positive and is capped at 5000.
732 * Offset must be positive but is not capped.
734 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
735 * @param string $optionname to specify an option other than rclimit to pull from.
736 * @return array first element is limit, second is offset
738 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
739 global $wgUser;
741 $limit = $this->getInt( 'limit', 0 );
742 if( $limit < 0 ) {
743 $limit = 0;
745 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
746 $limit = $wgUser->getIntOption( $optionname );
748 if( $limit <= 0 ) {
749 $limit = $deflimit;
751 if( $limit > 5000 ) {
752 $limit = 5000; # We have *some* limits...
755 $offset = $this->getInt( 'offset', 0 );
756 if( $offset < 0 ) {
757 $offset = 0;
760 return array( $limit, $offset );
764 * Return the path to the temporary file where PHP has stored the upload.
766 * @param $key String:
767 * @return string or NULL if no such file.
769 public function getFileTempname( $key ) {
770 $file = new WebRequestUpload( $this, $key );
771 return $file->getTempName();
775 * Return the size of the upload, or 0.
777 * @deprecated since 1.17
778 * @param $key String:
779 * @return integer
781 public function getFileSize( $key ) {
782 wfDeprecated( __METHOD__, '1.17' );
783 $file = new WebRequestUpload( $this, $key );
784 return $file->getSize();
788 * Return the upload error or 0
790 * @param $key String:
791 * @return integer
793 public function getUploadError( $key ) {
794 $file = new WebRequestUpload( $this, $key );
795 return $file->getError();
799 * Return the original filename of the uploaded file, as reported by
800 * the submitting user agent. HTML-style character entities are
801 * interpreted and normalized to Unicode normalization form C, in part
802 * to deal with weird input from Safari with non-ASCII filenames.
804 * Other than this the name is not verified for being a safe filename.
806 * @param $key String:
807 * @return string or NULL if no such file.
809 public function getFileName( $key ) {
810 $file = new WebRequestUpload( $this, $key );
811 return $file->getName();
815 * Return a WebRequestUpload object corresponding to the key
817 * @param $key string
818 * @return WebRequestUpload
820 public function getUpload( $key ) {
821 return new WebRequestUpload( $this, $key );
825 * Return a handle to WebResponse style object, for setting cookies,
826 * headers and other stuff, for Request being worked on.
828 * @return WebResponse
830 public function response() {
831 /* Lazy initialization of response object for this request */
832 if ( !is_object( $this->response ) ) {
833 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
834 $this->response = new $class();
836 return $this->response;
840 * Initialise the header list
842 private function initHeaders() {
843 if ( count( $this->headers ) ) {
844 return;
847 if ( function_exists( 'apache_request_headers' ) ) {
848 foreach ( apache_request_headers() as $tempName => $tempValue ) {
849 $this->headers[strtoupper( $tempName )] = $tempValue;
851 } else {
852 foreach ( $_SERVER as $name => $value ) {
853 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
854 $name = str_replace( '_', '-', substr( $name, 5 ) );
855 $this->headers[$name] = $value;
856 } elseif ( $name === 'CONTENT_LENGTH' ) {
857 $this->headers['CONTENT-LENGTH'] = $value;
864 * Get an array containing all request headers
866 * @return Array mapping header name to its value
868 public function getAllHeaders() {
869 $this->initHeaders();
870 return $this->headers;
874 * Get a request header, or false if it isn't set
875 * @param string $name case-insensitive header name
877 * @return string|bool False on failure
879 public function getHeader( $name ) {
880 $this->initHeaders();
881 $name = strtoupper( $name );
882 if ( isset( $this->headers[$name] ) ) {
883 return $this->headers[$name];
884 } else {
885 return false;
890 * Get data from $_SESSION
892 * @param string $key name of key in $_SESSION
893 * @return Mixed
895 public function getSessionData( $key ) {
896 if( !isset( $_SESSION[$key] ) ) {
897 return null;
899 return $_SESSION[$key];
903 * Set session data
905 * @param string $key name of key in $_SESSION
906 * @param $data Mixed
908 public function setSessionData( $key, $data ) {
909 $_SESSION[$key] = $data;
913 * Check if Internet Explorer will detect an incorrect cache extension in
914 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
915 * message or redirect to a safer URL. Returns true if the URL is OK, and
916 * false if an error message has been shown and the request should be aborted.
918 * @param $extWhitelist array
919 * @throws HttpError
920 * @return bool
922 public function checkUrlExtension( $extWhitelist = array() ) {
923 global $wgScriptExtension;
924 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
925 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
926 if ( !$this->wasPosted() ) {
927 $newUrl = IEUrlExtension::fixUrlForIE6(
928 $this->getFullRequestURL(), $extWhitelist );
929 if ( $newUrl !== false ) {
930 $this->doSecurityRedirect( $newUrl );
931 return false;
934 throw new HttpError( 403,
935 'Invalid file extension found in the path info or query string.' );
937 return true;
941 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
942 * IE 6. Returns true if it was successful, false otherwise.
944 * @param $url string
945 * @return bool
947 protected function doSecurityRedirect( $url ) {
948 header( 'Location: ' . $url );
949 header( 'Content-Type: text/html' );
950 $encUrl = htmlspecialchars( $url );
951 echo <<<HTML
952 <html>
953 <head>
954 <title>Security redirect</title>
955 </head>
956 <body>
957 <h1>Security redirect</h1>
959 We can't serve non-HTML content from the URL you have requested, because
960 Internet Explorer would interpret it as an incorrect and potentially dangerous
961 content type.</p>
962 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the URL you have requested, except that
963 "&amp;*" is appended. This prevents Internet Explorer from seeing a bogus file
964 extension.
965 </p>
966 </body>
967 </html>
968 HTML;
969 echo "\n";
970 return true;
974 * Returns true if the PATH_INFO ends with an extension other than a script
975 * extension. This could confuse IE for scripts that send arbitrary data which
976 * is not HTML but may be detected as such.
978 * Various past attempts to use the URL to make this check have generally
979 * run up against the fact that CGI does not provide a standard method to
980 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
981 * but only by prefixing it with the script name and maybe some other stuff,
982 * the extension is not mangled. So this should be a reasonably portable
983 * way to perform this security check.
985 * Also checks for anything that looks like a file extension at the end of
986 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
987 * if there was no dot before the question mark (bug 28235).
989 * @deprecated Use checkUrlExtension().
991 * @param $extWhitelist array
993 * @return bool
995 public function isPathInfoBad( $extWhitelist = array() ) {
996 wfDeprecated( __METHOD__, '1.17' );
997 global $wgScriptExtension;
998 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
999 return IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist );
1003 * Parse the Accept-Language header sent by the client into an array
1004 * @return array array( languageCode => q-value ) sorted by q-value in descending order then
1005 * appearing time in the header in ascending order.
1006 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1007 * This is aligned with rfc2616 section 14.4
1008 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1010 public function getAcceptLang() {
1011 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
1012 $acceptLang = $this->getHeader( 'Accept-Language' );
1013 if ( !$acceptLang ) {
1014 return array();
1017 // Return the language codes in lower case
1018 $acceptLang = strtolower( $acceptLang );
1020 // Break up string into pieces (languages and q factors)
1021 $lang_parse = null;
1022 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})?)?)?/',
1023 $acceptLang, $lang_parse );
1025 if ( !count( $lang_parse[1] ) ) {
1026 return array();
1029 $langcodes = $lang_parse[1];
1030 $qvalues = $lang_parse[4];
1031 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1033 // Set default q factor to 1
1034 foreach ( $indices as $index ) {
1035 if ( $qvalues[$index] === '' ) {
1036 $qvalues[$index] = 1;
1037 } elseif ( $qvalues[$index] == 0 ) {
1038 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1042 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1043 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1045 // Create a list like "en" => 0.8
1046 $langs = array_combine( $langcodes, $qvalues );
1048 return $langs;
1052 * Fetch the raw IP from the request
1054 * @since 1.19
1056 * @throws MWException
1057 * @return String
1059 protected function getRawIP() {
1060 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1061 return null;
1064 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1065 throw new MWException( __METHOD__ . " : Could not determine the remote IP address due to multiple values." );
1066 } else {
1067 $ipchain = $_SERVER['REMOTE_ADDR'];
1070 return IP::canonicalize( $ipchain );
1074 * Work out the IP address based on various globals
1075 * For trusted proxies, use the XFF client IP (first of the chain)
1077 * @since 1.19
1079 * @throws MWException
1080 * @return string
1082 public function getIP() {
1083 global $wgUsePrivateIPs;
1085 # Return cached result
1086 if ( $this->ip !== null ) {
1087 return $this->ip;
1090 # collect the originating ips
1091 $ip = $this->getRawIP();
1093 # Append XFF
1094 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1095 if ( $forwardedFor !== false ) {
1096 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1097 $ipchain = array_reverse( $ipchain );
1098 if ( $ip ) {
1099 array_unshift( $ipchain, $ip );
1102 # Step through XFF list and find the last address in the list which is a trusted server
1103 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1104 foreach ( $ipchain as $i => $curIP ) {
1105 $curIP = IP::canonicalize( $curIP );
1106 if ( wfIsTrustedProxy( $curIP ) ) {
1107 if ( isset( $ipchain[$i + 1] ) ) {
1108 if ( $wgUsePrivateIPs || IP::isPublic( $ipchain[$i + 1] ) ) {
1109 $ip = $ipchain[$i + 1];
1112 } else {
1113 break;
1118 # Allow extensions to improve our guess
1119 wfRunHooks( 'GetIP', array( &$ip ) );
1121 if ( !$ip ) {
1122 throw new MWException( "Unable to determine IP" );
1125 wfDebug( "IP: $ip\n" );
1126 $this->ip = $ip;
1127 return $ip;
1131 * @param string $ip
1132 * @return void
1133 * @since 1.21
1135 public function setIP( $ip ) {
1136 $this->ip = $ip;
1141 * Object to access the $_FILES array
1143 class WebRequestUpload {
1144 protected $request;
1145 protected $doesExist;
1146 protected $fileInfo;
1149 * Constructor. Should only be called by WebRequest
1151 * @param $request WebRequest The associated request
1152 * @param string $key Key in $_FILES array (name of form field)
1154 public function __construct( $request, $key ) {
1155 $this->request = $request;
1156 $this->doesExist = isset( $_FILES[$key] );
1157 if ( $this->doesExist ) {
1158 $this->fileInfo = $_FILES[$key];
1163 * Return whether a file with this name was uploaded.
1165 * @return bool
1167 public function exists() {
1168 return $this->doesExist;
1172 * Return the original filename of the uploaded file
1174 * @return mixed Filename or null if non-existent
1176 public function getName() {
1177 if ( !$this->exists() ) {
1178 return null;
1181 global $wgContLang;
1182 $name = $this->fileInfo['name'];
1184 # Safari sends filenames in HTML-encoded Unicode form D...
1185 # Horrid and evil! Let's try to make some kind of sense of it.
1186 $name = Sanitizer::decodeCharReferences( $name );
1187 $name = $wgContLang->normalize( $name );
1188 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1189 return $name;
1193 * Return the file size of the uploaded file
1195 * @return int File size or zero if non-existent
1197 public function getSize() {
1198 if ( !$this->exists() ) {
1199 return 0;
1202 return $this->fileInfo['size'];
1206 * Return the path to the temporary file
1208 * @return mixed Path or null if non-existent
1210 public function getTempName() {
1211 if ( !$this->exists() ) {
1212 return null;
1215 return $this->fileInfo['tmp_name'];
1219 * Return the upload error. See link for explanation
1220 * http://www.php.net/manual/en/features.file-upload.errors.php
1222 * @return int One of the UPLOAD_ constants, 0 if non-existent
1224 public function getError() {
1225 if ( !$this->exists() ) {
1226 return 0; # UPLOAD_ERR_OK
1229 return $this->fileInfo['error'];
1233 * Returns whether this upload failed because of overflow of a maximum set
1234 * in php.ini
1236 * @return bool
1238 public function isIniSizeOverflow() {
1239 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1240 # PHP indicated that upload_max_filesize is exceeded
1241 return true;
1244 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1245 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1246 # post_max_size is exceeded
1247 return true;
1250 return false;
1255 * WebRequest clone which takes values from a provided array.
1257 * @ingroup HTTP
1259 class FauxRequest extends WebRequest {
1260 private $wasPosted = false;
1261 private $session = array();
1264 * @param array $data of *non*-urlencoded key => value pairs, the
1265 * fake GET/POST values
1266 * @param bool $wasPosted whether to treat the data as POST
1267 * @param $session Mixed: session array or null
1268 * @throws MWException
1270 public function __construct( $data = array(), $wasPosted = false, $session = null ) {
1271 if( is_array( $data ) ) {
1272 $this->data = $data;
1273 } else {
1274 throw new MWException( "FauxRequest() got bogus data" );
1276 $this->wasPosted = $wasPosted;
1277 if( $session ) {
1278 $this->session = $session;
1283 * @param $method string
1284 * @throws MWException
1286 private function notImplemented( $method ) {
1287 throw new MWException( "{$method}() not implemented" );
1291 * @param $name string
1292 * @param $default string
1293 * @return string
1295 public function getText( $name, $default = '' ) {
1296 # Override; don't recode since we're using internal data
1297 return (string)$this->getVal( $name, $default );
1301 * @return Array
1303 public function getValues() {
1304 return $this->data;
1308 * @return array
1310 public function getQueryValues() {
1311 if ( $this->wasPosted ) {
1312 return array();
1313 } else {
1314 return $this->data;
1318 public function getMethod() {
1319 return $this->wasPosted ? 'POST' : 'GET';
1323 * @return bool
1325 public function wasPosted() {
1326 return $this->wasPosted;
1329 public function getCookie( $key, $prefix = null, $default = null ) {
1330 return $default;
1333 public function checkSessionCookie() {
1334 return false;
1337 public function getRequestURL() {
1338 $this->notImplemented( __METHOD__ );
1342 * @param $name
1343 * @return bool|string
1345 public function getHeader( $name ) {
1346 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1350 * @param $name string
1351 * @param $val string
1353 public function setHeader( $name, $val ) {
1354 $this->headers[$name] = $val;
1358 * @param $key
1359 * @return mixed
1361 public function getSessionData( $key ) {
1362 if( isset( $this->session[$key] ) ) {
1363 return $this->session[$key];
1365 return null;
1369 * @param $key
1370 * @param $data
1372 public function setSessionData( $key, $data ) {
1373 $this->session[$key] = $data;
1377 * @return array|Mixed|null
1379 public function getSessionArray() {
1380 return $this->session;
1384 * @param array $extWhitelist
1385 * @return bool
1387 public function isPathInfoBad( $extWhitelist = array() ) {
1388 return false;
1392 * @param array $extWhitelist
1393 * @return bool
1395 public function checkUrlExtension( $extWhitelist = array() ) {
1396 return true;
1400 * @return string
1402 protected function getRawIP() {
1403 return '127.0.0.1';
1408 * Similar to FauxRequest, but only fakes URL parameters and method
1409 * (POST or GET) and use the base request for the remaining stuff
1410 * (cookies, session and headers).
1412 * @ingroup HTTP
1413 * @since 1.19
1415 class DerivativeRequest extends FauxRequest {
1416 private $base;
1418 public function __construct( WebRequest $base, $data, $wasPosted = false ) {
1419 $this->base = $base;
1420 parent::__construct( $data, $wasPosted );
1423 public function getCookie( $key, $prefix = null, $default = null ) {
1424 return $this->base->getCookie( $key, $prefix, $default );
1427 public function checkSessionCookie() {
1428 return $this->base->checkSessionCookie();
1431 public function getHeader( $name ) {
1432 return $this->base->getHeader( $name );
1435 public function getAllHeaders() {
1436 return $this->base->getAllHeaders();
1439 public function getSessionData( $key ) {
1440 return $this->base->getSessionData( $key );
1443 public function setSessionData( $key, $data ) {
1444 $this->base->setSessionData( $key, $data );
1447 public function getAcceptLang() {
1448 return $this->base->getAcceptLang();
1451 public function getIP() {
1452 return $this->base->getIP();