HTTPS-ify links to Wikimedia's sites in MW core source
[mediawiki.git] / includes / WebRequest.php
blob05e229d0c0d656b46e02fc725ea2778a08062c89
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 $proto = self::detectProtocol();
180 $stdPort = $proto === 'https' ? 443 : 80;
182 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
183 $host = 'localhost';
184 $port = $stdPort;
185 foreach ( $varNames as $varName ) {
186 if ( !isset( $_SERVER[$varName] ) ) {
187 continue;
189 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
190 if ( !$parts ) {
191 // Invalid, do not use
192 continue;
194 $host = $parts[0];
195 if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
196 // Bug 70021: Assume that upstream proxy is running on the default
197 // port based on the protocol. We have no reliable way to determine
198 // the actual port in use upstream.
199 $port = $stdPort;
200 } elseif ( $parts[1] === false ) {
201 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
202 $port = $_SERVER['SERVER_PORT'];
203 } // else leave it as $stdPort
204 } else {
205 $port = $parts[1];
207 break;
210 return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
214 * Detect the protocol from $_SERVER.
215 * This is for use prior to Setup.php, when no WebRequest object is available.
216 * At other times, use the non-static function getProtocol().
218 * @return array
220 public static function detectProtocol() {
221 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
222 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
223 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
224 return 'https';
225 } else {
226 return 'http';
231 * Get the number of seconds to have elapsed since request start,
232 * in fractional seconds, with microsecond resolution.
234 * @return float
235 * @since 1.25
237 public function getElapsedTime() {
238 return microtime( true ) - $this->requestTime;
242 * Get the current URL protocol (http or https)
243 * @return string
245 public function getProtocol() {
246 if ( $this->protocol === null ) {
247 $this->protocol = self::detectProtocol();
249 return $this->protocol;
253 * Check for title, action, and/or variant data in the URL
254 * and interpolate it into the GET variables.
255 * This should only be run after $wgContLang is available,
256 * as we may need the list of language variants to determine
257 * available variant URLs.
259 public function interpolateTitle() {
260 // bug 16019: title interpolation on API queries is useless and sometimes harmful
261 if ( defined( 'MW_API' ) ) {
262 return;
265 $matches = self::getPathInfo( 'title' );
266 foreach ( $matches as $key => $val ) {
267 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
272 * URL rewriting function; tries to extract page title and,
273 * optionally, one other fixed parameter value from a URL path.
275 * @param string $path The URL path given from the client
276 * @param array $bases One or more URLs, optionally with $1 at the end
277 * @param string $key If provided, the matching key in $bases will be
278 * passed on as the value of this URL parameter
279 * @return array Array of URL variables to interpolate; empty if no match
281 static function extractTitle( $path, $bases, $key = false ) {
282 foreach ( (array)$bases as $keyValue => $base ) {
283 // Find the part after $wgArticlePath
284 $base = str_replace( '$1', '', $base );
285 $baseLen = strlen( $base );
286 if ( substr( $path, 0, $baseLen ) == $base ) {
287 $raw = substr( $path, $baseLen );
288 if ( $raw !== '' ) {
289 $matches = array( 'title' => rawurldecode( $raw ) );
290 if ( $key ) {
291 $matches[$key] = $keyValue;
293 return $matches;
297 return array();
301 * Recursively normalizes UTF-8 strings in the given array.
303 * @param string|array $data
304 * @return array|string Cleaned-up version of the given
305 * @private
307 function normalizeUnicode( $data ) {
308 if ( is_array( $data ) ) {
309 foreach ( $data as $key => $val ) {
310 $data[$key] = $this->normalizeUnicode( $val );
312 } else {
313 global $wgContLang;
314 $data = isset( $wgContLang ) ? $wgContLang->normalize( $data ) : UtfNormal\Validator::cleanUp( $data );
316 return $data;
320 * Fetch a value from the given array or return $default if it's not set.
322 * @param array $arr
323 * @param string $name
324 * @param mixed $default
325 * @return mixed
327 private function getGPCVal( $arr, $name, $default ) {
328 # PHP is so nice to not touch input data, except sometimes:
329 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
330 # Work around PHP *feature* to avoid *bugs* elsewhere.
331 $name = strtr( $name, '.', '_' );
332 if ( isset( $arr[$name] ) ) {
333 global $wgContLang;
334 $data = $arr[$name];
335 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
336 # Check for alternate/legacy character encoding.
337 if ( isset( $wgContLang ) ) {
338 $data = $wgContLang->checkTitleEncoding( $data );
341 $data = $this->normalizeUnicode( $data );
342 return $data;
343 } else {
344 return $default;
349 * Fetch a scalar from the input or return $default if it's not set.
350 * Returns a string. Arrays are discarded. Useful for
351 * non-freeform text inputs (e.g. predefined internal text keys
352 * selected by a drop-down menu). For freeform input, see getText().
354 * @param string $name
355 * @param string $default Optional default (or null)
356 * @return string
358 public function getVal( $name, $default = null ) {
359 $val = $this->getGPCVal( $this->data, $name, $default );
360 if ( is_array( $val ) ) {
361 $val = $default;
363 if ( is_null( $val ) ) {
364 return $val;
365 } else {
366 return (string)$val;
371 * Set an arbitrary value into our get/post data.
373 * @param string $key Key name to use
374 * @param mixed $value Value to set
375 * @return mixed Old value if one was present, null otherwise
377 public function setVal( $key, $value ) {
378 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
379 $this->data[$key] = $value;
380 return $ret;
384 * Unset an arbitrary value from our get/post data.
386 * @param string $key Key name to use
387 * @return mixed Old value if one was present, null otherwise
389 public function unsetVal( $key ) {
390 if ( !isset( $this->data[$key] ) ) {
391 $ret = null;
392 } else {
393 $ret = $this->data[$key];
394 unset( $this->data[$key] );
396 return $ret;
400 * Fetch an array from the input or return $default if it's not set.
401 * If source was scalar, will return an array with a single element.
402 * If no source and no default, returns null.
404 * @param string $name
405 * @param array $default Optional default (or null)
406 * @return array
408 public function getArray( $name, $default = null ) {
409 $val = $this->getGPCVal( $this->data, $name, $default );
410 if ( is_null( $val ) ) {
411 return null;
412 } else {
413 return (array)$val;
418 * Fetch an array of integers, or return $default if it's not set.
419 * If source was scalar, will return an array with a single element.
420 * If no source and no default, returns null.
421 * If an array is returned, contents are guaranteed to be integers.
423 * @param string $name
424 * @param array $default Option default (or null)
425 * @return array Array of ints
427 public function getIntArray( $name, $default = null ) {
428 $val = $this->getArray( $name, $default );
429 if ( is_array( $val ) ) {
430 $val = array_map( 'intval', $val );
432 return $val;
436 * Fetch an integer value from the input or return $default if not set.
437 * Guaranteed to return an integer; non-numeric input will typically
438 * return 0.
440 * @param string $name
441 * @param int $default
442 * @return int
444 public function getInt( $name, $default = 0 ) {
445 return intval( $this->getVal( $name, $default ) );
449 * Fetch an integer value from the input or return null if empty.
450 * Guaranteed to return an integer or null; non-numeric input will
451 * typically return null.
453 * @param string $name
454 * @return int|null
456 public function getIntOrNull( $name ) {
457 $val = $this->getVal( $name );
458 return is_numeric( $val )
459 ? intval( $val )
460 : null;
464 * Fetch a floating point value from the input or return $default if not set.
465 * Guaranteed to return a float; non-numeric input will typically
466 * return 0.
468 * @since 1.23
469 * @param string $name
470 * @param float $default
471 * @return float
473 public function getFloat( $name, $default = 0.0 ) {
474 return floatval( $this->getVal( $name, $default ) );
478 * Fetch a boolean value from the input or return $default if not set.
479 * Guaranteed to return true or false, with normal PHP semantics for
480 * boolean interpretation of strings.
482 * @param string $name
483 * @param bool $default
484 * @return bool
486 public function getBool( $name, $default = false ) {
487 return (bool)$this->getVal( $name, $default );
491 * Fetch a boolean value from the input or return $default if not set.
492 * Unlike getBool, the string "false" will result in boolean false, which is
493 * useful when interpreting information sent from JavaScript.
495 * @param string $name
496 * @param bool $default
497 * @return bool
499 public function getFuzzyBool( $name, $default = false ) {
500 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
504 * Return true if the named value is set in the input, whatever that
505 * value is (even "0"). Return false if the named value is not set.
506 * Example use is checking for the presence of check boxes in forms.
508 * @param string $name
509 * @return bool
511 public function getCheck( $name ) {
512 # Checkboxes and buttons are only present when clicked
513 # Presence connotes truth, absence false
514 return $this->getVal( $name, null ) !== null;
518 * Fetch a text string from the given array or return $default if it's not
519 * set. Carriage returns are stripped from the text, and with some language
520 * modules there is an input transliteration applied. This should generally
521 * be used for form "<textarea>" and "<input>" fields. Used for
522 * user-supplied freeform text input (for which input transformations may
523 * be required - e.g. Esperanto x-coding).
525 * @param string $name
526 * @param string $default Optional
527 * @return string
529 public function getText( $name, $default = '' ) {
530 global $wgContLang;
531 $val = $this->getVal( $name, $default );
532 return str_replace( "\r\n", "\n",
533 $wgContLang->recodeInput( $val ) );
537 * Extracts the given named values into an array.
538 * If no arguments are given, returns all input values.
539 * No transformation is performed on the values.
541 * @return array
543 public function getValues() {
544 $names = func_get_args();
545 if ( count( $names ) == 0 ) {
546 $names = array_keys( $this->data );
549 $retVal = array();
550 foreach ( $names as $name ) {
551 $value = $this->getGPCVal( $this->data, $name, null );
552 if ( !is_null( $value ) ) {
553 $retVal[$name] = $value;
556 return $retVal;
560 * Returns the names of all input values excluding those in $exclude.
562 * @param array $exclude
563 * @return array
565 public function getValueNames( $exclude = array() ) {
566 return array_diff( array_keys( $this->getValues() ), $exclude );
570 * Get the values passed in the query string.
571 * No transformation is performed on the values.
573 * @return array
575 public function getQueryValues() {
576 return $_GET;
580 * Return the contents of the Query with no decoding. Use when you need to
581 * know exactly what was sent, e.g. for an OAuth signature over the elements.
583 * @return string
585 public function getRawQueryString() {
586 return $_SERVER['QUERY_STRING'];
590 * Return the contents of the POST with no decoding. Use when you need to
591 * know exactly what was sent, e.g. for an OAuth signature over the elements.
593 * @return string
595 public function getRawPostString() {
596 if ( !$this->wasPosted() ) {
597 return '';
599 return $this->getRawInput();
603 * Return the raw request body, with no processing. Cached since some methods
604 * disallow reading the stream more than once. As stated in the php docs, this
605 * does not work with enctype="multipart/form-data".
607 * @return string
609 public function getRawInput() {
610 static $input = null;
611 if ( $input === null ) {
612 $input = file_get_contents( 'php://input' );
614 return $input;
618 * Get the HTTP method used for this request.
620 * @return string
622 public function getMethod() {
623 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
627 * Returns true if the present request was reached by a POST operation,
628 * false otherwise (GET, HEAD, or command-line).
630 * Note that values retrieved by the object may come from the
631 * GET URL etc even on a POST request.
633 * @return bool
635 public function wasPosted() {
636 return $this->getMethod() == 'POST';
640 * Returns true if there is a session cookie set.
641 * This does not necessarily mean that the user is logged in!
643 * If you want to check for an open session, use session_id()
644 * instead; that will also tell you if the session was opened
645 * during the current request (in which case the cookie will
646 * be sent back to the client at the end of the script run).
648 * @return bool
650 public function checkSessionCookie() {
651 return isset( $_COOKIE[session_name()] );
655 * Get a cookie from the $_COOKIE jar
657 * @param string $key The name of the cookie
658 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
659 * @param mixed $default What to return if the value isn't found
660 * @return mixed Cookie value or $default if the cookie not set
662 public function getCookie( $key, $prefix = null, $default = null ) {
663 if ( $prefix === null ) {
664 global $wgCookiePrefix;
665 $prefix = $wgCookiePrefix;
667 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
671 * Return the path and query string portion of the request URI.
672 * This will be suitable for use as a relative link in HTML output.
674 * @throws MWException
675 * @return string
677 public function getRequestURL() {
678 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
679 $base = $_SERVER['REQUEST_URI'];
680 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
681 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
683 // Probably IIS; doesn't set REQUEST_URI
684 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
685 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
686 $base = $_SERVER['SCRIPT_NAME'];
687 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
688 $base .= '?' . $_SERVER['QUERY_STRING'];
690 } else {
691 // This shouldn't happen!
692 throw new MWException( "Web server doesn't provide either " .
693 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
694 "of your web server configuration to https://phabricator.wikimedia.org/" );
696 // User-agents should not send a fragment with the URI, but
697 // if they do, and the web server passes it on to us, we
698 // need to strip it or we get false-positive redirect loops
699 // or weird output URLs
700 $hash = strpos( $base, '#' );
701 if ( $hash !== false ) {
702 $base = substr( $base, 0, $hash );
705 if ( $base[0] == '/' ) {
706 // More than one slash will look like it is protocol relative
707 return preg_replace( '!^/+!', '/', $base );
708 } else {
709 // We may get paths with a host prepended; strip it.
710 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
715 * Return the request URI with the canonical service and hostname, path,
716 * and query string. This will be suitable for use as an absolute link
717 * in HTML or other output.
719 * If $wgServer is protocol-relative, this will return a fully
720 * qualified URL with the protocol that was used for this request.
722 * @return string
724 public function getFullRequestURL() {
725 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
729 * Take an arbitrary query and rewrite the present URL to include it
730 * @deprecated Use appendQueryValue/appendQueryArray instead
731 * @param string $query Query string fragment; do not include initial '?'
732 * @return string
734 public function appendQuery( $query ) {
735 wfDeprecated( __METHOD__, '1.25' );
736 return $this->appendQueryArray( wfCgiToArray( $query ) );
740 * @param string $key
741 * @param string $value
742 * @param bool $onlyquery [deprecated]
743 * @return string
745 public function appendQueryValue( $key, $value, $onlyquery = true ) {
746 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
750 * Appends or replaces value of query variables.
752 * @param array $array Array of values to replace/add to query
753 * @param bool $onlyquery Whether to only return the query string and not the complete URL [deprecated]
754 * @return string
756 public function appendQueryArray( $array, $onlyquery = true ) {
757 global $wgTitle;
758 $newquery = $this->getQueryValues();
759 unset( $newquery['title'] );
760 $newquery = array_merge( $newquery, $array );
761 $query = wfArrayToCgi( $newquery );
762 if ( !$onlyquery ) {
763 wfDeprecated( __METHOD__, '1.25' );
764 return $wgTitle->getLocalURL( $query );
767 return $query;
771 * Check for limit and offset parameters on the input, and return sensible
772 * defaults if not given. The limit must be positive and is capped at 5000.
773 * Offset must be positive but is not capped.
775 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
776 * @param string $optionname To specify an option other than rclimit to pull from.
777 * @return array First element is limit, second is offset
779 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
780 global $wgUser;
782 $limit = $this->getInt( 'limit', 0 );
783 if ( $limit < 0 ) {
784 $limit = 0;
786 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
787 $limit = $wgUser->getIntOption( $optionname );
789 if ( $limit <= 0 ) {
790 $limit = $deflimit;
792 if ( $limit > 5000 ) {
793 $limit = 5000; # We have *some* limits...
796 $offset = $this->getInt( 'offset', 0 );
797 if ( $offset < 0 ) {
798 $offset = 0;
801 return array( $limit, $offset );
805 * Return the path to the temporary file where PHP has stored the upload.
807 * @param string $key
808 * @return string|null String or null if no such file.
810 public function getFileTempname( $key ) {
811 $file = new WebRequestUpload( $this, $key );
812 return $file->getTempName();
816 * Return the upload error or 0
818 * @param string $key
819 * @return int
821 public function getUploadError( $key ) {
822 $file = new WebRequestUpload( $this, $key );
823 return $file->getError();
827 * Return the original filename of the uploaded file, as reported by
828 * the submitting user agent. HTML-style character entities are
829 * interpreted and normalized to Unicode normalization form C, in part
830 * to deal with weird input from Safari with non-ASCII filenames.
832 * Other than this the name is not verified for being a safe filename.
834 * @param string $key
835 * @return string|null String or null if no such file.
837 public function getFileName( $key ) {
838 $file = new WebRequestUpload( $this, $key );
839 return $file->getName();
843 * Return a WebRequestUpload object corresponding to the key
845 * @param string $key
846 * @return WebRequestUpload
848 public function getUpload( $key ) {
849 return new WebRequestUpload( $this, $key );
853 * Return a handle to WebResponse style object, for setting cookies,
854 * headers and other stuff, for Request being worked on.
856 * @return WebResponse
858 public function response() {
859 /* Lazy initialization of response object for this request */
860 if ( !is_object( $this->response ) ) {
861 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
862 $this->response = new $class();
864 return $this->response;
868 * Initialise the header list
870 private function initHeaders() {
871 if ( count( $this->headers ) ) {
872 return;
875 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
876 if ( $apacheHeaders ) {
877 foreach ( $apacheHeaders as $tempName => $tempValue ) {
878 $this->headers[strtoupper( $tempName )] = $tempValue;
880 } else {
881 foreach ( $_SERVER as $name => $value ) {
882 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
883 $name = str_replace( '_', '-', substr( $name, 5 ) );
884 $this->headers[$name] = $value;
885 } elseif ( $name === 'CONTENT_LENGTH' ) {
886 $this->headers['CONTENT-LENGTH'] = $value;
893 * Get an array containing all request headers
895 * @return array Mapping header name to its value
897 public function getAllHeaders() {
898 $this->initHeaders();
899 return $this->headers;
903 * Get a request header, or false if it isn't set.
905 * @param string $name Case-insensitive header name
906 * @param int $flags Bitwise combination of:
907 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
908 * of values, as described in RFC 2616 § 4.2.
909 * (since 1.26).
910 * @return string|array|bool False if header is unset; otherwise the
911 * header value(s) as either a string (the default) or an array, if
912 * WebRequest::GETHEADER_LIST flag was set.
914 public function getHeader( $name, $flags = 0 ) {
915 $this->initHeaders();
916 $name = strtoupper( $name );
917 if ( !isset( $this->headers[$name] ) ) {
918 return false;
920 $value = $this->headers[$name];
921 if ( $flags & self::GETHEADER_LIST ) {
922 $value = array_map( 'trim', explode( ',', $value ) );
924 return $value;
928 * Get data from $_SESSION
930 * @param string $key Name of key in $_SESSION
931 * @return mixed
933 public function getSessionData( $key ) {
934 if ( !isset( $_SESSION[$key] ) ) {
935 return null;
937 return $_SESSION[$key];
941 * Set session data
943 * @param string $key Name of key in $_SESSION
944 * @param mixed $data
946 public function setSessionData( $key, $data ) {
947 $_SESSION[$key] = $data;
951 * Check if Internet Explorer will detect an incorrect cache extension in
952 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
953 * message or redirect to a safer URL. Returns true if the URL is OK, and
954 * false if an error message has been shown and the request should be aborted.
956 * @param array $extWhitelist
957 * @throws HttpError
958 * @return bool
960 public function checkUrlExtension( $extWhitelist = array() ) {
961 global $wgScriptExtension;
962 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
963 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
964 if ( !$this->wasPosted() ) {
965 $newUrl = IEUrlExtension::fixUrlForIE6(
966 $this->getFullRequestURL(), $extWhitelist );
967 if ( $newUrl !== false ) {
968 $this->doSecurityRedirect( $newUrl );
969 return false;
972 throw new HttpError( 403,
973 'Invalid file extension found in the path info or query string.' );
975 return true;
979 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
980 * IE 6. Returns true if it was successful, false otherwise.
982 * @param string $url
983 * @return bool
985 protected function doSecurityRedirect( $url ) {
986 header( 'Location: ' . $url );
987 header( 'Content-Type: text/html' );
988 $encUrl = htmlspecialchars( $url );
989 echo <<<HTML
990 <html>
991 <head>
992 <title>Security redirect</title>
993 </head>
994 <body>
995 <h1>Security redirect</h1>
997 We can't serve non-HTML content from the URL you have requested, because
998 Internet Explorer would interpret it as an incorrect and potentially dangerous
999 content type.</p>
1000 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1001 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1002 Explorer from seeing a bogus file extension.
1003 </p>
1004 </body>
1005 </html>
1006 HTML;
1007 echo "\n";
1008 return true;
1012 * Parse the Accept-Language header sent by the client into an array
1014 * @return array Array( languageCode => q-value ) sorted by q-value in
1015 * descending order then appearing time in the header in ascending order.
1016 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1017 * This is aligned with rfc2616 section 14.4
1018 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1020 public function getAcceptLang() {
1021 // Modified version of code found at
1022 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1023 $acceptLang = $this->getHeader( 'Accept-Language' );
1024 if ( !$acceptLang ) {
1025 return array();
1028 // Return the language codes in lower case
1029 $acceptLang = strtolower( $acceptLang );
1031 // Break up string into pieces (languages and q factors)
1032 $lang_parse = null;
1033 preg_match_all(
1034 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1035 $acceptLang,
1036 $lang_parse
1039 if ( !count( $lang_parse[1] ) ) {
1040 return array();
1043 $langcodes = $lang_parse[1];
1044 $qvalues = $lang_parse[4];
1045 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1047 // Set default q factor to 1
1048 foreach ( $indices as $index ) {
1049 if ( $qvalues[$index] === '' ) {
1050 $qvalues[$index] = 1;
1051 } elseif ( $qvalues[$index] == 0 ) {
1052 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1056 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1057 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1059 // Create a list like "en" => 0.8
1060 $langs = array_combine( $langcodes, $qvalues );
1062 return $langs;
1066 * Fetch the raw IP from the request
1068 * @since 1.19
1070 * @throws MWException
1071 * @return string
1073 protected function getRawIP() {
1074 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1075 return null;
1078 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1079 throw new MWException( __METHOD__
1080 . " : Could not determine the remote IP address due to multiple values." );
1081 } else {
1082 $ipchain = $_SERVER['REMOTE_ADDR'];
1085 return IP::canonicalize( $ipchain );
1089 * Work out the IP address based on various globals
1090 * For trusted proxies, use the XFF client IP (first of the chain)
1092 * @since 1.19
1094 * @throws MWException
1095 * @return string
1097 public function getIP() {
1098 global $wgUsePrivateIPs;
1100 # Return cached result
1101 if ( $this->ip !== null ) {
1102 return $this->ip;
1105 # collect the originating ips
1106 $ip = $this->getRawIP();
1107 if ( !$ip ) {
1108 throw new MWException( 'Unable to determine IP.' );
1111 # Append XFF
1112 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1113 if ( $forwardedFor !== false ) {
1114 $isConfigured = IP::isConfiguredProxy( $ip );
1115 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1116 $ipchain = array_reverse( $ipchain );
1117 array_unshift( $ipchain, $ip );
1119 # Step through XFF list and find the last address in the list which is a
1120 # trusted server. Set $ip to the IP address given by that trusted server,
1121 # unless the address is not sensible (e.g. private). However, prefer private
1122 # IP addresses over proxy servers controlled by this site (more sensible).
1123 # Note that some XFF values might be "unknown" with Squid/Varnish.
1124 foreach ( $ipchain as $i => $curIP ) {
1125 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1126 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1127 || !IP::isTrustedProxy( $curIP )
1129 break; // IP is not valid/trusted or does not point to anything
1131 if (
1132 IP::isPublic( $ipchain[$i + 1] ) ||
1133 $wgUsePrivateIPs ||
1134 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1136 // Follow the next IP according to the proxy
1137 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1138 if ( !$nextIP && $isConfigured ) {
1139 // We have not yet made it past CDN/proxy servers of this site,
1140 // so either they are misconfigured or there is some IP spoofing.
1141 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1143 $ip = $nextIP;
1144 // keep traversing the chain
1145 continue;
1147 break;
1151 # Allow extensions to improve our guess
1152 Hooks::run( 'GetIP', array( &$ip ) );
1154 if ( !$ip ) {
1155 throw new MWException( "Unable to determine IP." );
1158 wfDebug( "IP: $ip\n" );
1159 $this->ip = $ip;
1160 return $ip;
1164 * @param string $ip
1165 * @return void
1166 * @since 1.21
1168 public function setIP( $ip ) {
1169 $this->ip = $ip;
1174 * Object to access the $_FILES array
1176 class WebRequestUpload {
1177 protected $request;
1178 protected $doesExist;
1179 protected $fileInfo;
1182 * Constructor. Should only be called by WebRequest
1184 * @param WebRequest $request The associated request
1185 * @param string $key Key in $_FILES array (name of form field)
1187 public function __construct( $request, $key ) {
1188 $this->request = $request;
1189 $this->doesExist = isset( $_FILES[$key] );
1190 if ( $this->doesExist ) {
1191 $this->fileInfo = $_FILES[$key];
1196 * Return whether a file with this name was uploaded.
1198 * @return bool
1200 public function exists() {
1201 return $this->doesExist;
1205 * Return the original filename of the uploaded file
1207 * @return string|null Filename or null if non-existent
1209 public function getName() {
1210 if ( !$this->exists() ) {
1211 return null;
1214 global $wgContLang;
1215 $name = $this->fileInfo['name'];
1217 # Safari sends filenames in HTML-encoded Unicode form D...
1218 # Horrid and evil! Let's try to make some kind of sense of it.
1219 $name = Sanitizer::decodeCharReferences( $name );
1220 $name = $wgContLang->normalize( $name );
1221 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1222 return $name;
1226 * Return the file size of the uploaded file
1228 * @return int File size or zero if non-existent
1230 public function getSize() {
1231 if ( !$this->exists() ) {
1232 return 0;
1235 return $this->fileInfo['size'];
1239 * Return the path to the temporary file
1241 * @return string|null Path or null if non-existent
1243 public function getTempName() {
1244 if ( !$this->exists() ) {
1245 return null;
1248 return $this->fileInfo['tmp_name'];
1252 * Return the upload error. See link for explanation
1253 * http://www.php.net/manual/en/features.file-upload.errors.php
1255 * @return int One of the UPLOAD_ constants, 0 if non-existent
1257 public function getError() {
1258 if ( !$this->exists() ) {
1259 return 0; # UPLOAD_ERR_OK
1262 return $this->fileInfo['error'];
1266 * Returns whether this upload failed because of overflow of a maximum set
1267 * in php.ini
1269 * @return bool
1271 public function isIniSizeOverflow() {
1272 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1273 # PHP indicated that upload_max_filesize is exceeded
1274 return true;
1277 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1278 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1279 # post_max_size is exceeded
1280 return true;
1283 return false;
1288 * WebRequest clone which takes values from a provided array.
1290 * @ingroup HTTP
1292 class FauxRequest extends WebRequest {
1293 private $wasPosted = false;
1294 private $session = array();
1295 private $requestUrl;
1298 * @param array $data Array of *non*-urlencoded key => value pairs, the
1299 * fake GET/POST values
1300 * @param bool $wasPosted Whether to treat the data as POST
1301 * @param array|null $session Session array or null
1302 * @param string $protocol 'http' or 'https'
1303 * @throws MWException
1305 public function __construct( $data = array(), $wasPosted = false,
1306 $session = null, $protocol = 'http'
1308 $this->requestTime = microtime( true );
1310 if ( is_array( $data ) ) {
1311 $this->data = $data;
1312 } else {
1313 throw new MWException( "FauxRequest() got bogus data" );
1315 $this->wasPosted = $wasPosted;
1316 if ( $session ) {
1317 $this->session = $session;
1319 $this->protocol = $protocol;
1323 * @param string $method
1324 * @throws MWException
1326 private function notImplemented( $method ) {
1327 throw new MWException( "{$method}() not implemented" );
1331 * @param string $name
1332 * @param string $default
1333 * @return string
1335 public function getText( $name, $default = '' ) {
1336 # Override; don't recode since we're using internal data
1337 return (string)$this->getVal( $name, $default );
1341 * @return array
1343 public function getValues() {
1344 return $this->data;
1348 * @return array
1350 public function getQueryValues() {
1351 if ( $this->wasPosted ) {
1352 return array();
1353 } else {
1354 return $this->data;
1358 public function getMethod() {
1359 return $this->wasPosted ? 'POST' : 'GET';
1363 * @return bool
1365 public function wasPosted() {
1366 return $this->wasPosted;
1369 public function getCookie( $key, $prefix = null, $default = null ) {
1370 return $default;
1373 public function checkSessionCookie() {
1374 return false;
1377 public function setRequestURL( $url ) {
1378 $this->requestUrl = $url;
1381 public function getRequestURL() {
1382 if ( $this->requestUrl === null ) {
1383 throw new MWException( 'Request URL not set' );
1385 return $this->requestUrl;
1388 public function getProtocol() {
1389 return $this->protocol;
1392 private function initHeaders() {
1393 return;
1397 * @param string $name
1398 * @param string $val
1400 public function setHeader( $name, $val ) {
1401 $name = strtoupper( $name );
1402 $this->headers[$name] = $val;
1406 * @param string $key
1407 * @return array|null
1409 public function getSessionData( $key ) {
1410 if ( isset( $this->session[$key] ) ) {
1411 return $this->session[$key];
1413 return null;
1417 * @param string $key
1418 * @param array $data
1420 public function setSessionData( $key, $data ) {
1421 $this->session[$key] = $data;
1425 * @return array|mixed|null
1427 public function getSessionArray() {
1428 return $this->session;
1432 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1433 * @return string
1435 public function getRawQueryString() {
1436 return '';
1440 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1441 * @return string
1443 public function getRawPostString() {
1444 return '';
1448 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1449 * @return string
1451 public function getRawInput() {
1452 return '';
1456 * @param array $extWhitelist
1457 * @return bool
1459 public function checkUrlExtension( $extWhitelist = array() ) {
1460 return true;
1464 * @return string
1466 protected function getRawIP() {
1467 return '127.0.0.1';
1472 * Similar to FauxRequest, but only fakes URL parameters and method
1473 * (POST or GET) and use the base request for the remaining stuff
1474 * (cookies, session and headers).
1476 * @ingroup HTTP
1477 * @since 1.19
1479 class DerivativeRequest extends FauxRequest {
1480 private $base;
1483 * @param WebRequest $base
1484 * @param array $data Array of *non*-urlencoded key => value pairs, the
1485 * fake GET/POST values
1486 * @param bool $wasPosted Whether to treat the data as POST
1488 public function __construct( WebRequest $base, $data, $wasPosted = false ) {
1489 $this->base = $base;
1490 parent::__construct( $data, $wasPosted );
1493 public function getCookie( $key, $prefix = null, $default = null ) {
1494 return $this->base->getCookie( $key, $prefix, $default );
1497 public function checkSessionCookie() {
1498 return $this->base->checkSessionCookie();
1501 public function getHeader( $name, $flags = 0 ) {
1502 return $this->base->getHeader( $name, $flags );
1505 public function getAllHeaders() {
1506 return $this->base->getAllHeaders();
1509 public function getSessionData( $key ) {
1510 return $this->base->getSessionData( $key );
1513 public function setSessionData( $key, $data ) {
1514 $this->base->setSessionData( $key, $data );
1517 public function getAcceptLang() {
1518 return $this->base->getAcceptLang();
1521 public function getIP() {
1522 return $this->base->getIP();
1525 public function getProtocol() {
1526 return $this->base->getProtocol();
1529 public function getElapsedTime() {
1530 return $this->base->getElapsedTime();