Merge "Import BatchRowUpdate classes from Echo"
[mediawiki.git] / includes / WebRequest.php
blob03410ccc9f8889ad6bf8a57f9587c9fabec66262
1 <?php
2 /**
3 * Deal with importing all those nasty globals and things
5 * Copyright © 2003 Brion Vibber <brion@pobox.com>
6 * https://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 stripping illegal input characters and
29 * 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 * Flag to make WebRequest::getHeader return an array of values.
43 * @since 1.26
45 const GETHEADER_LIST = 1;
47 /**
48 * Lazy-init response object
49 * @var WebResponse
51 private $response;
53 /**
54 * Cached client IP address
55 * @var string
57 private $ip;
59 /**
60 * The timestamp of the start of the request, with microsecond precision.
61 * @var float
63 protected $requestTime;
65 /**
66 * Cached URL protocol
67 * @var string
69 protected $protocol;
71 public function __construct() {
72 $this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
73 ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
75 // POST overrides GET data
76 // We don't use $_REQUEST here to avoid interference from cookies...
77 $this->data = $_POST + $_GET;
80 /**
81 * Extract relevant query arguments from the http request uri's path
82 * to be merged with the normal php provided query arguments.
83 * Tries to use the REQUEST_URI data if available and parses it
84 * according to the wiki's configuration looking for any known pattern.
86 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
87 * provided by the server if any and use that to set a 'title' parameter.
89 * @param string $want If this is not 'all', then the function
90 * will return an empty array if it determines that the URL is
91 * inside a rewrite path.
93 * @return array Any query arguments found in path matches.
95 public static function getPathInfo( $want = 'all' ) {
96 global $wgUsePathInfo;
97 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
98 // And also by Apache 2.x, double slashes are converted to single slashes.
99 // So we will use REQUEST_URI if possible.
100 $matches = array();
101 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
102 // Slurp out the path portion to examine...
103 $url = $_SERVER['REQUEST_URI'];
104 if ( !preg_match( '!^https?://!', $url ) ) {
105 $url = 'http://unused' . $url;
107 MediaWiki\suppressWarnings();
108 $a = parse_url( $url );
109 MediaWiki\restoreWarnings();
110 if ( $a ) {
111 $path = isset( $a['path'] ) ? $a['path'] : '';
113 global $wgScript;
114 if ( $path == $wgScript && $want !== 'all' ) {
115 // Script inside a rewrite path?
116 // Abort to keep from breaking...
117 return $matches;
120 $router = new PathRouter;
122 // Raw PATH_INFO style
123 $router->add( "$wgScript/$1" );
125 if ( isset( $_SERVER['SCRIPT_NAME'] )
126 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
128 # Check for SCRIPT_NAME, we handle index.php explicitly
129 # But we do have some other .php files such as img_auth.php
130 # Don't let root article paths clober the parsing for them
131 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
134 global $wgArticlePath;
135 if ( $wgArticlePath ) {
136 $router->add( $wgArticlePath );
139 global $wgActionPaths;
140 if ( $wgActionPaths ) {
141 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
144 global $wgVariantArticlePath, $wgContLang;
145 if ( $wgVariantArticlePath ) {
146 $router->add( $wgVariantArticlePath,
147 array( 'variant' => '$2' ),
148 array( '$2' => $wgContLang->getVariants() )
152 Hooks::run( 'WebRequestPathInfoRouter', array( $router ) );
154 $matches = $router->parse( $path );
156 } elseif ( $wgUsePathInfo ) {
157 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
158 // Mangled PATH_INFO
159 // http://bugs.php.net/bug.php?id=31892
160 // Also reported when ini_get('cgi.fix_pathinfo')==false
161 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
163 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
164 // Regular old PATH_INFO yay
165 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
169 return $matches;
173 * Work out an appropriate URL prefix containing scheme and host, based on
174 * information detected from $_SERVER
176 * @return string
178 public static function detectServer() {
179 global $wgAssumeProxiesUseDefaultProtocolPorts;
181 $proto = self::detectProtocol();
182 $stdPort = $proto === 'https' ? 443 : 80;
184 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
185 $host = 'localhost';
186 $port = $stdPort;
187 foreach ( $varNames as $varName ) {
188 if ( !isset( $_SERVER[$varName] ) ) {
189 continue;
192 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
193 if ( !$parts ) {
194 // Invalid, do not use
195 continue;
198 $host = $parts[0];
199 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
200 // Bug 70021: Assume that upstream proxy is running on the default
201 // port based on the protocol. We have no reliable way to determine
202 // the actual port in use upstream.
203 $port = $stdPort;
204 } elseif ( $parts[1] === false ) {
205 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
206 $port = $_SERVER['SERVER_PORT'];
207 } // else leave it as $stdPort
208 } else {
209 $port = $parts[1];
211 break;
214 return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
218 * Detect the protocol from $_SERVER.
219 * This is for use prior to Setup.php, when no WebRequest object is available.
220 * At other times, use the non-static function getProtocol().
222 * @return array
224 public static function detectProtocol() {
225 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
226 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
227 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
228 return 'https';
229 } else {
230 return 'http';
235 * Get the number of seconds to have elapsed since request start,
236 * in fractional seconds, with microsecond resolution.
238 * @return float
239 * @since 1.25
241 public function getElapsedTime() {
242 return microtime( true ) - $this->requestTime;
246 * Get the current URL protocol (http or https)
247 * @return string
249 public function getProtocol() {
250 if ( $this->protocol === null ) {
251 $this->protocol = self::detectProtocol();
253 return $this->protocol;
257 * Check for title, action, and/or variant data in the URL
258 * and interpolate it into the GET variables.
259 * This should only be run after $wgContLang is available,
260 * as we may need the list of language variants to determine
261 * available variant URLs.
263 public function interpolateTitle() {
264 // bug 16019: title interpolation on API queries is useless and sometimes harmful
265 if ( defined( 'MW_API' ) ) {
266 return;
269 $matches = self::getPathInfo( 'title' );
270 foreach ( $matches as $key => $val ) {
271 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
276 * URL rewriting function; tries to extract page title and,
277 * optionally, one other fixed parameter value from a URL path.
279 * @param string $path The URL path given from the client
280 * @param array $bases One or more URLs, optionally with $1 at the end
281 * @param string $key If provided, the matching key in $bases will be
282 * passed on as the value of this URL parameter
283 * @return array Array of URL variables to interpolate; empty if no match
285 static function extractTitle( $path, $bases, $key = false ) {
286 foreach ( (array)$bases as $keyValue => $base ) {
287 // Find the part after $wgArticlePath
288 $base = str_replace( '$1', '', $base );
289 $baseLen = strlen( $base );
290 if ( substr( $path, 0, $baseLen ) == $base ) {
291 $raw = substr( $path, $baseLen );
292 if ( $raw !== '' ) {
293 $matches = array( 'title' => rawurldecode( $raw ) );
294 if ( $key ) {
295 $matches[$key] = $keyValue;
297 return $matches;
301 return array();
305 * Recursively normalizes UTF-8 strings in the given array.
307 * @param string|array $data
308 * @return array|string Cleaned-up version of the given
309 * @private
311 function normalizeUnicode( $data ) {
312 if ( is_array( $data ) ) {
313 foreach ( $data as $key => $val ) {
314 $data[$key] = $this->normalizeUnicode( $val );
316 } else {
317 global $wgContLang;
318 $data = isset( $wgContLang ) ? $wgContLang->normalize( $data ) : UtfNormal\Validator::cleanUp( $data );
320 return $data;
324 * Fetch a value from the given array or return $default if it's not set.
326 * @param array $arr
327 * @param string $name
328 * @param mixed $default
329 * @return mixed
331 private function getGPCVal( $arr, $name, $default ) {
332 # PHP is so nice to not touch input data, except sometimes:
333 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
334 # Work around PHP *feature* to avoid *bugs* elsewhere.
335 $name = strtr( $name, '.', '_' );
336 if ( isset( $arr[$name] ) ) {
337 global $wgContLang;
338 $data = $arr[$name];
339 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
340 # Check for alternate/legacy character encoding.
341 if ( isset( $wgContLang ) ) {
342 $data = $wgContLang->checkTitleEncoding( $data );
345 $data = $this->normalizeUnicode( $data );
346 return $data;
347 } else {
348 return $default;
353 * Fetch a scalar from the input or return $default if it's not set.
354 * Returns a string. Arrays are discarded. Useful for
355 * non-freeform text inputs (e.g. predefined internal text keys
356 * selected by a drop-down menu). For freeform input, see getText().
358 * @param string $name
359 * @param string $default Optional default (or null)
360 * @return string
362 public function getVal( $name, $default = null ) {
363 $val = $this->getGPCVal( $this->data, $name, $default );
364 if ( is_array( $val ) ) {
365 $val = $default;
367 if ( is_null( $val ) ) {
368 return $val;
369 } else {
370 return (string)$val;
375 * Set an arbitrary value into our get/post data.
377 * @param string $key Key name to use
378 * @param mixed $value Value to set
379 * @return mixed Old value if one was present, null otherwise
381 public function setVal( $key, $value ) {
382 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
383 $this->data[$key] = $value;
384 return $ret;
388 * Unset an arbitrary value from our get/post data.
390 * @param string $key Key name to use
391 * @return mixed Old value if one was present, null otherwise
393 public function unsetVal( $key ) {
394 if ( !isset( $this->data[$key] ) ) {
395 $ret = null;
396 } else {
397 $ret = $this->data[$key];
398 unset( $this->data[$key] );
400 return $ret;
404 * Fetch an array from the input or return $default if it's not set.
405 * If source was scalar, will return an array with a single element.
406 * If no source and no default, returns null.
408 * @param string $name
409 * @param array $default Optional default (or null)
410 * @return array
412 public function getArray( $name, $default = null ) {
413 $val = $this->getGPCVal( $this->data, $name, $default );
414 if ( is_null( $val ) ) {
415 return null;
416 } else {
417 return (array)$val;
422 * Fetch an array of integers, or return $default if it's not set.
423 * If source was scalar, will return an array with a single element.
424 * If no source and no default, returns null.
425 * If an array is returned, contents are guaranteed to be integers.
427 * @param string $name
428 * @param array $default Option default (or null)
429 * @return array Array of ints
431 public function getIntArray( $name, $default = null ) {
432 $val = $this->getArray( $name, $default );
433 if ( is_array( $val ) ) {
434 $val = array_map( 'intval', $val );
436 return $val;
440 * Fetch an integer value from the input or return $default if not set.
441 * Guaranteed to return an integer; non-numeric input will typically
442 * return 0.
444 * @param string $name
445 * @param int $default
446 * @return int
448 public function getInt( $name, $default = 0 ) {
449 return intval( $this->getVal( $name, $default ) );
453 * Fetch an integer value from the input or return null if empty.
454 * Guaranteed to return an integer or null; non-numeric input will
455 * typically return null.
457 * @param string $name
458 * @return int|null
460 public function getIntOrNull( $name ) {
461 $val = $this->getVal( $name );
462 return is_numeric( $val )
463 ? intval( $val )
464 : null;
468 * Fetch a floating point value from the input or return $default if not set.
469 * Guaranteed to return a float; non-numeric input will typically
470 * return 0.
472 * @since 1.23
473 * @param string $name
474 * @param float $default
475 * @return float
477 public function getFloat( $name, $default = 0.0 ) {
478 return floatval( $this->getVal( $name, $default ) );
482 * Fetch a boolean value from the input or return $default if not set.
483 * Guaranteed to return true or false, with normal PHP semantics for
484 * boolean interpretation of strings.
486 * @param string $name
487 * @param bool $default
488 * @return bool
490 public function getBool( $name, $default = false ) {
491 return (bool)$this->getVal( $name, $default );
495 * Fetch a boolean value from the input or return $default if not set.
496 * Unlike getBool, the string "false" will result in boolean false, which is
497 * useful when interpreting information sent from JavaScript.
499 * @param string $name
500 * @param bool $default
501 * @return bool
503 public function getFuzzyBool( $name, $default = false ) {
504 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
508 * Return true if the named value is set in the input, whatever that
509 * value is (even "0"). Return false if the named value is not set.
510 * Example use is checking for the presence of check boxes in forms.
512 * @param string $name
513 * @return bool
515 public function getCheck( $name ) {
516 # Checkboxes and buttons are only present when clicked
517 # Presence connotes truth, absence false
518 return $this->getVal( $name, null ) !== null;
522 * Fetch a text string from the given array or return $default if it's not
523 * set. Carriage returns are stripped from the text, and with some language
524 * modules there is an input transliteration applied. This should generally
525 * be used for form "<textarea>" and "<input>" fields. Used for
526 * user-supplied freeform text input (for which input transformations may
527 * be required - e.g. Esperanto x-coding).
529 * @param string $name
530 * @param string $default Optional
531 * @return string
533 public function getText( $name, $default = '' ) {
534 global $wgContLang;
535 $val = $this->getVal( $name, $default );
536 return str_replace( "\r\n", "\n",
537 $wgContLang->recodeInput( $val ) );
541 * Extracts the given named values into an array.
542 * If no arguments are given, returns all input values.
543 * No transformation is performed on the values.
545 * @return array
547 public function getValues() {
548 $names = func_get_args();
549 if ( count( $names ) == 0 ) {
550 $names = array_keys( $this->data );
553 $retVal = array();
554 foreach ( $names as $name ) {
555 $value = $this->getGPCVal( $this->data, $name, null );
556 if ( !is_null( $value ) ) {
557 $retVal[$name] = $value;
560 return $retVal;
564 * Returns the names of all input values excluding those in $exclude.
566 * @param array $exclude
567 * @return array
569 public function getValueNames( $exclude = array() ) {
570 return array_diff( array_keys( $this->getValues() ), $exclude );
574 * Get the values passed in the query string.
575 * No transformation is performed on the values.
577 * @return array
579 public function getQueryValues() {
580 return $_GET;
584 * Return the contents of the Query with no decoding. Use when you need to
585 * know exactly what was sent, e.g. for an OAuth signature over the elements.
587 * @return string
589 public function getRawQueryString() {
590 return $_SERVER['QUERY_STRING'];
594 * Return the contents of the POST with no decoding. Use when you need to
595 * know exactly what was sent, e.g. for an OAuth signature over the elements.
597 * @return string
599 public function getRawPostString() {
600 if ( !$this->wasPosted() ) {
601 return '';
603 return $this->getRawInput();
607 * Return the raw request body, with no processing. Cached since some methods
608 * disallow reading the stream more than once. As stated in the php docs, this
609 * does not work with enctype="multipart/form-data".
611 * @return string
613 public function getRawInput() {
614 static $input = null;
615 if ( $input === null ) {
616 $input = file_get_contents( 'php://input' );
618 return $input;
622 * Get the HTTP method used for this request.
624 * @return string
626 public function getMethod() {
627 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
631 * Returns true if the present request was reached by a POST operation,
632 * false otherwise (GET, HEAD, or command-line).
634 * Note that values retrieved by the object may come from the
635 * GET URL etc even on a POST request.
637 * @return bool
639 public function wasPosted() {
640 return $this->getMethod() == 'POST';
644 * Returns true if there is a session cookie set.
645 * This does not necessarily mean that the user is logged in!
647 * If you want to check for an open session, use session_id()
648 * instead; that will also tell you if the session was opened
649 * during the current request (in which case the cookie will
650 * be sent back to the client at the end of the script run).
652 * @return bool
654 public function checkSessionCookie() {
655 return isset( $_COOKIE[session_name()] );
659 * Get a cookie from the $_COOKIE jar
661 * @param string $key The name of the cookie
662 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
663 * @param mixed $default What to return if the value isn't found
664 * @return mixed Cookie value or $default if the cookie not set
666 public function getCookie( $key, $prefix = null, $default = null ) {
667 if ( $prefix === null ) {
668 global $wgCookiePrefix;
669 $prefix = $wgCookiePrefix;
671 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
675 * Return the path and query string portion of the request URI.
676 * This will be suitable for use as a relative link in HTML output.
678 * @throws MWException
679 * @return string
681 public function getRequestURL() {
682 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
683 $base = $_SERVER['REQUEST_URI'];
684 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
685 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
687 // Probably IIS; doesn't set REQUEST_URI
688 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
689 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
690 $base = $_SERVER['SCRIPT_NAME'];
691 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
692 $base .= '?' . $_SERVER['QUERY_STRING'];
694 } else {
695 // This shouldn't happen!
696 throw new MWException( "Web server doesn't provide either " .
697 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
698 "of your web server configuration to https://phabricator.wikimedia.org/" );
700 // User-agents should not send a fragment with the URI, but
701 // if they do, and the web server passes it on to us, we
702 // need to strip it or we get false-positive redirect loops
703 // or weird output URLs
704 $hash = strpos( $base, '#' );
705 if ( $hash !== false ) {
706 $base = substr( $base, 0, $hash );
709 if ( $base[0] == '/' ) {
710 // More than one slash will look like it is protocol relative
711 return preg_replace( '!^/+!', '/', $base );
712 } else {
713 // We may get paths with a host prepended; strip it.
714 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
719 * Return the request URI with the canonical service and hostname, path,
720 * and query string. This will be suitable for use as an absolute link
721 * in HTML or other output.
723 * If $wgServer is protocol-relative, this will return a fully
724 * qualified URL with the protocol that was used for this request.
726 * @return string
728 public function getFullRequestURL() {
729 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
733 * Take an arbitrary query and rewrite the present URL to include it
734 * @deprecated Use appendQueryValue/appendQueryArray instead
735 * @param string $query Query string fragment; do not include initial '?'
736 * @return string
738 public function appendQuery( $query ) {
739 wfDeprecated( __METHOD__, '1.25' );
740 return $this->appendQueryArray( wfCgiToArray( $query ) );
744 * @param string $key
745 * @param string $value
746 * @param bool $onlyquery [deprecated]
747 * @return string
749 public function appendQueryValue( $key, $value, $onlyquery = true ) {
750 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
754 * Appends or replaces value of query variables.
756 * @param array $array Array of values to replace/add to query
757 * @param bool $onlyquery Whether to only return the query string and not the complete URL [deprecated]
758 * @return string
760 public function appendQueryArray( $array, $onlyquery = true ) {
761 global $wgTitle;
762 $newquery = $this->getQueryValues();
763 unset( $newquery['title'] );
764 $newquery = array_merge( $newquery, $array );
765 $query = wfArrayToCgi( $newquery );
766 if ( !$onlyquery ) {
767 wfDeprecated( __METHOD__, '1.25' );
768 return $wgTitle->getLocalURL( $query );
771 return $query;
775 * Check for limit and offset parameters on the input, and return sensible
776 * defaults if not given. The limit must be positive and is capped at 5000.
777 * Offset must be positive but is not capped.
779 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
780 * @param string $optionname To specify an option other than rclimit to pull from.
781 * @return int[] First element is limit, second is offset
783 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
784 global $wgUser;
786 $limit = $this->getInt( 'limit', 0 );
787 if ( $limit < 0 ) {
788 $limit = 0;
790 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
791 $limit = $wgUser->getIntOption( $optionname );
793 if ( $limit <= 0 ) {
794 $limit = $deflimit;
796 if ( $limit > 5000 ) {
797 $limit = 5000; # We have *some* limits...
800 $offset = $this->getInt( 'offset', 0 );
801 if ( $offset < 0 ) {
802 $offset = 0;
805 return array( $limit, $offset );
809 * Return the path to the temporary file where PHP has stored the upload.
811 * @param string $key
812 * @return string|null String or null if no such file.
814 public function getFileTempname( $key ) {
815 $file = new WebRequestUpload( $this, $key );
816 return $file->getTempName();
820 * Return the upload error or 0
822 * @param string $key
823 * @return int
825 public function getUploadError( $key ) {
826 $file = new WebRequestUpload( $this, $key );
827 return $file->getError();
831 * Return the original filename of the uploaded file, as reported by
832 * the submitting user agent. HTML-style character entities are
833 * interpreted and normalized to Unicode normalization form C, in part
834 * to deal with weird input from Safari with non-ASCII filenames.
836 * Other than this the name is not verified for being a safe filename.
838 * @param string $key
839 * @return string|null String or null if no such file.
841 public function getFileName( $key ) {
842 $file = new WebRequestUpload( $this, $key );
843 return $file->getName();
847 * Return a WebRequestUpload object corresponding to the key
849 * @param string $key
850 * @return WebRequestUpload
852 public function getUpload( $key ) {
853 return new WebRequestUpload( $this, $key );
857 * Return a handle to WebResponse style object, for setting cookies,
858 * headers and other stuff, for Request being worked on.
860 * @return WebResponse
862 public function response() {
863 /* Lazy initialization of response object for this request */
864 if ( !is_object( $this->response ) ) {
865 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
866 $this->response = new $class();
868 return $this->response;
872 * Initialise the header list
874 private function initHeaders() {
875 if ( count( $this->headers ) ) {
876 return;
879 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
880 if ( $apacheHeaders ) {
881 foreach ( $apacheHeaders as $tempName => $tempValue ) {
882 $this->headers[strtoupper( $tempName )] = $tempValue;
884 } else {
885 foreach ( $_SERVER as $name => $value ) {
886 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
887 $name = str_replace( '_', '-', substr( $name, 5 ) );
888 $this->headers[$name] = $value;
889 } elseif ( $name === 'CONTENT_LENGTH' ) {
890 $this->headers['CONTENT-LENGTH'] = $value;
897 * Get an array containing all request headers
899 * @return array Mapping header name to its value
901 public function getAllHeaders() {
902 $this->initHeaders();
903 return $this->headers;
907 * Get a request header, or false if it isn't set.
909 * @param string $name Case-insensitive header name
910 * @param int $flags Bitwise combination of:
911 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
912 * of values, as described in RFC 2616 § 4.2.
913 * (since 1.26).
914 * @return string|array|bool False if header is unset; otherwise the
915 * header value(s) as either a string (the default) or an array, if
916 * WebRequest::GETHEADER_LIST flag was set.
918 public function getHeader( $name, $flags = 0 ) {
919 $this->initHeaders();
920 $name = strtoupper( $name );
921 if ( !isset( $this->headers[$name] ) ) {
922 return false;
924 $value = $this->headers[$name];
925 if ( $flags & self::GETHEADER_LIST ) {
926 $value = array_map( 'trim', explode( ',', $value ) );
928 return $value;
932 * Get data from $_SESSION
934 * @param string $key Name of key in $_SESSION
935 * @return mixed
937 public function getSessionData( $key ) {
938 if ( !isset( $_SESSION[$key] ) ) {
939 return null;
941 return $_SESSION[$key];
945 * Set session data
947 * @param string $key Name of key in $_SESSION
948 * @param mixed $data
950 public function setSessionData( $key, $data ) {
951 $_SESSION[$key] = $data;
955 * Check if Internet Explorer will detect an incorrect cache extension in
956 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
957 * message or redirect to a safer URL. Returns true if the URL is OK, and
958 * false if an error message has been shown and the request should be aborted.
960 * @param array $extWhitelist
961 * @throws HttpError
962 * @return bool
964 public function checkUrlExtension( $extWhitelist = array() ) {
965 global $wgScriptExtension;
966 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
967 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
968 if ( !$this->wasPosted() ) {
969 $newUrl = IEUrlExtension::fixUrlForIE6(
970 $this->getFullRequestURL(), $extWhitelist );
971 if ( $newUrl !== false ) {
972 $this->doSecurityRedirect( $newUrl );
973 return false;
976 throw new HttpError( 403,
977 'Invalid file extension found in the path info or query string.' );
979 return true;
983 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
984 * IE 6. Returns true if it was successful, false otherwise.
986 * @param string $url
987 * @return bool
989 protected function doSecurityRedirect( $url ) {
990 header( 'Location: ' . $url );
991 header( 'Content-Type: text/html' );
992 $encUrl = htmlspecialchars( $url );
993 echo <<<HTML
994 <html>
995 <head>
996 <title>Security redirect</title>
997 </head>
998 <body>
999 <h1>Security redirect</h1>
1001 We can't serve non-HTML content from the URL you have requested, because
1002 Internet Explorer would interpret it as an incorrect and potentially dangerous
1003 content type.</p>
1004 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1005 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1006 Explorer from seeing a bogus file extension.
1007 </p>
1008 </body>
1009 </html>
1010 HTML;
1011 echo "\n";
1012 return true;
1016 * Parse the Accept-Language header sent by the client into an array
1018 * @return array Array( languageCode => q-value ) sorted by q-value in
1019 * descending order then appearing time in the header in ascending order.
1020 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1021 * This is aligned with rfc2616 section 14.4
1022 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1024 public function getAcceptLang() {
1025 // Modified version of code found at
1026 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1027 $acceptLang = $this->getHeader( 'Accept-Language' );
1028 if ( !$acceptLang ) {
1029 return array();
1032 // Return the language codes in lower case
1033 $acceptLang = strtolower( $acceptLang );
1035 // Break up string into pieces (languages and q factors)
1036 $lang_parse = null;
1037 preg_match_all(
1038 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1039 $acceptLang,
1040 $lang_parse
1043 if ( !count( $lang_parse[1] ) ) {
1044 return array();
1047 $langcodes = $lang_parse[1];
1048 $qvalues = $lang_parse[4];
1049 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1051 // Set default q factor to 1
1052 foreach ( $indices as $index ) {
1053 if ( $qvalues[$index] === '' ) {
1054 $qvalues[$index] = 1;
1055 } elseif ( $qvalues[$index] == 0 ) {
1056 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1060 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1061 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1063 // Create a list like "en" => 0.8
1064 $langs = array_combine( $langcodes, $qvalues );
1066 return $langs;
1070 * Fetch the raw IP from the request
1072 * @since 1.19
1074 * @throws MWException
1075 * @return string
1077 protected function getRawIP() {
1078 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1079 return null;
1082 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1083 throw new MWException( __METHOD__
1084 . " : Could not determine the remote IP address due to multiple values." );
1085 } else {
1086 $ipchain = $_SERVER['REMOTE_ADDR'];
1089 return IP::canonicalize( $ipchain );
1093 * Work out the IP address based on various globals
1094 * For trusted proxies, use the XFF client IP (first of the chain)
1096 * @since 1.19
1098 * @throws MWException
1099 * @return string
1101 public function getIP() {
1102 global $wgUsePrivateIPs;
1104 # Return cached result
1105 if ( $this->ip !== null ) {
1106 return $this->ip;
1109 # collect the originating ips
1110 $ip = $this->getRawIP();
1111 if ( !$ip ) {
1112 throw new MWException( 'Unable to determine IP.' );
1115 # Append XFF
1116 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1117 if ( $forwardedFor !== false ) {
1118 $isConfigured = IP::isConfiguredProxy( $ip );
1119 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1120 $ipchain = array_reverse( $ipchain );
1121 array_unshift( $ipchain, $ip );
1123 # Step through XFF list and find the last address in the list which is a
1124 # trusted server. Set $ip to the IP address given by that trusted server,
1125 # unless the address is not sensible (e.g. private). However, prefer private
1126 # IP addresses over proxy servers controlled by this site (more sensible).
1127 # Note that some XFF values might be "unknown" with Squid/Varnish.
1128 foreach ( $ipchain as $i => $curIP ) {
1129 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1130 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1131 || !IP::isTrustedProxy( $curIP )
1133 break; // IP is not valid/trusted or does not point to anything
1135 if (
1136 IP::isPublic( $ipchain[$i + 1] ) ||
1137 $wgUsePrivateIPs ||
1138 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1140 // Follow the next IP according to the proxy
1141 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1142 if ( !$nextIP && $isConfigured ) {
1143 // We have not yet made it past CDN/proxy servers of this site,
1144 // so either they are misconfigured or there is some IP spoofing.
1145 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1147 $ip = $nextIP;
1148 // keep traversing the chain
1149 continue;
1151 break;
1155 # Allow extensions to improve our guess
1156 Hooks::run( 'GetIP', array( &$ip ) );
1158 if ( !$ip ) {
1159 throw new MWException( "Unable to determine IP." );
1162 wfDebug( "IP: $ip\n" );
1163 $this->ip = $ip;
1164 return $ip;
1168 * @param string $ip
1169 * @return void
1170 * @since 1.21
1172 public function setIP( $ip ) {
1173 $this->ip = $ip;
1178 * Object to access the $_FILES array
1180 class WebRequestUpload {
1181 protected $request;
1182 protected $doesExist;
1183 protected $fileInfo;
1186 * Constructor. Should only be called by WebRequest
1188 * @param WebRequest $request The associated request
1189 * @param string $key Key in $_FILES array (name of form field)
1191 public function __construct( $request, $key ) {
1192 $this->request = $request;
1193 $this->doesExist = isset( $_FILES[$key] );
1194 if ( $this->doesExist ) {
1195 $this->fileInfo = $_FILES[$key];
1200 * Return whether a file with this name was uploaded.
1202 * @return bool
1204 public function exists() {
1205 return $this->doesExist;
1209 * Return the original filename of the uploaded file
1211 * @return string|null Filename or null if non-existent
1213 public function getName() {
1214 if ( !$this->exists() ) {
1215 return null;
1218 global $wgContLang;
1219 $name = $this->fileInfo['name'];
1221 # Safari sends filenames in HTML-encoded Unicode form D...
1222 # Horrid and evil! Let's try to make some kind of sense of it.
1223 $name = Sanitizer::decodeCharReferences( $name );
1224 $name = $wgContLang->normalize( $name );
1225 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1226 return $name;
1230 * Return the file size of the uploaded file
1232 * @return int File size or zero if non-existent
1234 public function getSize() {
1235 if ( !$this->exists() ) {
1236 return 0;
1239 return $this->fileInfo['size'];
1243 * Return the path to the temporary file
1245 * @return string|null Path or null if non-existent
1247 public function getTempName() {
1248 if ( !$this->exists() ) {
1249 return null;
1252 return $this->fileInfo['tmp_name'];
1256 * Return the upload error. See link for explanation
1257 * http://www.php.net/manual/en/features.file-upload.errors.php
1259 * @return int One of the UPLOAD_ constants, 0 if non-existent
1261 public function getError() {
1262 if ( !$this->exists() ) {
1263 return 0; # UPLOAD_ERR_OK
1266 return $this->fileInfo['error'];
1270 * Returns whether this upload failed because of overflow of a maximum set
1271 * in php.ini
1273 * @return bool
1275 public function isIniSizeOverflow() {
1276 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1277 # PHP indicated that upload_max_filesize is exceeded
1278 return true;
1281 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1282 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1283 # post_max_size is exceeded
1284 return true;
1287 return false;
1292 * WebRequest clone which takes values from a provided array.
1294 * @ingroup HTTP
1296 class FauxRequest extends WebRequest {
1297 private $wasPosted = false;
1298 private $session = array();
1299 private $requestUrl;
1300 protected $cookies = array();
1303 * @param array $data Array of *non*-urlencoded key => value pairs, the
1304 * fake GET/POST values
1305 * @param bool $wasPosted Whether to treat the data as POST
1306 * @param array|null $session Session array or null
1307 * @param string $protocol 'http' or 'https'
1308 * @throws MWException
1310 public function __construct( $data = array(), $wasPosted = false,
1311 $session = null, $protocol = 'http'
1313 $this->requestTime = microtime( true );
1315 if ( is_array( $data ) ) {
1316 $this->data = $data;
1317 } else {
1318 throw new MWException( "FauxRequest() got bogus data" );
1320 $this->wasPosted = $wasPosted;
1321 if ( $session ) {
1322 $this->session = $session;
1324 $this->protocol = $protocol;
1328 * @param string $method
1329 * @throws MWException
1331 private function notImplemented( $method ) {
1332 throw new MWException( "{$method}() not implemented" );
1336 * @param string $name
1337 * @param string $default
1338 * @return string
1340 public function getText( $name, $default = '' ) {
1341 # Override; don't recode since we're using internal data
1342 return (string)$this->getVal( $name, $default );
1346 * @return array
1348 public function getValues() {
1349 return $this->data;
1353 * @return array
1355 public function getQueryValues() {
1356 if ( $this->wasPosted ) {
1357 return array();
1358 } else {
1359 return $this->data;
1363 public function getMethod() {
1364 return $this->wasPosted ? 'POST' : 'GET';
1368 * @return bool
1370 public function wasPosted() {
1371 return $this->wasPosted;
1374 public function getCookie( $key, $prefix = null, $default = null ) {
1375 if ( $prefix === null ) {
1376 global $wgCookiePrefix;
1377 $prefix = $wgCookiePrefix;
1379 $name = $prefix . $key;
1380 return isset( $this->cookies[$name] ) ? $this->cookies[$name] : $default;
1384 * @since 1.26
1385 * @param string $name Unprefixed name of the cookie to set
1386 * @param string|null $value Value of the cookie to set
1387 * @param string|null $prefix Cookie prefix. Defaults to $wgCookiePrefix
1389 public function setCookie( $key, $value, $prefix = null ) {
1390 $this->setCookies( array( $key => $value ), $prefix );
1394 * @since 1.26
1395 * @param array $cookies
1396 * @param string|null $prefix Cookie prefix. Defaults to $wgCookiePrefix
1398 public function setCookies( $cookies, $prefix = null ) {
1399 if ( $prefix === null ) {
1400 global $wgCookiePrefix;
1401 $prefix = $wgCookiePrefix;
1403 foreach ( $cookies as $key => $value ) {
1404 $name = $prefix . $key;
1405 $this->cookies[$name] = $value;
1409 public function checkSessionCookie() {
1410 return false;
1413 public function setRequestURL( $url ) {
1414 $this->requestUrl = $url;
1417 public function getRequestURL() {
1418 if ( $this->requestUrl === null ) {
1419 throw new MWException( 'Request URL not set' );
1421 return $this->requestUrl;
1424 public function getProtocol() {
1425 return $this->protocol;
1428 private function initHeaders() {
1429 return;
1433 * @param string $name
1434 * @param string $val
1436 public function setHeader( $name, $val ) {
1437 $this->setHeaders( array( $name => $val ) );
1441 * @since 1.26
1442 * @param array $headers
1444 public function setHeaders( $headers ) {
1445 foreach ( $headers as $name => $val ) {
1446 $name = strtoupper( $name );
1447 $this->headers[$name] = $val;
1452 * @param string $key
1453 * @return array|null
1455 public function getSessionData( $key ) {
1456 if ( isset( $this->session[$key] ) ) {
1457 return $this->session[$key];
1459 return null;
1463 * @param string $key
1464 * @param array $data
1466 public function setSessionData( $key, $data ) {
1467 $this->session[$key] = $data;
1471 * @return array|mixed|null
1473 public function getSessionArray() {
1474 return $this->session;
1478 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1479 * @return string
1481 public function getRawQueryString() {
1482 return '';
1486 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1487 * @return string
1489 public function getRawPostString() {
1490 return '';
1494 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1495 * @return string
1497 public function getRawInput() {
1498 return '';
1502 * @param array $extWhitelist
1503 * @return bool
1505 public function checkUrlExtension( $extWhitelist = array() ) {
1506 return true;
1510 * @return string
1512 protected function getRawIP() {
1513 return '127.0.0.1';
1518 * Similar to FauxRequest, but only fakes URL parameters and method
1519 * (POST or GET) and use the base request for the remaining stuff
1520 * (cookies, session and headers).
1522 * @ingroup HTTP
1523 * @since 1.19
1525 class DerivativeRequest extends FauxRequest {
1526 private $base;
1529 * @param WebRequest $base
1530 * @param array $data Array of *non*-urlencoded key => value pairs, the
1531 * fake GET/POST values
1532 * @param bool $wasPosted Whether to treat the data as POST
1534 public function __construct( WebRequest $base, $data, $wasPosted = false ) {
1535 $this->base = $base;
1536 parent::__construct( $data, $wasPosted );
1539 public function getCookie( $key, $prefix = null, $default = null ) {
1540 return $this->base->getCookie( $key, $prefix, $default );
1543 public function checkSessionCookie() {
1544 return $this->base->checkSessionCookie();
1547 public function getHeader( $name, $flags = 0 ) {
1548 return $this->base->getHeader( $name, $flags );
1551 public function getAllHeaders() {
1552 return $this->base->getAllHeaders();
1555 public function getSessionData( $key ) {
1556 return $this->base->getSessionData( $key );
1559 public function setSessionData( $key, $data ) {
1560 $this->base->setSessionData( $key, $data );
1563 public function getAcceptLang() {
1564 return $this->base->getAcceptLang();
1567 public function getIP() {
1568 return $this->base->getIP();
1571 public function getProtocol() {
1572 return $this->base->getProtocol();
1575 public function getElapsedTime() {
1576 return $this->base->getElapsedTime();