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
27 * The WebRequest class encapsulates getting at data passed in the
28 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
29 * stripping illegal input characters and normalizing Unicode sequences.
31 * Usually this is used via a global singleton, $wgRequest. You should
32 * not create a second WebRequest object; make a FauxRequest object if
33 * you want to pass arbitrary data to some function in place of the web
39 protected $data, $headers = array();
42 * Lazy-init response object
48 * Cached client IP address
59 public function __construct() {
60 /// @todo FIXME: This preemptive de-quoting can interfere with other web libraries
61 /// and increases our memory footprint. It would be cleaner to do on
62 /// demand; but currently we have no wrapper for $_SERVER etc.
63 $this->checkMagicQuotes();
65 // POST overrides GET data
66 // We don't use $_REQUEST here to avoid interference from cookies...
67 $this->data
= $_POST +
$_GET;
71 * Extract relevant query arguments from the http request uri's path
72 * to be merged with the normal php provided query arguments.
73 * Tries to use the REQUEST_URI data if available and parses it
74 * according to the wiki's configuration looking for any known pattern.
76 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
77 * provided by the server if any and use that to set a 'title' parameter.
79 * @param string $want If this is not 'all', then the function
80 * will return an empty array if it determines that the URL is
81 * inside a rewrite path.
83 * @return array Any query arguments found in path matches.
85 public static function getPathInfo( $want = 'all' ) {
86 global $wgUsePathInfo;
87 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
88 // And also by Apache 2.x, double slashes are converted to single slashes.
89 // So we will use REQUEST_URI if possible.
91 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
92 // Slurp out the path portion to examine...
93 $url = $_SERVER['REQUEST_URI'];
94 if ( !preg_match( '!^https?://!', $url ) ) {
95 $url = 'http://unused' . $url;
98 $a = parse_url( $url );
101 $path = isset( $a['path'] ) ?
$a['path'] : '';
104 if ( $path == $wgScript && $want !== 'all' ) {
105 // Script inside a rewrite path?
106 // Abort to keep from breaking...
110 $router = new PathRouter
;
112 // Raw PATH_INFO style
113 $router->add( "$wgScript/$1" );
115 if ( isset( $_SERVER['SCRIPT_NAME'] )
116 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
118 # Check for SCRIPT_NAME, we handle index.php explicitly
119 # But we do have some other .php files such as img_auth.php
120 # Don't let root article paths clober the parsing for them
121 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
124 global $wgArticlePath;
125 if ( $wgArticlePath ) {
126 $router->add( $wgArticlePath );
129 global $wgActionPaths;
130 if ( $wgActionPaths ) {
131 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
134 global $wgVariantArticlePath, $wgContLang;
135 if ( $wgVariantArticlePath ) {
136 $router->add( $wgVariantArticlePath,
137 array( 'variant' => '$2' ),
138 array( '$2' => $wgContLang->getVariants() )
142 wfRunHooks( 'WebRequestPathInfoRouter', array( $router ) );
144 $matches = $router->parse( $path );
146 } elseif ( $wgUsePathInfo ) {
147 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
149 // http://bugs.php.net/bug.php?id=31892
150 // Also reported when ini_get('cgi.fix_pathinfo')==false
151 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
153 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
154 // Regular old PATH_INFO yay
155 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
163 * Work out an appropriate URL prefix containing scheme and host, based on
164 * information detected from $_SERVER
168 public static function detectServer() {
169 $proto = self
::detectProtocol();
170 $stdPort = $proto === 'https' ?
443 : 80;
172 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
175 foreach ( $varNames as $varName ) {
176 if ( !isset( $_SERVER[$varName] ) ) {
179 $parts = IP
::splitHostAndPort( $_SERVER[$varName] );
181 // Invalid, do not use
185 if ( $parts[1] === false ) {
186 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
187 $port = $_SERVER['SERVER_PORT'];
188 } // else leave it as $stdPort
195 return $proto . '://' . IP
::combineHostAndPort( $host, $port, $stdPort );
199 * Detect the protocol from $_SERVER.
200 * This is for use prior to Setup.php, when no WebRequest object is available.
201 * At other times, use the non-static function getProtocol().
205 public static function detectProtocol() {
206 if ( ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ||
207 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
208 $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) ) {
216 * Get the current URL protocol (http or https)
219 public function getProtocol() {
220 if ( $this->protocol
=== null ) {
221 $this->protocol
= self
::detectProtocol();
223 return $this->protocol
;
227 * Check for title, action, and/or variant data in the URL
228 * and interpolate it into the GET variables.
229 * This should only be run after $wgContLang is available,
230 * as we may need the list of language variants to determine
231 * available variant URLs.
233 public function interpolateTitle() {
234 // bug 16019: title interpolation on API queries is useless and sometimes harmful
235 if ( defined( 'MW_API' ) ) {
239 $matches = self
::getPathInfo( 'title' );
240 foreach ( $matches as $key => $val ) {
241 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
246 * URL rewriting function; tries to extract page title and,
247 * optionally, one other fixed parameter value from a URL path.
249 * @param string $path The URL path given from the client
250 * @param array $bases One or more URLs, optionally with $1 at the end
251 * @param string $key If provided, the matching key in $bases will be
252 * passed on as the value of this URL parameter
253 * @return array Array of URL variables to interpolate; empty if no match
255 static function extractTitle( $path, $bases, $key = false ) {
256 foreach ( (array)$bases as $keyValue => $base ) {
257 // Find the part after $wgArticlePath
258 $base = str_replace( '$1', '', $base );
259 $baseLen = strlen( $base );
260 if ( substr( $path, 0, $baseLen ) == $base ) {
261 $raw = substr( $path, $baseLen );
263 $matches = array( 'title' => rawurldecode( $raw ) );
265 $matches[$key] = $keyValue;
275 * Recursively strips slashes from the given array;
276 * used for undoing the evil that is magic_quotes_gpc.
278 * @param array $arr will be modified
279 * @param bool $topLevel Specifies if the array passed is from the top
280 * level of the source. In PHP5 magic_quotes only escapes the first level
281 * of keys that belong to an array.
282 * @return array The original array
283 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
285 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
287 foreach ( $arr as $key => $val ) {
288 if ( is_array( $val ) ) {
289 $cleanKey = $topLevel ?
stripslashes( $key ) : $key;
290 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
292 $cleanKey = stripslashes( $key );
293 $clean[$cleanKey] = stripslashes( $val );
301 * If magic_quotes_gpc option is on, run the global arrays
302 * through fix_magic_quotes to strip out the stupid slashes.
303 * WARNING: This should only be done once! Running a second
304 * time could damage the values.
306 private function checkMagicQuotes() {
307 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
308 && get_magic_quotes_gpc();
309 if ( $mustFixQuotes ) {
310 $this->fix_magic_quotes( $_COOKIE );
311 $this->fix_magic_quotes( $_ENV );
312 $this->fix_magic_quotes( $_GET );
313 $this->fix_magic_quotes( $_POST );
314 $this->fix_magic_quotes( $_REQUEST );
315 $this->fix_magic_quotes( $_SERVER );
320 * Recursively normalizes UTF-8 strings in the given array.
322 * @param string|array $data
323 * @return array|string Cleaned-up version of the given
326 function normalizeUnicode( $data ) {
327 if ( is_array( $data ) ) {
328 foreach ( $data as $key => $val ) {
329 $data[$key] = $this->normalizeUnicode( $val );
333 $data = isset( $wgContLang ) ?
$wgContLang->normalize( $data ) : UtfNormal
::cleanUp( $data );
339 * Fetch a value from the given array or return $default if it's not set.
342 * @param string $name
343 * @param mixed $default
346 private function getGPCVal( $arr, $name, $default ) {
347 # PHP is so nice to not touch input data, except sometimes:
348 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
349 # Work around PHP *feature* to avoid *bugs* elsewhere.
350 $name = strtr( $name, '.', '_' );
351 if ( isset( $arr[$name] ) ) {
354 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
355 # Check for alternate/legacy character encoding.
356 if ( isset( $wgContLang ) ) {
357 $data = $wgContLang->checkTitleEncoding( $data );
360 $data = $this->normalizeUnicode( $data );
368 * Fetch a scalar from the input or return $default if it's not set.
369 * Returns a string. Arrays are discarded. Useful for
370 * non-freeform text inputs (e.g. predefined internal text keys
371 * selected by a drop-down menu). For freeform input, see getText().
373 * @param string $name
374 * @param string $default Optional default (or null)
377 public function getVal( $name, $default = null ) {
378 $val = $this->getGPCVal( $this->data
, $name, $default );
379 if ( is_array( $val ) ) {
382 if ( is_null( $val ) ) {
390 * Set an arbitrary value into our get/post data.
392 * @param string $key Key name to use
393 * @param mixed $value Value to set
394 * @return mixed Old value if one was present, null otherwise
396 public function setVal( $key, $value ) {
397 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
398 $this->data
[$key] = $value;
403 * Unset an arbitrary value from our get/post data.
405 * @param string $key Key name to use
406 * @return mixed Old value if one was present, null otherwise
408 public function unsetVal( $key ) {
409 if ( !isset( $this->data
[$key] ) ) {
412 $ret = $this->data
[$key];
413 unset( $this->data
[$key] );
419 * Fetch an array from the input or return $default if it's not set.
420 * If source was scalar, will return an array with a single element.
421 * If no source and no default, returns null.
423 * @param string $name
424 * @param array $default Optional default (or null)
427 public function getArray( $name, $default = null ) {
428 $val = $this->getGPCVal( $this->data
, $name, $default );
429 if ( is_null( $val ) ) {
437 * Fetch an array of integers, or return $default if it's not set.
438 * If source was scalar, will return an array with a single element.
439 * If no source and no default, returns null.
440 * If an array is returned, contents are guaranteed to be integers.
442 * @param string $name
443 * @param array $default Option default (or null)
444 * @return array Array of ints
446 public function getIntArray( $name, $default = null ) {
447 $val = $this->getArray( $name, $default );
448 if ( is_array( $val ) ) {
449 $val = array_map( 'intval', $val );
455 * Fetch an integer value from the input or return $default if not set.
456 * Guaranteed to return an integer; non-numeric input will typically
459 * @param string $name
460 * @param int $default
463 public function getInt( $name, $default = 0 ) {
464 return intval( $this->getVal( $name, $default ) );
468 * Fetch an integer value from the input or return null if empty.
469 * Guaranteed to return an integer or null; non-numeric input will
470 * typically return null.
472 * @param string $name
475 public function getIntOrNull( $name ) {
476 $val = $this->getVal( $name );
477 return is_numeric( $val )
483 * Fetch a floating point value from the input or return $default if not set.
484 * Guaranteed to return a float; non-numeric input will typically
488 * @param string $name
489 * @param float $default
492 public function getFloat( $name, $default = 0.0 ) {
493 return floatval( $this->getVal( $name, $default ) );
497 * Fetch a boolean value from the input or return $default if not set.
498 * Guaranteed to return true or false, with normal PHP semantics for
499 * boolean interpretation of strings.
501 * @param string $name
502 * @param bool $default
505 public function getBool( $name, $default = false ) {
506 return (bool)$this->getVal( $name, $default );
510 * Fetch a boolean value from the input or return $default if not set.
511 * Unlike getBool, the string "false" will result in boolean false, which is
512 * useful when interpreting information sent from JavaScript.
514 * @param string $name
515 * @param bool $default
518 public function getFuzzyBool( $name, $default = false ) {
519 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
523 * Return true if the named value is set in the input, whatever that
524 * value is (even "0"). Return false if the named value is not set.
525 * Example use is checking for the presence of check boxes in forms.
527 * @param string $name
530 public function getCheck( $name ) {
531 # Checkboxes and buttons are only present when clicked
532 # Presence connotes truth, absence false
533 return $this->getVal( $name, null ) !== null;
537 * Fetch a text string from the given array or return $default if it's not
538 * set. Carriage returns are stripped from the text, and with some language
539 * modules there is an input transliteration applied. This should generally
540 * be used for form "<textarea>" and "<input>" fields. Used for
541 * user-supplied freeform text input (for which input transformations may
542 * be required - e.g. Esperanto x-coding).
544 * @param string $name
545 * @param string $default Optional
548 public function getText( $name, $default = '' ) {
550 $val = $this->getVal( $name, $default );
551 return str_replace( "\r\n", "\n",
552 $wgContLang->recodeInput( $val ) );
556 * Extracts the given named values into an array.
557 * If no arguments are given, returns all input values.
558 * No transformation is performed on the values.
562 public function getValues() {
563 $names = func_get_args();
564 if ( count( $names ) == 0 ) {
565 $names = array_keys( $this->data
);
569 foreach ( $names as $name ) {
570 $value = $this->getGPCVal( $this->data
, $name, null );
571 if ( !is_null( $value ) ) {
572 $retVal[$name] = $value;
579 * Returns the names of all input values excluding those in $exclude.
581 * @param array $exclude
584 public function getValueNames( $exclude = array() ) {
585 return array_diff( array_keys( $this->getValues() ), $exclude );
589 * Get the values passed in the query string.
590 * No transformation is performed on the values.
594 public function getQueryValues() {
599 * Return the contents of the Query with no decoding. Use when you need to
600 * know exactly what was sent, e.g. for an OAuth signature over the elements.
604 public function getRawQueryString() {
605 return $_SERVER['QUERY_STRING'];
609 * Return the contents of the POST with no decoding. Use when you need to
610 * know exactly what was sent, e.g. for an OAuth signature over the elements.
614 public function getRawPostString() {
615 if ( !$this->wasPosted() ) {
618 return $this->getRawInput();
622 * Return the raw request body, with no processing. Cached since some methods
623 * disallow reading the stream more than once. As stated in the php docs, this
624 * does not work with enctype="multipart/form-data".
628 public function getRawInput() {
629 static $input = null;
630 if ( $input === null ) {
631 $input = file_get_contents( 'php://input' );
637 * Get the HTTP method used for this request.
641 public function getMethod() {
642 return isset( $_SERVER['REQUEST_METHOD'] ) ?
$_SERVER['REQUEST_METHOD'] : 'GET';
646 * Returns true if the present request was reached by a POST operation,
647 * false otherwise (GET, HEAD, or command-line).
649 * Note that values retrieved by the object may come from the
650 * GET URL etc even on a POST request.
654 public function wasPosted() {
655 return $this->getMethod() == 'POST';
659 * Returns true if there is a session cookie set.
660 * This does not necessarily mean that the user is logged in!
662 * If you want to check for an open session, use session_id()
663 * instead; that will also tell you if the session was opened
664 * during the current request (in which case the cookie will
665 * be sent back to the client at the end of the script run).
669 public function checkSessionCookie() {
670 return isset( $_COOKIE[session_name()] );
674 * Get a cookie from the $_COOKIE jar
676 * @param string $key The name of the cookie
677 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
678 * @param mixed $default What to return if the value isn't found
679 * @return mixed Cookie value or $default if the cookie not set
681 public function getCookie( $key, $prefix = null, $default = null ) {
682 if ( $prefix === null ) {
683 global $wgCookiePrefix;
684 $prefix = $wgCookiePrefix;
686 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
690 * Return the path and query string portion of the request URI.
691 * This will be suitable for use as a relative link in HTML output.
693 * @throws MWException
696 public function getRequestURL() {
697 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
698 $base = $_SERVER['REQUEST_URI'];
699 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
700 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
702 // Probably IIS; doesn't set REQUEST_URI
703 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
704 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
705 $base = $_SERVER['SCRIPT_NAME'];
706 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
707 $base .= '?' . $_SERVER['QUERY_STRING'];
710 // This shouldn't happen!
711 throw new MWException( "Web server doesn't provide either " .
712 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
713 "of your web server configuration to http://bugzilla.wikimedia.org/" );
715 // User-agents should not send a fragment with the URI, but
716 // if they do, and the web server passes it on to us, we
717 // need to strip it or we get false-positive redirect loops
718 // or weird output URLs
719 $hash = strpos( $base, '#' );
720 if ( $hash !== false ) {
721 $base = substr( $base, 0, $hash );
724 if ( $base[0] == '/' ) {
725 // More than one slash will look like it is protocol relative
726 return preg_replace( '!^/+!', '/', $base );
728 // We may get paths with a host prepended; strip it.
729 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
734 * Return the request URI with the canonical service and hostname, path,
735 * and query string. This will be suitable for use as an absolute link
736 * in HTML or other output.
738 * If $wgServer is protocol-relative, this will return a fully
739 * qualified URL with the protocol that was used for this request.
743 public function getFullRequestURL() {
744 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT
);
748 * Take an arbitrary query and rewrite the present URL to include it
749 * @param string $query query string fragment; do not include initial '?'
753 public function appendQuery( $query ) {
754 return $this->appendQueryArray( wfCgiToArray( $query ) );
758 * HTML-safe version of appendQuery().
759 * @deprecated: Deprecated in 1.20, warnings in 1.21, remove in 1.22.
761 * @param string $query Query string fragment; do not include initial '?'
764 public function escapeAppendQuery( $query ) {
765 return htmlspecialchars( $this->appendQuery( $query ) );
770 * @param string $value
771 * @param bool $onlyquery
774 public function appendQueryValue( $key, $value, $onlyquery = false ) {
775 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
779 * Appends or replaces value of query variables.
781 * @param array $array Array of values to replace/add to query
782 * @param bool $onlyquery Whether to only return the query string and not the complete URL
785 public function appendQueryArray( $array, $onlyquery = false ) {
787 $newquery = $this->getQueryValues();
788 unset( $newquery['title'] );
789 $newquery = array_merge( $newquery, $array );
790 $query = wfArrayToCgi( $newquery );
791 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
795 * Check for limit and offset parameters on the input, and return sensible
796 * defaults if not given. The limit must be positive and is capped at 5000.
797 * Offset must be positive but is not capped.
799 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
800 * @param string $optionname To specify an option other than rclimit to pull from.
801 * @return array First element is limit, second is offset
803 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
806 $limit = $this->getInt( 'limit', 0 );
810 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
811 $limit = $wgUser->getIntOption( $optionname );
816 if ( $limit > 5000 ) {
817 $limit = 5000; # We have *some* limits...
820 $offset = $this->getInt( 'offset', 0 );
825 return array( $limit, $offset );
829 * Return the path to the temporary file where PHP has stored the upload.
832 * @return string|null string or null if no such file.
834 public function getFileTempname( $key ) {
835 $file = new WebRequestUpload( $this, $key );
836 return $file->getTempName();
840 * Return the upload error or 0
845 public function getUploadError( $key ) {
846 $file = new WebRequestUpload( $this, $key );
847 return $file->getError();
851 * Return the original filename of the uploaded file, as reported by
852 * the submitting user agent. HTML-style character entities are
853 * interpreted and normalized to Unicode normalization form C, in part
854 * to deal with weird input from Safari with non-ASCII filenames.
856 * Other than this the name is not verified for being a safe filename.
859 * @return string|null string or null if no such file.
861 public function getFileName( $key ) {
862 $file = new WebRequestUpload( $this, $key );
863 return $file->getName();
867 * Return a WebRequestUpload object corresponding to the key
870 * @return WebRequestUpload
872 public function getUpload( $key ) {
873 return new WebRequestUpload( $this, $key );
877 * Return a handle to WebResponse style object, for setting cookies,
878 * headers and other stuff, for Request being worked on.
880 * @return WebResponse
882 public function response() {
883 /* Lazy initialization of response object for this request */
884 if ( !is_object( $this->response
) ) {
885 $class = ( $this instanceof FauxRequest
) ?
'FauxResponse' : 'WebResponse';
886 $this->response
= new $class();
888 return $this->response
;
892 * Initialise the header list
894 private function initHeaders() {
895 if ( count( $this->headers
) ) {
899 $apacheHeaders = function_exists( 'apache_request_headers' ) ?
apache_request_headers() : false;
900 if ( $apacheHeaders ) {
901 foreach ( $apacheHeaders as $tempName => $tempValue ) {
902 $this->headers
[strtoupper( $tempName )] = $tempValue;
905 foreach ( $_SERVER as $name => $value ) {
906 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
907 $name = str_replace( '_', '-', substr( $name, 5 ) );
908 $this->headers
[$name] = $value;
909 } elseif ( $name === 'CONTENT_LENGTH' ) {
910 $this->headers
['CONTENT-LENGTH'] = $value;
917 * Get an array containing all request headers
919 * @return array Mapping header name to its value
921 public function getAllHeaders() {
922 $this->initHeaders();
923 return $this->headers
;
927 * Get a request header, or false if it isn't set
928 * @param string $name case-insensitive header name
930 * @return string|bool False on failure
932 public function getHeader( $name ) {
933 $this->initHeaders();
934 $name = strtoupper( $name );
935 if ( isset( $this->headers
[$name] ) ) {
936 return $this->headers
[$name];
943 * Get data from $_SESSION
945 * @param string $key Name of key in $_SESSION
948 public function getSessionData( $key ) {
949 if ( !isset( $_SESSION[$key] ) ) {
952 return $_SESSION[$key];
958 * @param string $key Name of key in $_SESSION
961 public function setSessionData( $key, $data ) {
962 $_SESSION[$key] = $data;
966 * Check if Internet Explorer will detect an incorrect cache extension in
967 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
968 * message or redirect to a safer URL. Returns true if the URL is OK, and
969 * false if an error message has been shown and the request should be aborted.
971 * @param array $extWhitelist
975 public function checkUrlExtension( $extWhitelist = array() ) {
976 global $wgScriptExtension;
977 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
978 if ( IEUrlExtension
::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
979 if ( !$this->wasPosted() ) {
980 $newUrl = IEUrlExtension
::fixUrlForIE6(
981 $this->getFullRequestURL(), $extWhitelist );
982 if ( $newUrl !== false ) {
983 $this->doSecurityRedirect( $newUrl );
987 throw new HttpError( 403,
988 'Invalid file extension found in the path info or query string.' );
994 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
995 * IE 6. Returns true if it was successful, false otherwise.
1000 protected function doSecurityRedirect( $url ) {
1001 header( 'Location: ' . $url );
1002 header( 'Content-Type: text/html' );
1003 $encUrl = htmlspecialchars( $url );
1007 <title>Security redirect</title>
1010 <h1>Security redirect</h1>
1012 We can't serve non-HTML content from the URL you have requested
, because
1013 Internet Explorer would interpret it
as an incorrect
and potentially dangerous
1015 <p
>Instead
, please
use <a href
="$encUrl">this URL
</a
>, which is the same
as the
1016 URL you have requested
, except that
"&*" is appended
. This prevents Internet
1017 Explorer from seeing a bogus file extension
.
1027 * Parse the Accept-Language header sent by the client into an array
1029 * @return array array( languageCode => q-value ) sorted by q-value in
1030 * descending order then appearing time in the header in ascending order.
1031 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1032 * This is aligned with rfc2616 section 14.4
1033 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1035 public function getAcceptLang() {
1036 // Modified version of code found at
1037 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1038 $acceptLang = $this->getHeader( 'Accept-Language' );
1039 if ( !$acceptLang ) {
1043 // Return the language codes in lower case
1044 $acceptLang = strtolower( $acceptLang );
1046 // Break up string into pieces (languages and q factors)
1049 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1054 if ( !count( $lang_parse[1] ) ) {
1058 $langcodes = $lang_parse[1];
1059 $qvalues = $lang_parse[4];
1060 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1062 // Set default q factor to 1
1063 foreach ( $indices as $index ) {
1064 if ( $qvalues[$index] === '' ) {
1065 $qvalues[$index] = 1;
1066 } elseif ( $qvalues[$index] == 0 ) {
1067 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1071 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1072 array_multisort( $qvalues, SORT_DESC
, SORT_NUMERIC
, $indices, $langcodes );
1074 // Create a list like "en" => 0.8
1075 $langs = array_combine( $langcodes, $qvalues );
1081 * Fetch the raw IP from the request
1085 * @throws MWException
1088 protected function getRawIP() {
1089 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1093 if ( is_array( $_SERVER['REMOTE_ADDR'] ) ||
strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1094 throw new MWException( __METHOD__
1095 . " : Could not determine the remote IP address due to multiple values." );
1097 $ipchain = $_SERVER['REMOTE_ADDR'];
1100 return IP
::canonicalize( $ipchain );
1104 * Work out the IP address based on various globals
1105 * For trusted proxies, use the XFF client IP (first of the chain)
1109 * @throws MWException
1112 public function getIP() {
1113 global $wgUsePrivateIPs;
1115 # Return cached result
1116 if ( $this->ip
!== null ) {
1120 # collect the originating ips
1121 $ip = $this->getRawIP();
1123 throw new MWException( 'Unable to determine IP.' );
1127 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1128 if ( $forwardedFor !== false ) {
1129 $isConfigured = IP
::isConfiguredProxy( $ip );
1130 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1131 $ipchain = array_reverse( $ipchain );
1132 array_unshift( $ipchain, $ip );
1134 # Step through XFF list and find the last address in the list which is a
1135 # trusted server. Set $ip to the IP address given by that trusted server,
1136 # unless the address is not sensible (e.g. private). However, prefer private
1137 # IP addresses over proxy servers controlled by this site (more sensible).
1138 # Note that some XFF values might be "unknown" with Squid/Varnish.
1139 foreach ( $ipchain as $i => $curIP ) {
1140 $curIP = IP
::sanitizeIP( IP
::canonicalize( $curIP ) );
1141 if ( !$curIP ||
!isset( $ipchain[$i +
1] ) ||
$ipchain[$i +
1] === 'unknown'
1142 ||
!IP
::isTrustedProxy( $curIP )
1144 break; // IP is not valid/trusted or does not point to anything
1147 IP
::isPublic( $ipchain[$i +
1] ) ||
1149 IP
::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1151 // Follow the next IP according to the proxy
1152 $nextIP = IP
::canonicalize( $ipchain[$i +
1] );
1153 if ( !$nextIP && $isConfigured ) {
1154 // We have not yet made it past CDN/proxy servers of this site,
1155 // so either they are misconfigured or there is some IP spoofing.
1156 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1159 // keep traversing the chain
1166 # Allow extensions to improve our guess
1167 wfRunHooks( 'GetIP', array( &$ip ) );
1170 throw new MWException( "Unable to determine IP." );
1173 wfDebug( "IP: $ip\n" );
1183 public function setIP( $ip ) {
1189 * Object to access the $_FILES array
1191 class WebRequestUpload
{
1193 protected $doesExist;
1194 protected $fileInfo;
1197 * Constructor. Should only be called by WebRequest
1199 * @param WebRequest $request The associated request
1200 * @param string $key Key in $_FILES array (name of form field)
1202 public function __construct( $request, $key ) {
1203 $this->request
= $request;
1204 $this->doesExist
= isset( $_FILES[$key] );
1205 if ( $this->doesExist
) {
1206 $this->fileInfo
= $_FILES[$key];
1211 * Return whether a file with this name was uploaded.
1215 public function exists() {
1216 return $this->doesExist
;
1220 * Return the original filename of the uploaded file
1222 * @return string|null Filename or null if non-existent
1224 public function getName() {
1225 if ( !$this->exists() ) {
1230 $name = $this->fileInfo
['name'];
1232 # Safari sends filenames in HTML-encoded Unicode form D...
1233 # Horrid and evil! Let's try to make some kind of sense of it.
1234 $name = Sanitizer
::decodeCharReferences( $name );
1235 $name = $wgContLang->normalize( $name );
1236 wfDebug( __METHOD__
. ": {$this->fileInfo['name']} normalized to '$name'\n" );
1241 * Return the file size of the uploaded file
1243 * @return int File size or zero if non-existent
1245 public function getSize() {
1246 if ( !$this->exists() ) {
1250 return $this->fileInfo
['size'];
1254 * Return the path to the temporary file
1256 * @return string|null Path or null if non-existent
1258 public function getTempName() {
1259 if ( !$this->exists() ) {
1263 return $this->fileInfo
['tmp_name'];
1267 * Return the upload error. See link for explanation
1268 * http://www.php.net/manual/en/features.file-upload.errors.php
1270 * @return int One of the UPLOAD_ constants, 0 if non-existent
1272 public function getError() {
1273 if ( !$this->exists() ) {
1274 return 0; # UPLOAD_ERR_OK
1277 return $this->fileInfo
['error'];
1281 * Returns whether this upload failed because of overflow of a maximum set
1286 public function isIniSizeOverflow() {
1287 if ( $this->getError() == UPLOAD_ERR_INI_SIZE
) {
1288 # PHP indicated that upload_max_filesize is exceeded
1292 $contentLength = $this->request
->getHeader( 'CONTENT_LENGTH' );
1293 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1294 # post_max_size is exceeded
1303 * WebRequest clone which takes values from a provided array.
1307 class FauxRequest
extends WebRequest
{
1308 private $wasPosted = false;
1309 private $session = array();
1312 * @param array $data of *non*-urlencoded key => value pairs, the
1313 * fake GET/POST values
1314 * @param bool $wasPosted Whether to treat the data as POST
1315 * @param array|null $session Session array or null
1316 * @param string $protocol 'http' or 'https'
1317 * @throws MWException
1319 public function __construct( $data = array(), $wasPosted = false,
1320 $session = null, $protocol = 'http'
1322 if ( is_array( $data ) ) {
1323 $this->data
= $data;
1325 throw new MWException( "FauxRequest() got bogus data" );
1327 $this->wasPosted
= $wasPosted;
1329 $this->session
= $session;
1331 $this->protocol
= $protocol;
1335 * @param string $method
1336 * @throws MWException
1338 private function notImplemented( $method ) {
1339 throw new MWException( "{$method}() not implemented" );
1343 * @param string $name
1344 * @param string $default
1347 public function getText( $name, $default = '' ) {
1348 # Override; don't recode since we're using internal data
1349 return (string)$this->getVal( $name, $default );
1355 public function getValues() {
1362 public function getQueryValues() {
1363 if ( $this->wasPosted
) {
1370 public function getMethod() {
1371 return $this->wasPosted ?
'POST' : 'GET';
1377 public function wasPosted() {
1378 return $this->wasPosted
;
1381 public function getCookie( $key, $prefix = null, $default = null ) {
1385 public function checkSessionCookie() {
1389 public function getRequestURL() {
1390 $this->notImplemented( __METHOD__
);
1393 public function getProtocol() {
1394 return $this->protocol
;
1398 * @param string $name The name of the header to get (case insensitive).
1399 * @return bool|string
1401 public function getHeader( $name ) {
1402 $name = strtoupper( $name );
1403 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
1407 * @param string $name
1408 * @param string $val
1410 public function setHeader( $name, $val ) {
1411 $name = strtoupper( $name );
1412 $this->headers
[$name] = $val;
1416 * @param string $key
1417 * @return array|null
1419 public function getSessionData( $key ) {
1420 if ( isset( $this->session
[$key] ) ) {
1421 return $this->session
[$key];
1427 * @param string $key
1428 * @param array $data
1430 public function setSessionData( $key, $data ) {
1431 $this->session
[$key] = $data;
1435 * @return array|mixed|null
1437 public function getSessionArray() {
1438 return $this->session
;
1442 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1445 public function getRawQueryString() {
1450 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1453 public function getRawPostString() {
1458 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1461 public function getRawInput() {
1466 * @param array $extWhitelist
1469 public function checkUrlExtension( $extWhitelist = array() ) {
1476 protected function getRawIP() {
1482 * Similar to FauxRequest, but only fakes URL parameters and method
1483 * (POST or GET) and use the base request for the remaining stuff
1484 * (cookies, session and headers).
1489 class DerivativeRequest
extends FauxRequest
{
1493 * @param WebRequest $base
1494 * @param array $data Array of *non*-urlencoded key => value pairs, the
1495 * fake GET/POST values
1496 * @param bool $wasPosted Whether to treat the data as POST
1498 public function __construct( WebRequest
$base, $data, $wasPosted = false ) {
1499 $this->base
= $base;
1500 parent
::__construct( $data, $wasPosted );
1503 public function getCookie( $key, $prefix = null, $default = null ) {
1504 return $this->base
->getCookie( $key, $prefix, $default );
1507 public function checkSessionCookie() {
1508 return $this->base
->checkSessionCookie();
1511 public function getHeader( $name ) {
1512 return $this->base
->getHeader( $name );
1515 public function getAllHeaders() {
1516 return $this->base
->getAllHeaders();
1519 public function getSessionData( $key ) {
1520 return $this->base
->getSessionData( $key );
1523 public function setSessionData( $key, $data ) {
1524 $this->base
->setSessionData( $key, $data );
1527 public function getAcceptLang() {
1528 return $this->base
->getAcceptLang();
1531 public function getIP() {
1532 return $this->base
->getIP();
1535 public function getProtocol() {
1536 return $this->base
->getProtocol();