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
26 use MediaWiki\Session\SessionManager
;
29 * The WebRequest class encapsulates getting at data passed in the
30 * URL or via a POSTed form stripping illegal input characters and
31 * normalizing Unicode sequences.
36 protected $data, $headers = [];
39 * Flag to make WebRequest::getHeader return an array of values.
42 const GETHEADER_LIST
= 1;
45 * Lazy-init response object
51 * Cached client IP address
57 * The timestamp of the start of the request, with microsecond precision.
60 protected $requestTime;
69 * @var \\MediaWiki\\Session\\SessionId|null Session ID to use for this
70 * request. We can't save the session directly due to reference cycles not
71 * working too well (slow GC in Zend and never collected in HHVM).
73 protected $sessionId = null;
75 public function __construct() {
76 $this->requestTime
= isset( $_SERVER['REQUEST_TIME_FLOAT'] )
77 ?
$_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
79 // POST overrides GET data
80 // We don't use $_REQUEST here to avoid interference from cookies...
81 $this->data
= $_POST +
$_GET;
85 * Extract relevant query arguments from the http request uri's path
86 * to be merged with the normal php provided query arguments.
87 * Tries to use the REQUEST_URI data if available and parses it
88 * according to the wiki's configuration looking for any known pattern.
90 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
91 * provided by the server if any and use that to set a 'title' parameter.
93 * @param string $want If this is not 'all', then the function
94 * will return an empty array if it determines that the URL is
95 * inside a rewrite path.
97 * @return array Any query arguments found in path matches.
99 public static function getPathInfo( $want = 'all' ) {
100 global $wgUsePathInfo;
101 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
102 // And also by Apache 2.x, double slashes are converted to single slashes.
103 // So we will use REQUEST_URI if possible.
105 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
106 // Slurp out the path portion to examine...
107 $url = $_SERVER['REQUEST_URI'];
108 if ( !preg_match( '!^https?://!', $url ) ) {
109 $url = 'http://unused' . $url;
111 MediaWiki\
suppressWarnings();
112 $a = parse_url( $url );
113 MediaWiki\restoreWarnings
();
115 $path = isset( $a['path'] ) ?
$a['path'] : '';
118 if ( $path == $wgScript && $want !== 'all' ) {
119 // Script inside a rewrite path?
120 // Abort to keep from breaking...
124 $router = new PathRouter
;
126 // Raw PATH_INFO style
127 $router->add( "$wgScript/$1" );
129 if ( isset( $_SERVER['SCRIPT_NAME'] )
130 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
132 # Check for SCRIPT_NAME, we handle index.php explicitly
133 # But we do have some other .php files such as img_auth.php
134 # Don't let root article paths clober the parsing for them
135 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
138 global $wgArticlePath;
139 if ( $wgArticlePath ) {
140 $router->add( $wgArticlePath );
143 global $wgActionPaths;
144 if ( $wgActionPaths ) {
145 $router->add( $wgActionPaths, [ 'action' => '$key' ] );
148 global $wgVariantArticlePath, $wgContLang;
149 if ( $wgVariantArticlePath ) {
150 $router->add( $wgVariantArticlePath,
151 [ 'variant' => '$2' ],
152 [ '$2' => $wgContLang->getVariants() ]
156 Hooks
::run( 'WebRequestPathInfoRouter', [ $router ] );
158 $matches = $router->parse( $path );
160 } elseif ( $wgUsePathInfo ) {
161 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
163 // http://bugs.php.net/bug.php?id=31892
164 // Also reported when ini_get('cgi.fix_pathinfo')==false
165 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
167 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
168 // Regular old PATH_INFO yay
169 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
177 * Work out an appropriate URL prefix containing scheme and host, based on
178 * information detected from $_SERVER
182 public static function detectServer() {
183 global $wgAssumeProxiesUseDefaultProtocolPorts;
185 $proto = self
::detectProtocol();
186 $stdPort = $proto === 'https' ?
443 : 80;
188 $varNames = [ 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' ];
191 foreach ( $varNames as $varName ) {
192 if ( !isset( $_SERVER[$varName] ) ) {
196 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
198 // Invalid, do not use
203 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
204 // Bug 70021: Assume that upstream proxy is running on the default
205 // port based on the protocol. We have no reliable way to determine
206 // the actual port in use upstream.
208 } elseif ( $parts[1] === false ) {
209 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
210 $port = $_SERVER['SERVER_PORT'];
211 } // else leave it as $stdPort
218 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
222 * Detect the protocol from $_SERVER.
223 * This is for use prior to Setup.php, when no WebRequest object is available.
224 * At other times, use the non-static function getProtocol().
228 public static function detectProtocol() {
229 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
230 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
231 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
239 * Get the number of seconds to have elapsed since request start,
240 * in fractional seconds, with microsecond resolution.
245 public function getElapsedTime() {
246 return microtime( true ) - $this->requestTime
;
250 * Get the current URL protocol (http or https)
253 public function getProtocol() {
254 if ( $this->protocol
=== null ) {
255 $this->protocol
= self
::detectProtocol();
257 return $this->protocol
;
261 * Check for title, action, and/or variant data in the URL
262 * and interpolate it into the GET variables.
263 * This should only be run after $wgContLang is available,
264 * as we may need the list of language variants to determine
265 * available variant URLs.
267 public function interpolateTitle() {
268 // bug 16019: title interpolation on API queries is useless and sometimes harmful
269 if ( defined( 'MW_API' ) ) {
273 $matches = self
::getPathInfo( 'title' );
274 foreach ( $matches as $key => $val ) {
275 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
280 * URL rewriting function; tries to extract page title and,
281 * optionally, one other fixed parameter value from a URL path.
283 * @param string $path The URL path given from the client
284 * @param array $bases One or more URLs, optionally with $1 at the end
285 * @param string $key If provided, the matching key in $bases will be
286 * passed on as the value of this URL parameter
287 * @return array Array of URL variables to interpolate; empty if no match
289 static function extractTitle( $path, $bases, $key = false ) {
290 foreach ( (array)$bases as $keyValue => $base ) {
291 // Find the part after $wgArticlePath
292 $base = str_replace( '$1', '', $base );
293 $baseLen = strlen( $base );
294 if ( substr( $path, 0, $baseLen ) == $base ) {
295 $raw = substr( $path, $baseLen );
297 $matches = [ 'title' => rawurldecode( $raw ) ];
299 $matches[$key] = $keyValue;
309 * Recursively normalizes UTF-8 strings in the given array.
311 * @param string|array $data
312 * @return array|string Cleaned-up version of the given
315 function normalizeUnicode( $data ) {
316 if ( is_array( $data ) ) {
317 foreach ( $data as $key => $val ) {
318 $data[$key] = $this->normalizeUnicode( $val );
322 $data = isset( $wgContLang ) ?
323 $wgContLang->normalize( $data ) :
324 UtfNormal\Validator
::cleanUp( $data );
330 * Fetch a value from the given array or return $default if it's not set.
333 * @param string $name
334 * @param mixed $default
337 private function getGPCVal( $arr, $name, $default ) {
338 # PHP is so nice to not touch input data, except sometimes:
339 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
340 # Work around PHP *feature* to avoid *bugs* elsewhere.
341 $name = strtr( $name, '.', '_' );
342 if ( isset( $arr[$name] ) ) {
345 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
346 # Check for alternate/legacy character encoding.
347 if ( isset( $wgContLang ) ) {
348 $data = $wgContLang->checkTitleEncoding( $data );
351 $data = $this->normalizeUnicode( $data );
359 * Fetch a scalar from the input or return $default if it's not set.
360 * Returns a string. Arrays are discarded. Useful for
361 * non-freeform text inputs (e.g. predefined internal text keys
362 * selected by a drop-down menu). For freeform input, see getText().
364 * @param string $name
365 * @param string $default Optional default (or null)
368 public function getVal( $name, $default = null ) {
369 $val = $this->getGPCVal( $this->data
, $name, $default );
370 if ( is_array( $val ) ) {
373 if ( is_null( $val ) ) {
381 * Set an arbitrary value into our get/post data.
383 * @param string $key Key name to use
384 * @param mixed $value Value to set
385 * @return mixed Old value if one was present, null otherwise
387 public function setVal( $key, $value ) {
388 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
389 $this->data
[$key] = $value;
394 * Unset an arbitrary value from our get/post data.
396 * @param string $key Key name to use
397 * @return mixed Old value if one was present, null otherwise
399 public function unsetVal( $key ) {
400 if ( !isset( $this->data
[$key] ) ) {
403 $ret = $this->data
[$key];
404 unset( $this->data
[$key] );
410 * Fetch an array from the input or return $default if it's not set.
411 * If source was scalar, will return an array with a single element.
412 * If no source and no default, returns null.
414 * @param string $name
415 * @param array $default Optional default (or null)
418 public function getArray( $name, $default = null ) {
419 $val = $this->getGPCVal( $this->data
, $name, $default );
420 if ( is_null( $val ) ) {
428 * Fetch an array of integers, or return $default if it's not set.
429 * If source was scalar, will return an array with a single element.
430 * If no source and no default, returns null.
431 * If an array is returned, contents are guaranteed to be integers.
433 * @param string $name
434 * @param array $default Option default (or null)
435 * @return array Array of ints
437 public function getIntArray( $name, $default = null ) {
438 $val = $this->getArray( $name, $default );
439 if ( is_array( $val ) ) {
440 $val = array_map( 'intval', $val );
446 * Fetch an integer value from the input or return $default if not set.
447 * Guaranteed to return an integer; non-numeric input will typically
450 * @param string $name
451 * @param int $default
454 public function getInt( $name, $default = 0 ) {
455 return intval( $this->getVal( $name, $default ) );
459 * Fetch an integer value from the input or return null if empty.
460 * Guaranteed to return an integer or null; non-numeric input will
461 * typically return null.
463 * @param string $name
466 public function getIntOrNull( $name ) {
467 $val = $this->getVal( $name );
468 return is_numeric( $val )
474 * Fetch a floating point value from the input or return $default if not set.
475 * Guaranteed to return a float; non-numeric input will typically
479 * @param string $name
480 * @param float $default
483 public function getFloat( $name, $default = 0.0 ) {
484 return floatval( $this->getVal( $name, $default ) );
488 * Fetch a boolean value from the input or return $default if not set.
489 * Guaranteed to return true or false, with normal PHP semantics for
490 * boolean interpretation of strings.
492 * @param string $name
493 * @param bool $default
496 public function getBool( $name, $default = false ) {
497 return (bool)$this->getVal( $name, $default );
501 * Fetch a boolean value from the input or return $default if not set.
502 * Unlike getBool, the string "false" will result in boolean false, which is
503 * useful when interpreting information sent from JavaScript.
505 * @param string $name
506 * @param bool $default
509 public function getFuzzyBool( $name, $default = false ) {
510 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
514 * Return true if the named value is set in the input, whatever that
515 * value is (even "0"). Return false if the named value is not set.
516 * Example use is checking for the presence of check boxes in forms.
518 * @param string $name
521 public function getCheck( $name ) {
522 # Checkboxes and buttons are only present when clicked
523 # Presence connotes truth, absence false
524 return $this->getVal( $name, null ) !== null;
528 * Fetch a text string from the given array or return $default if it's not
529 * set. Carriage returns are stripped from the text, and with some language
530 * modules there is an input transliteration applied. This should generally
531 * be used for form "<textarea>" and "<input>" fields. Used for
532 * user-supplied freeform text input (for which input transformations may
533 * be required - e.g. Esperanto x-coding).
535 * @param string $name
536 * @param string $default Optional
539 public function getText( $name, $default = '' ) {
541 $val = $this->getVal( $name, $default );
542 return str_replace( "\r\n", "\n",
543 $wgContLang->recodeInput( $val ) );
547 * Extracts the given named values into an array.
548 * If no arguments are given, returns all input values.
549 * No transformation is performed on the values.
553 public function getValues() {
554 $names = func_get_args();
555 if ( count( $names ) == 0 ) {
556 $names = array_keys( $this->data
);
560 foreach ( $names as $name ) {
561 $value = $this->getGPCVal( $this->data
, $name, null );
562 if ( !is_null( $value ) ) {
563 $retVal[$name] = $value;
570 * Returns the names of all input values excluding those in $exclude.
572 * @param array $exclude
575 public function getValueNames( $exclude = [] ) {
576 return array_diff( array_keys( $this->getValues() ), $exclude );
580 * Get the values passed in the query string.
581 * No transformation is performed on the values.
585 public function getQueryValues() {
590 * Return the contents of the Query with no decoding. Use when you need to
591 * know exactly what was sent, e.g. for an OAuth signature over the elements.
595 public function getRawQueryString() {
596 return $_SERVER['QUERY_STRING'];
600 * Return the contents of the POST with no decoding. Use when you need to
601 * know exactly what was sent, e.g. for an OAuth signature over the elements.
605 public function getRawPostString() {
606 if ( !$this->wasPosted() ) {
609 return $this->getRawInput();
613 * Return the raw request body, with no processing. Cached since some methods
614 * disallow reading the stream more than once. As stated in the php docs, this
615 * does not work with enctype="multipart/form-data".
619 public function getRawInput() {
620 static $input = null;
621 if ( $input === null ) {
622 $input = file_get_contents( 'php://input' );
628 * Get the HTTP method used for this request.
632 public function getMethod() {
633 return isset( $_SERVER['REQUEST_METHOD'] ) ?
$_SERVER['REQUEST_METHOD'] : 'GET';
637 * Returns true if the present request was reached by a POST operation,
638 * false otherwise (GET, HEAD, or command-line).
640 * Note that values retrieved by the object may come from the
641 * GET URL etc even on a POST request.
645 public function wasPosted() {
646 return $this->getMethod() == 'POST';
650 * Return the session for this request
652 * @note For performance, keep the session locally if you will be making
653 * much use of it instead of calling this method repeatedly.
654 * @return MediaWiki\\Session\\Session
656 public function getSession() {
657 if ( $this->sessionId
!== null ) {
658 $session = SessionManager
::singleton()->getSessionById( (string)$this->sessionId
, true, $this );
664 $session = SessionManager
::singleton()->getSessionForRequest( $this );
665 $this->sessionId
= $session->getSessionId();
670 * Set the session for this request
672 * @private For use by MediaWiki\\Session classes only
673 * @param MediaWiki\\Session\\SessionId $sessionId
675 public function setSessionId( MediaWiki\Session\SessionId
$sessionId ) {
676 $this->sessionId
= $sessionId;
680 * Returns true if the request has a persistent session.
681 * This does not necessarily mean that the user is logged in!
683 * @deprecated since 1.27, use
684 * \\MediaWiki\\Session\\SessionManager::singleton()->getPersistedSessionId()
688 public function checkSessionCookie() {
689 global $wgInitialSessionId;
690 wfDeprecated( __METHOD__
, '1.27' );
691 return $wgInitialSessionId !== null &&
692 $this->getSession()->getId() === (string)$wgInitialSessionId;
696 * Get a cookie from the $_COOKIE jar
698 * @param string $key The name of the cookie
699 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
700 * @param mixed $default What to return if the value isn't found
701 * @return mixed Cookie value or $default if the cookie not set
703 public function getCookie( $key, $prefix = null, $default = null ) {
704 if ( $prefix === null ) {
705 global $wgCookiePrefix;
706 $prefix = $wgCookiePrefix;
708 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
712 * Return the path and query string portion of the request URI.
713 * This will be suitable for use as a relative link in HTML output.
715 * @throws MWException
718 public function getRequestURL() {
719 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
720 $base = $_SERVER['REQUEST_URI'];
721 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
722 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
724 // Probably IIS; doesn't set REQUEST_URI
725 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
726 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
727 $base = $_SERVER['SCRIPT_NAME'];
728 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
729 $base .= '?' . $_SERVER['QUERY_STRING'];
732 // This shouldn't happen!
733 throw new MWException( "Web server doesn't provide either " .
734 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
735 "of your web server configuration to https://phabricator.wikimedia.org/" );
737 // User-agents should not send a fragment with the URI, but
738 // if they do, and the web server passes it on to us, we
739 // need to strip it or we get false-positive redirect loops
740 // or weird output URLs
741 $hash = strpos( $base, '#' );
742 if ( $hash !== false ) {
743 $base = substr( $base, 0, $hash );
746 if ( $base[0] == '/' ) {
747 // More than one slash will look like it is protocol relative
748 return preg_replace( '!^/+!', '/', $base );
750 // We may get paths with a host prepended; strip it.
751 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
756 * Return the request URI with the canonical service and hostname, path,
757 * and query string. This will be suitable for use as an absolute link
758 * in HTML or other output.
760 * If $wgServer is protocol-relative, this will return a fully
761 * qualified URL with the protocol that was used for this request.
765 public function getFullRequestURL() {
766 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
771 * @param string $value
774 public function appendQueryValue( $key, $value ) {
775 return $this->appendQueryArray( [ $key => $value ] );
779 * Appends or replaces value of query variables.
781 * @param array $array Array of values to replace/add to query
784 public function appendQueryArray( $array ) {
785 $newquery = $this->getQueryValues();
786 unset( $newquery['title'] );
787 $newquery = array_merge( $newquery, $array );
789 return wfArrayToCgi( $newquery );
793 * Check for limit and offset parameters on the input, and return sensible
794 * defaults if not given. The limit must be positive and is capped at 5000.
795 * Offset must be positive but is not capped.
797 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
798 * @param string $optionname To specify an option other than rclimit to pull from.
799 * @return int[] First element is limit, second is offset
801 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
804 $limit = $this->getInt( 'limit', 0 );
808 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
809 $limit = $wgUser->getIntOption( $optionname );
814 if ( $limit > 5000 ) {
815 $limit = 5000; # We have *some* limits...
818 $offset = $this->getInt( 'offset', 0 );
823 return [ $limit, $offset ];
827 * Return the path to the temporary file where PHP has stored the upload.
830 * @return string|null String or null if no such file.
832 public function getFileTempname( $key ) {
833 $file = new WebRequestUpload( $this, $key );
834 return $file->getTempName();
838 * Return the upload error or 0
843 public function getUploadError( $key ) {
844 $file = new WebRequestUpload( $this, $key );
845 return $file->getError();
849 * Return the original filename of the uploaded file, as reported by
850 * the submitting user agent. HTML-style character entities are
851 * interpreted and normalized to Unicode normalization form C, in part
852 * to deal with weird input from Safari with non-ASCII filenames.
854 * Other than this the name is not verified for being a safe filename.
857 * @return string|null String or null if no such file.
859 public function getFileName( $key ) {
860 $file = new WebRequestUpload( $this, $key );
861 return $file->getName();
865 * Return a WebRequestUpload object corresponding to the key
868 * @return WebRequestUpload
870 public function getUpload( $key ) {
871 return new WebRequestUpload( $this, $key );
875 * Return a handle to WebResponse style object, for setting cookies,
876 * headers and other stuff, for Request being worked on.
878 * @return WebResponse
880 public function response() {
881 /* Lazy initialization of response object for this request */
882 if ( !is_object( $this->response
) ) {
883 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
884 $this->response
= new $class();
886 return $this->response
;
890 * Initialise the header list
892 protected function initHeaders() {
893 if ( count( $this->headers
) ) {
897 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
898 if ( $apacheHeaders ) {
899 foreach ( $apacheHeaders as $tempName => $tempValue ) {
900 $this->headers
[strtoupper( $tempName )] = $tempValue;
903 foreach ( $_SERVER as $name => $value ) {
904 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
905 $name = str_replace( '_', '-', substr( $name, 5 ) );
906 $this->headers
[$name] = $value;
907 } elseif ( $name === 'CONTENT_LENGTH' ) {
908 $this->headers
['CONTENT-LENGTH'] = $value;
915 * Get an array containing all request headers
917 * @return array Mapping header name to its value
919 public function getAllHeaders() {
920 $this->initHeaders();
921 return $this->headers
;
925 * Get a request header, or false if it isn't set.
927 * @param string $name Case-insensitive header name
928 * @param int $flags Bitwise combination of:
929 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
930 * of values, as described in RFC 2616 § 4.2.
932 * @return string|array|bool False if header is unset; otherwise the
933 * header value(s) as either a string (the default) or an array, if
934 * WebRequest::GETHEADER_LIST flag was set.
936 public function getHeader( $name, $flags = 0 ) {
937 $this->initHeaders();
938 $name = strtoupper( $name );
939 if ( !isset( $this->headers
[$name] ) ) {
942 $value = $this->headers
[$name];
943 if ( $flags & self
::GETHEADER_LIST
) {
944 $value = array_map( 'trim', explode( ',', $value ) );
950 * Get data from the session
952 * @note Prefer $this->getSession() instead if making multiple calls.
953 * @param string $key Name of key in the session
956 public function getSessionData( $key ) {
957 return $this->getSession()->get( $key );
963 * @note Prefer $this->getSession() instead if making multiple calls.
964 * @param string $key Name of key in the session
967 public function setSessionData( $key, $data ) {
968 return $this->getSession()->set( $key, $data );
972 * Check if Internet Explorer will detect an incorrect cache extension in
973 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
974 * message or redirect to a safer URL. Returns true if the URL is OK, and
975 * false if an error message has been shown and the request should be aborted.
977 * @param array $extWhitelist
981 public function checkUrlExtension( $extWhitelist = [] ) {
982 $extWhitelist[] = 'php';
983 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
984 if ( !$this->wasPosted() ) {
985 $newUrl = IEUrlExtension
::fixUrlForIE6(
986 $this->getFullRequestURL(), $extWhitelist );
987 if ( $newUrl !== false ) {
988 $this->doSecurityRedirect( $newUrl );
992 throw new HttpError( 403,
993 'Invalid file extension found in the path info or query string.' );
999 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1000 * IE 6. Returns true if it was successful, false otherwise.
1002 * @param string $url
1005 protected function doSecurityRedirect( $url ) {
1006 header( 'Location: ' . $url );
1007 header( 'Content-Type: text/html' );
1008 $encUrl = htmlspecialchars( $url );
1012 <title>Security redirect</title>
1015 <h1>Security redirect</h1>
1017 We can't serve non-HTML content from the URL you have requested
, because
1018 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
1020 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
1021 URL you have requested
, except that
"&*" is appended
. This prevents Internet
1022 Explorer from seeing a bogus file extension
.
1032 * Parse the Accept-Language header sent by the client into an array
1034 * @return array Array( languageCode => q-value ) sorted by q-value in
1035 * descending order then appearing time in the header in ascending order.
1036 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1037 * This is aligned with rfc2616 section 14.4
1038 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1040 public function getAcceptLang() {
1041 // Modified version of code found at
1042 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1043 $acceptLang = $this->getHeader( 'Accept-Language' );
1044 if ( !$acceptLang ) {
1048 // Return the language codes in lower case
1049 $acceptLang = strtolower( $acceptLang );
1051 // Break up string into pieces (languages and q factors)
1054 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1059 if ( !count( $lang_parse[1] ) ) {
1063 $langcodes = $lang_parse[1];
1064 $qvalues = $lang_parse[4];
1065 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1067 // Set default q factor to 1
1068 foreach ( $indices as $index ) {
1069 if ( $qvalues[$index] === '' ) {
1070 $qvalues[$index] = 1;
1071 } elseif ( $qvalues[$index] == 0 ) {
1072 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1076 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1077 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1079 // Create a list like "en" => 0.8
1080 $langs = array_combine( $langcodes, $qvalues );
1086 * Fetch the raw IP from the request
1090 * @throws MWException
1093 protected function getRawIP() {
1094 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1098 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1099 throw new MWException( __METHOD__
1100 . " : Could not determine the remote IP address due to multiple values." );
1102 $ipchain = $_SERVER['REMOTE_ADDR'];
1105 return IP
::canonicalize( $ipchain );
1109 * Work out the IP address based on various globals
1110 * For trusted proxies, use the XFF client IP (first of the chain)
1114 * @throws MWException
1117 public function getIP() {
1118 global $wgUsePrivateIPs;
1120 # Return cached result
1121 if ( $this->ip
!== null ) {
1125 # collect the originating ips
1126 $ip = $this->getRawIP();
1128 throw new MWException( 'Unable to determine IP.' );
1132 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1133 if ( $forwardedFor !== false ) {
1134 $isConfigured = IP
::isConfiguredProxy( $ip );
1135 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1136 $ipchain = array_reverse( $ipchain );
1137 array_unshift( $ipchain, $ip );
1139 # Step through XFF list and find the last address in the list which is a
1140 # trusted server. Set $ip to the IP address given by that trusted server,
1141 # unless the address is not sensible (e.g. private). However, prefer private
1142 # IP addresses over proxy servers controlled by this site (more sensible).
1143 # Note that some XFF values might be "unknown" with Squid/Varnish.
1144 foreach ( $ipchain as $i => $curIP ) {
1145 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1146 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1147 ||
!IP
::isTrustedProxy( $curIP )
1149 break; // IP is not valid/trusted or does not point to anything
1152 IP
::isPublic( $ipchain[$i +
1] ) ||
1154 IP
::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1156 // Follow the next IP according to the proxy
1157 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1158 if ( !$nextIP && $isConfigured ) {
1159 // We have not yet made it past CDN/proxy servers of this site,
1160 // so either they are misconfigured or there is some IP spoofing.
1161 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1164 // keep traversing the chain
1171 # Allow extensions to improve our guess
1172 Hooks
::run( 'GetIP', [ &$ip ] );
1175 throw new MWException( "Unable to determine IP." );
1178 wfDebug( "IP: $ip\n" );
1188 public function setIP( $ip ) {