Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / WebRequest.php
blob152a3d2d19d1a112fadb18fa95add54925ef4f1b
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 use MediaWiki\Session\Session;
27 use MediaWiki\Session\SessionId;
28 use MediaWiki\Session\SessionManager;
30 /**
31 * The WebRequest class encapsulates getting at data passed in the
32 * URL or via a POSTed form stripping illegal input characters and
33 * normalizing Unicode sequences.
35 * @ingroup HTTP
37 class WebRequest {
38 protected $data, $headers = [];
40 /**
41 * Flag to make WebRequest::getHeader return an array of values.
42 * @since 1.26
44 const GETHEADER_LIST = 1;
46 /**
47 * The unique request ID.
48 * @var string
50 private static $reqId;
52 /**
53 * Lazy-init response object
54 * @var WebResponse
56 private $response;
58 /**
59 * Cached client IP address
60 * @var string
62 private $ip;
64 /**
65 * The timestamp of the start of the request, with microsecond precision.
66 * @var float
68 protected $requestTime;
70 /**
71 * Cached URL protocol
72 * @var string
74 protected $protocol;
76 /**
77 * @var SessionId|null Session ID to use for this
78 * request. We can't save the session directly due to reference cycles not
79 * working too well (slow GC in Zend and never collected in HHVM).
81 protected $sessionId = null;
83 /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
84 protected $markedAsSafe = false;
86 public function __construct() {
87 $this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
88 ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
90 // POST overrides GET data
91 // We don't use $_REQUEST here to avoid interference from cookies...
92 $this->data = $_POST + $_GET;
95 /**
96 * Extract relevant query arguments from the http request uri's path
97 * to be merged with the normal php provided query arguments.
98 * Tries to use the REQUEST_URI data if available and parses it
99 * according to the wiki's configuration looking for any known pattern.
101 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
102 * provided by the server if any and use that to set a 'title' parameter.
104 * @param string $want If this is not 'all', then the function
105 * will return an empty array if it determines that the URL is
106 * inside a rewrite path.
108 * @return array Any query arguments found in path matches.
110 public static function getPathInfo( $want = 'all' ) {
111 global $wgUsePathInfo;
112 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
113 // And also by Apache 2.x, double slashes are converted to single slashes.
114 // So we will use REQUEST_URI if possible.
115 $matches = [];
116 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
117 // Slurp out the path portion to examine...
118 $url = $_SERVER['REQUEST_URI'];
119 if ( !preg_match( '!^https?://!', $url ) ) {
120 $url = 'http://unused' . $url;
122 MediaWiki\suppressWarnings();
123 $a = parse_url( $url );
124 MediaWiki\restoreWarnings();
125 if ( $a ) {
126 $path = isset( $a['path'] ) ? $a['path'] : '';
128 global $wgScript;
129 if ( $path == $wgScript && $want !== 'all' ) {
130 // Script inside a rewrite path?
131 // Abort to keep from breaking...
132 return $matches;
135 $router = new PathRouter;
137 // Raw PATH_INFO style
138 $router->add( "$wgScript/$1" );
140 if ( isset( $_SERVER['SCRIPT_NAME'] )
141 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
143 # Check for SCRIPT_NAME, we handle index.php explicitly
144 # But we do have some other .php files such as img_auth.php
145 # Don't let root article paths clober the parsing for them
146 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
149 global $wgArticlePath;
150 if ( $wgArticlePath ) {
151 $router->add( $wgArticlePath );
154 global $wgActionPaths;
155 if ( $wgActionPaths ) {
156 $router->add( $wgActionPaths, [ 'action' => '$key' ] );
159 global $wgVariantArticlePath, $wgContLang;
160 if ( $wgVariantArticlePath ) {
161 $router->add( $wgVariantArticlePath,
162 [ 'variant' => '$2' ],
163 [ '$2' => $wgContLang->getVariants() ]
167 Hooks::run( 'WebRequestPathInfoRouter', [ $router ] );
169 $matches = $router->parse( $path );
171 } elseif ( $wgUsePathInfo ) {
172 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
173 // Mangled PATH_INFO
174 // http://bugs.php.net/bug.php?id=31892
175 // Also reported when ini_get('cgi.fix_pathinfo')==false
176 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
178 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
179 // Regular old PATH_INFO yay
180 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
184 return $matches;
188 * Work out an appropriate URL prefix containing scheme and host, based on
189 * information detected from $_SERVER
191 * @return string
193 public static function detectServer() {
194 global $wgAssumeProxiesUseDefaultProtocolPorts;
196 $proto = self::detectProtocol();
197 $stdPort = $proto === 'https' ? 443 : 80;
199 $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
200 $host = 'localhost';
201 $port = $stdPort;
202 foreach ( $varNames as $varName ) {
203 if ( !isset( $_SERVER[$varName] ) ) {
204 continue;
207 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
208 if ( !$parts ) {
209 // Invalid, do not use
210 continue;
213 $host = $parts[0];
214 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
215 // Bug 70021: Assume that upstream proxy is running on the default
216 // port based on the protocol. We have no reliable way to determine
217 // the actual port in use upstream.
218 $port = $stdPort;
219 } elseif ( $parts[1] === false ) {
220 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
221 $port = $_SERVER['SERVER_PORT'];
222 } // else leave it as $stdPort
223 } else {
224 $port = $parts[1];
226 break;
229 return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
233 * Detect the protocol from $_SERVER.
234 * This is for use prior to Setup.php, when no WebRequest object is available.
235 * At other times, use the non-static function getProtocol().
237 * @return array
239 public static function detectProtocol() {
240 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
241 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
242 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
243 return 'https';
244 } else {
245 return 'http';
250 * Get the number of seconds to have elapsed since request start,
251 * in fractional seconds, with microsecond resolution.
253 * @return float
254 * @since 1.25
256 public function getElapsedTime() {
257 return microtime( true ) - $this->requestTime;
261 * Get the unique request ID.
262 * This is either the value of the UNIQUE_ID envvar (if present) or a
263 * randomly-generated 24-character string.
265 * @return string
266 * @since 1.27
268 public static function getRequestId() {
269 if ( !self::$reqId ) {
270 self::$reqId = isset( $_SERVER['UNIQUE_ID'] )
271 ? $_SERVER['UNIQUE_ID'] : wfRandomString( 24 );
274 return self::$reqId;
278 * Override the unique request ID. This is for sub-requests, such as jobs,
279 * that wish to use the same id but are not part of the same execution context.
281 * @param string $id
282 * @since 1.27
284 public static function overrideRequestId( $id ) {
285 self::$reqId = $id;
289 * Get the current URL protocol (http or https)
290 * @return string
292 public function getProtocol() {
293 if ( $this->protocol === null ) {
294 $this->protocol = self::detectProtocol();
296 return $this->protocol;
300 * Check for title, action, and/or variant data in the URL
301 * and interpolate it into the GET variables.
302 * This should only be run after $wgContLang is available,
303 * as we may need the list of language variants to determine
304 * available variant URLs.
306 public function interpolateTitle() {
307 // bug 16019: title interpolation on API queries is useless and sometimes harmful
308 if ( defined( 'MW_API' ) ) {
309 return;
312 $matches = self::getPathInfo( 'title' );
313 foreach ( $matches as $key => $val ) {
314 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
319 * URL rewriting function; tries to extract page title and,
320 * optionally, one other fixed parameter value from a URL path.
322 * @param string $path The URL path given from the client
323 * @param array $bases One or more URLs, optionally with $1 at the end
324 * @param string|bool $key If provided, the matching key in $bases will be
325 * passed on as the value of this URL parameter
326 * @return array Array of URL variables to interpolate; empty if no match
328 static function extractTitle( $path, $bases, $key = false ) {
329 foreach ( (array)$bases as $keyValue => $base ) {
330 // Find the part after $wgArticlePath
331 $base = str_replace( '$1', '', $base );
332 $baseLen = strlen( $base );
333 if ( substr( $path, 0, $baseLen ) == $base ) {
334 $raw = substr( $path, $baseLen );
335 if ( $raw !== '' ) {
336 $matches = [ 'title' => rawurldecode( $raw ) ];
337 if ( $key ) {
338 $matches[$key] = $keyValue;
340 return $matches;
344 return [];
348 * Recursively normalizes UTF-8 strings in the given array.
350 * @param string|array $data
351 * @return array|string Cleaned-up version of the given
352 * @private
354 function normalizeUnicode( $data ) {
355 if ( is_array( $data ) ) {
356 foreach ( $data as $key => $val ) {
357 $data[$key] = $this->normalizeUnicode( $val );
359 } else {
360 global $wgContLang;
361 $data = isset( $wgContLang ) ?
362 $wgContLang->normalize( $data ) :
363 UtfNormal\Validator::cleanUp( $data );
365 return $data;
369 * Fetch a value from the given array or return $default if it's not set.
371 * @param array $arr
372 * @param string $name
373 * @param mixed $default
374 * @return mixed
376 private function getGPCVal( $arr, $name, $default ) {
377 # PHP is so nice to not touch input data, except sometimes:
378 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
379 # Work around PHP *feature* to avoid *bugs* elsewhere.
380 $name = strtr( $name, '.', '_' );
381 if ( isset( $arr[$name] ) ) {
382 global $wgContLang;
383 $data = $arr[$name];
384 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
385 # Check for alternate/legacy character encoding.
386 if ( isset( $wgContLang ) ) {
387 $data = $wgContLang->checkTitleEncoding( $data );
390 $data = $this->normalizeUnicode( $data );
391 return $data;
392 } else {
393 return $default;
398 * Fetch a scalar from the input or return $default if it's not set.
399 * Returns a string. Arrays are discarded. Useful for
400 * non-freeform text inputs (e.g. predefined internal text keys
401 * selected by a drop-down menu). For freeform input, see getText().
403 * @param string $name
404 * @param string $default Optional default (or null)
405 * @return string
407 public function getVal( $name, $default = null ) {
408 $val = $this->getGPCVal( $this->data, $name, $default );
409 if ( is_array( $val ) ) {
410 $val = $default;
412 if ( is_null( $val ) ) {
413 return $val;
414 } else {
415 return (string)$val;
420 * Set an arbitrary value into our get/post data.
422 * @param string $key Key name to use
423 * @param mixed $value Value to set
424 * @return mixed Old value if one was present, null otherwise
426 public function setVal( $key, $value ) {
427 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
428 $this->data[$key] = $value;
429 return $ret;
433 * Unset an arbitrary value from our get/post data.
435 * @param string $key Key name to use
436 * @return mixed Old value if one was present, null otherwise
438 public function unsetVal( $key ) {
439 if ( !isset( $this->data[$key] ) ) {
440 $ret = null;
441 } else {
442 $ret = $this->data[$key];
443 unset( $this->data[$key] );
445 return $ret;
449 * Fetch an array from the input or return $default if it's not set.
450 * If source was scalar, will return an array with a single element.
451 * If no source and no default, returns null.
453 * @param string $name
454 * @param array $default Optional default (or null)
455 * @return array
457 public function getArray( $name, $default = null ) {
458 $val = $this->getGPCVal( $this->data, $name, $default );
459 if ( is_null( $val ) ) {
460 return null;
461 } else {
462 return (array)$val;
467 * Fetch an array of integers, or return $default if it's not set.
468 * If source was scalar, will return an array with a single element.
469 * If no source and no default, returns null.
470 * If an array is returned, contents are guaranteed to be integers.
472 * @param string $name
473 * @param array $default Option default (or null)
474 * @return array Array of ints
476 public function getIntArray( $name, $default = null ) {
477 $val = $this->getArray( $name, $default );
478 if ( is_array( $val ) ) {
479 $val = array_map( 'intval', $val );
481 return $val;
485 * Fetch an integer value from the input or return $default if not set.
486 * Guaranteed to return an integer; non-numeric input will typically
487 * return 0.
489 * @param string $name
490 * @param int $default
491 * @return int
493 public function getInt( $name, $default = 0 ) {
494 return intval( $this->getVal( $name, $default ) );
498 * Fetch an integer value from the input or return null if empty.
499 * Guaranteed to return an integer or null; non-numeric input will
500 * typically return null.
502 * @param string $name
503 * @return int|null
505 public function getIntOrNull( $name ) {
506 $val = $this->getVal( $name );
507 return is_numeric( $val )
508 ? intval( $val )
509 : null;
513 * Fetch a floating point value from the input or return $default if not set.
514 * Guaranteed to return a float; non-numeric input will typically
515 * return 0.
517 * @since 1.23
518 * @param string $name
519 * @param float $default
520 * @return float
522 public function getFloat( $name, $default = 0.0 ) {
523 return floatval( $this->getVal( $name, $default ) );
527 * Fetch a boolean value from the input or return $default if not set.
528 * Guaranteed to return true or false, with normal PHP semantics for
529 * boolean interpretation of strings.
531 * @param string $name
532 * @param bool $default
533 * @return bool
535 public function getBool( $name, $default = false ) {
536 return (bool)$this->getVal( $name, $default );
540 * Fetch a boolean value from the input or return $default if not set.
541 * Unlike getBool, the string "false" will result in boolean false, which is
542 * useful when interpreting information sent from JavaScript.
544 * @param string $name
545 * @param bool $default
546 * @return bool
548 public function getFuzzyBool( $name, $default = false ) {
549 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
553 * Return true if the named value is set in the input, whatever that
554 * value is (even "0"). Return false if the named value is not set.
555 * Example use is checking for the presence of check boxes in forms.
557 * @param string $name
558 * @return bool
560 public function getCheck( $name ) {
561 # Checkboxes and buttons are only present when clicked
562 # Presence connotes truth, absence false
563 return $this->getVal( $name, null ) !== null;
567 * Fetch a text string from the given array or return $default if it's not
568 * set. Carriage returns are stripped from the text, and with some language
569 * modules there is an input transliteration applied. This should generally
570 * be used for form "<textarea>" and "<input>" fields. Used for
571 * user-supplied freeform text input (for which input transformations may
572 * be required - e.g. Esperanto x-coding).
574 * @param string $name
575 * @param string $default Optional
576 * @return string
578 public function getText( $name, $default = '' ) {
579 global $wgContLang;
580 $val = $this->getVal( $name, $default );
581 return str_replace( "\r\n", "\n",
582 $wgContLang->recodeInput( $val ) );
586 * Extracts the given named values into an array.
587 * If no arguments are given, returns all input values.
588 * No transformation is performed on the values.
590 * @return array
592 public function getValues() {
593 $names = func_get_args();
594 if ( count( $names ) == 0 ) {
595 $names = array_keys( $this->data );
598 $retVal = [];
599 foreach ( $names as $name ) {
600 $value = $this->getGPCVal( $this->data, $name, null );
601 if ( !is_null( $value ) ) {
602 $retVal[$name] = $value;
605 return $retVal;
609 * Returns the names of all input values excluding those in $exclude.
611 * @param array $exclude
612 * @return array
614 public function getValueNames( $exclude = [] ) {
615 return array_diff( array_keys( $this->getValues() ), $exclude );
619 * Get the values passed in the query string.
620 * No transformation is performed on the values.
622 * @return array
624 public function getQueryValues() {
625 return $_GET;
629 * Return the contents of the Query with no decoding. Use when you need to
630 * know exactly what was sent, e.g. for an OAuth signature over the elements.
632 * @return string
634 public function getRawQueryString() {
635 return $_SERVER['QUERY_STRING'];
639 * Return the contents of the POST with no decoding. Use when you need to
640 * know exactly what was sent, e.g. for an OAuth signature over the elements.
642 * @return string
644 public function getRawPostString() {
645 if ( !$this->wasPosted() ) {
646 return '';
648 return $this->getRawInput();
652 * Return the raw request body, with no processing. Cached since some methods
653 * disallow reading the stream more than once. As stated in the php docs, this
654 * does not work with enctype="multipart/form-data".
656 * @return string
658 public function getRawInput() {
659 static $input = null;
660 if ( $input === null ) {
661 $input = file_get_contents( 'php://input' );
663 return $input;
667 * Get the HTTP method used for this request.
669 * @return string
671 public function getMethod() {
672 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
676 * Returns true if the present request was reached by a POST operation,
677 * false otherwise (GET, HEAD, or command-line).
679 * Note that values retrieved by the object may come from the
680 * GET URL etc even on a POST request.
682 * @return bool
684 public function wasPosted() {
685 return $this->getMethod() == 'POST';
689 * Return the session for this request
690 * @since 1.27
691 * @note For performance, keep the session locally if you will be making
692 * much use of it instead of calling this method repeatedly.
693 * @return Session
695 public function getSession() {
696 if ( $this->sessionId !== null ) {
697 $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
698 if ( $session ) {
699 return $session;
703 $session = SessionManager::singleton()->getSessionForRequest( $this );
704 $this->sessionId = $session->getSessionId();
705 return $session;
709 * Set the session for this request
710 * @since 1.27
711 * @private For use by MediaWiki\Session classes only
712 * @param SessionId $sessionId
714 public function setSessionId( SessionId $sessionId ) {
715 $this->sessionId = $sessionId;
719 * Get the session id for this request, if any
720 * @since 1.27
721 * @private For use by MediaWiki\Session classes only
722 * @return SessionId|null
724 public function getSessionId() {
725 return $this->sessionId;
729 * Returns true if the request has a persistent session.
730 * This does not necessarily mean that the user is logged in!
732 * @deprecated since 1.27, use
733 * \MediaWiki\Session\SessionManager::singleton()->getPersistedSessionId()
734 * instead.
735 * @return bool
737 public function checkSessionCookie() {
738 global $wgInitialSessionId;
739 wfDeprecated( __METHOD__, '1.27' );
740 return $wgInitialSessionId !== null &&
741 $this->getSession()->getId() === (string)$wgInitialSessionId;
745 * Get a cookie from the $_COOKIE jar
747 * @param string $key The name of the cookie
748 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
749 * @param mixed $default What to return if the value isn't found
750 * @return mixed Cookie value or $default if the cookie not set
752 public function getCookie( $key, $prefix = null, $default = null ) {
753 if ( $prefix === null ) {
754 global $wgCookiePrefix;
755 $prefix = $wgCookiePrefix;
757 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
761 * Return the path and query string portion of the main request URI.
762 * This will be suitable for use as a relative link in HTML output.
764 * @throws MWException
765 * @return string
767 public static function getGlobalRequestURL() {
768 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
769 $base = $_SERVER['REQUEST_URI'];
770 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
771 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
773 // Probably IIS; doesn't set REQUEST_URI
774 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
775 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
776 $base = $_SERVER['SCRIPT_NAME'];
777 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
778 $base .= '?' . $_SERVER['QUERY_STRING'];
780 } else {
781 // This shouldn't happen!
782 throw new MWException( "Web server doesn't provide either " .
783 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
784 "of your web server configuration to https://phabricator.wikimedia.org/" );
786 // User-agents should not send a fragment with the URI, but
787 // if they do, and the web server passes it on to us, we
788 // need to strip it or we get false-positive redirect loops
789 // or weird output URLs
790 $hash = strpos( $base, '#' );
791 if ( $hash !== false ) {
792 $base = substr( $base, 0, $hash );
795 if ( $base[0] == '/' ) {
796 // More than one slash will look like it is protocol relative
797 return preg_replace( '!^/+!', '/', $base );
798 } else {
799 // We may get paths with a host prepended; strip it.
800 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
805 * Return the path and query string portion of the request URI.
806 * This will be suitable for use as a relative link in HTML output.
808 * @throws MWException
809 * @return string
811 public function getRequestURL() {
812 return self::getGlobalRequestURL();
816 * Return the request URI with the canonical service and hostname, path,
817 * and query string. This will be suitable for use as an absolute link
818 * in HTML or other output.
820 * If $wgServer is protocol-relative, this will return a fully
821 * qualified URL with the protocol that was used for this request.
823 * @return string
825 public function getFullRequestURL() {
826 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
830 * @param string $key
831 * @param string $value
832 * @return string
834 public function appendQueryValue( $key, $value ) {
835 return $this->appendQueryArray( [ $key => $value ] );
839 * Appends or replaces value of query variables.
841 * @param array $array Array of values to replace/add to query
842 * @return string
844 public function appendQueryArray( $array ) {
845 $newquery = $this->getQueryValues();
846 unset( $newquery['title'] );
847 $newquery = array_merge( $newquery, $array );
849 return wfArrayToCgi( $newquery );
853 * Check for limit and offset parameters on the input, and return sensible
854 * defaults if not given. The limit must be positive and is capped at 5000.
855 * Offset must be positive but is not capped.
857 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
858 * @param string $optionname To specify an option other than rclimit to pull from.
859 * @return int[] First element is limit, second is offset
861 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
862 global $wgUser;
864 $limit = $this->getInt( 'limit', 0 );
865 if ( $limit < 0 ) {
866 $limit = 0;
868 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
869 $limit = $wgUser->getIntOption( $optionname );
871 if ( $limit <= 0 ) {
872 $limit = $deflimit;
874 if ( $limit > 5000 ) {
875 $limit = 5000; # We have *some* limits...
878 $offset = $this->getInt( 'offset', 0 );
879 if ( $offset < 0 ) {
880 $offset = 0;
883 return [ $limit, $offset ];
887 * Return the path to the temporary file where PHP has stored the upload.
889 * @param string $key
890 * @return string|null String or null if no such file.
892 public function getFileTempname( $key ) {
893 $file = new WebRequestUpload( $this, $key );
894 return $file->getTempName();
898 * Return the upload error or 0
900 * @param string $key
901 * @return int
903 public function getUploadError( $key ) {
904 $file = new WebRequestUpload( $this, $key );
905 return $file->getError();
909 * Return the original filename of the uploaded file, as reported by
910 * the submitting user agent. HTML-style character entities are
911 * interpreted and normalized to Unicode normalization form C, in part
912 * to deal with weird input from Safari with non-ASCII filenames.
914 * Other than this the name is not verified for being a safe filename.
916 * @param string $key
917 * @return string|null String or null if no such file.
919 public function getFileName( $key ) {
920 $file = new WebRequestUpload( $this, $key );
921 return $file->getName();
925 * Return a WebRequestUpload object corresponding to the key
927 * @param string $key
928 * @return WebRequestUpload
930 public function getUpload( $key ) {
931 return new WebRequestUpload( $this, $key );
935 * Return a handle to WebResponse style object, for setting cookies,
936 * headers and other stuff, for Request being worked on.
938 * @return WebResponse
940 public function response() {
941 /* Lazy initialization of response object for this request */
942 if ( !is_object( $this->response ) ) {
943 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
944 $this->response = new $class();
946 return $this->response;
950 * Initialise the header list
952 protected function initHeaders() {
953 if ( count( $this->headers ) ) {
954 return;
957 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
958 if ( $apacheHeaders ) {
959 foreach ( $apacheHeaders as $tempName => $tempValue ) {
960 $this->headers[strtoupper( $tempName )] = $tempValue;
962 } else {
963 foreach ( $_SERVER as $name => $value ) {
964 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
965 $name = str_replace( '_', '-', substr( $name, 5 ) );
966 $this->headers[$name] = $value;
967 } elseif ( $name === 'CONTENT_LENGTH' ) {
968 $this->headers['CONTENT-LENGTH'] = $value;
975 * Get an array containing all request headers
977 * @return array Mapping header name to its value
979 public function getAllHeaders() {
980 $this->initHeaders();
981 return $this->headers;
985 * Get a request header, or false if it isn't set.
987 * @param string $name Case-insensitive header name
988 * @param int $flags Bitwise combination of:
989 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
990 * of values, as described in RFC 2616 § 4.2.
991 * (since 1.26).
992 * @return string|array|bool False if header is unset; otherwise the
993 * header value(s) as either a string (the default) or an array, if
994 * WebRequest::GETHEADER_LIST flag was set.
996 public function getHeader( $name, $flags = 0 ) {
997 $this->initHeaders();
998 $name = strtoupper( $name );
999 if ( !isset( $this->headers[$name] ) ) {
1000 return false;
1002 $value = $this->headers[$name];
1003 if ( $flags & self::GETHEADER_LIST ) {
1004 $value = array_map( 'trim', explode( ',', $value ) );
1006 return $value;
1010 * Get data from the session
1012 * @note Prefer $this->getSession() instead if making multiple calls.
1013 * @param string $key Name of key in the session
1014 * @return mixed
1016 public function getSessionData( $key ) {
1017 return $this->getSession()->get( $key );
1021 * Set session data
1023 * @note Prefer $this->getSession() instead if making multiple calls.
1024 * @param string $key Name of key in the session
1025 * @param mixed $data
1027 public function setSessionData( $key, $data ) {
1028 $this->getSession()->set( $key, $data );
1032 * Check if Internet Explorer will detect an incorrect cache extension in
1033 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1034 * message or redirect to a safer URL. Returns true if the URL is OK, and
1035 * false if an error message has been shown and the request should be aborted.
1037 * @param array $extWhitelist
1038 * @throws HttpError
1039 * @return bool
1041 public function checkUrlExtension( $extWhitelist = [] ) {
1042 $extWhitelist[] = 'php';
1043 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1044 if ( !$this->wasPosted() ) {
1045 $newUrl = IEUrlExtension::fixUrlForIE6(
1046 $this->getFullRequestURL(), $extWhitelist );
1047 if ( $newUrl !== false ) {
1048 $this->doSecurityRedirect( $newUrl );
1049 return false;
1052 throw new HttpError( 403,
1053 'Invalid file extension found in the path info or query string.' );
1055 return true;
1059 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1060 * IE 6. Returns true if it was successful, false otherwise.
1062 * @param string $url
1063 * @return bool
1065 protected function doSecurityRedirect( $url ) {
1066 header( 'Location: ' . $url );
1067 header( 'Content-Type: text/html' );
1068 $encUrl = htmlspecialchars( $url );
1069 echo <<<HTML
1070 <html>
1071 <head>
1072 <title>Security redirect</title>
1073 </head>
1074 <body>
1075 <h1>Security redirect</h1>
1077 We can't serve non-HTML content from the URL you have requested, because
1078 Internet Explorer would interpret it as an incorrect and potentially dangerous
1079 content type.</p>
1080 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1081 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1082 Explorer from seeing a bogus file extension.
1083 </p>
1084 </body>
1085 </html>
1086 HTML;
1087 echo "\n";
1088 return true;
1092 * Parse the Accept-Language header sent by the client into an array
1094 * @return array Array( languageCode => q-value ) sorted by q-value in
1095 * descending order then appearing time in the header in ascending order.
1096 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1097 * This is aligned with rfc2616 section 14.4
1098 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1100 public function getAcceptLang() {
1101 // Modified version of code found at
1102 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1103 $acceptLang = $this->getHeader( 'Accept-Language' );
1104 if ( !$acceptLang ) {
1105 return [];
1108 // Return the language codes in lower case
1109 $acceptLang = strtolower( $acceptLang );
1111 // Break up string into pieces (languages and q factors)
1112 $lang_parse = null;
1113 preg_match_all(
1114 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1115 $acceptLang,
1116 $lang_parse
1119 if ( !count( $lang_parse[1] ) ) {
1120 return [];
1123 $langcodes = $lang_parse[1];
1124 $qvalues = $lang_parse[4];
1125 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1127 // Set default q factor to 1
1128 foreach ( $indices as $index ) {
1129 if ( $qvalues[$index] === '' ) {
1130 $qvalues[$index] = 1;
1131 } elseif ( $qvalues[$index] == 0 ) {
1132 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1136 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1137 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1139 // Create a list like "en" => 0.8
1140 $langs = array_combine( $langcodes, $qvalues );
1142 return $langs;
1146 * Fetch the raw IP from the request
1148 * @since 1.19
1150 * @throws MWException
1151 * @return string
1153 protected function getRawIP() {
1154 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1155 return null;
1158 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1159 throw new MWException( __METHOD__
1160 . " : Could not determine the remote IP address due to multiple values." );
1161 } else {
1162 $ipchain = $_SERVER['REMOTE_ADDR'];
1165 return IP::canonicalize( $ipchain );
1169 * Work out the IP address based on various globals
1170 * For trusted proxies, use the XFF client IP (first of the chain)
1172 * @since 1.19
1174 * @throws MWException
1175 * @return string
1177 public function getIP() {
1178 global $wgUsePrivateIPs;
1180 # Return cached result
1181 if ( $this->ip !== null ) {
1182 return $this->ip;
1185 # collect the originating ips
1186 $ip = $this->getRawIP();
1187 if ( !$ip ) {
1188 throw new MWException( 'Unable to determine IP.' );
1191 # Append XFF
1192 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1193 if ( $forwardedFor !== false ) {
1194 $isConfigured = IP::isConfiguredProxy( $ip );
1195 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1196 $ipchain = array_reverse( $ipchain );
1197 array_unshift( $ipchain, $ip );
1199 # Step through XFF list and find the last address in the list which is a
1200 # trusted server. Set $ip to the IP address given by that trusted server,
1201 # unless the address is not sensible (e.g. private). However, prefer private
1202 # IP addresses over proxy servers controlled by this site (more sensible).
1203 # Note that some XFF values might be "unknown" with Squid/Varnish.
1204 foreach ( $ipchain as $i => $curIP ) {
1205 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1206 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1207 || !IP::isTrustedProxy( $curIP )
1209 break; // IP is not valid/trusted or does not point to anything
1211 if (
1212 IP::isPublic( $ipchain[$i + 1] ) ||
1213 $wgUsePrivateIPs ||
1214 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1216 // Follow the next IP according to the proxy
1217 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1218 if ( !$nextIP && $isConfigured ) {
1219 // We have not yet made it past CDN/proxy servers of this site,
1220 // so either they are misconfigured or there is some IP spoofing.
1221 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1223 $ip = $nextIP;
1224 // keep traversing the chain
1225 continue;
1227 break;
1231 # Allow extensions to improve our guess
1232 Hooks::run( 'GetIP', [ &$ip ] );
1234 if ( !$ip ) {
1235 throw new MWException( "Unable to determine IP." );
1238 wfDebug( "IP: $ip\n" );
1239 $this->ip = $ip;
1240 return $ip;
1244 * @param string $ip
1245 * @return void
1246 * @since 1.21
1248 public function setIP( $ip ) {
1249 $this->ip = $ip;
1253 * Check if this request uses a "safe" HTTP method
1255 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1256 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1257 * like POST and PUT are typical of non-safe requests which often change content.
1259 * @return bool
1260 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1261 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1262 * @since 1.28
1264 public function hasSafeMethod() {
1265 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1266 return false; // CLI mode
1269 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1273 * Whether this request should be identified as being "safe"
1275 * This means that the client is not requesting any state changes and that database writes
1276 * are not inherently required. Ideally, no visible updates would happen at all. If they
1277 * must, then they should not be publically attributed to the end user.
1279 * In more detail:
1280 * - Cache populations and refreshes MAY occur.
1281 * - Private user session updates and private server logging MAY occur.
1282 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1283 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1285 * @return bool
1286 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1287 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1288 * @since 1.28
1290 public function isSafeRequest() {
1291 if ( $this->markedAsSafe && $this->wasPosted() ) {
1292 return true; // marked as a "safe" POST
1295 return $this->hasSafeMethod();
1299 * Mark this request as identified as being nullipotent even if it is a POST request
1301 * POST requests are often used due to the need for a client payload, even if the request
1302 * is otherwise equivalent to a "safe method" request.
1304 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1305 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1306 * @since 1.28
1308 public function markAsSafeRequest() {
1309 $this->markedAsSafe = true;