Merge "move page_restrictions.pr_id to top in tables.sql"
[mediawiki.git] / includes / WebRequest.php
blob536ce12acf03eeedeef16511efedb495c76abbfc
1 <?php
2 /**
3 * Deal with importing all those nasty globals and things
5 * Copyright © 2003 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
26 /**
27 * The WebRequest class encapsulates getting at data passed in the
28 * URL or via a POSTed form, 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
34 * input.
36 * @ingroup HTTP
38 class WebRequest {
39 protected $data, $headers = array();
41 /**
42 * Lazy-init response object
43 * @var WebResponse
45 private $response;
47 /**
48 * Cached client IP address
49 * @var String
51 private $ip;
53 /**
54 * Cached URL protocol
55 * @var string
57 private $protocol;
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;
70 /**
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.
90 $matches = array();
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;
97 wfSuppressWarnings();
98 $a = parse_url( $url );
99 wfRestoreWarnings();
100 if ( $a ) {
101 $path = isset( $a['path'] ) ? $a['path'] : '';
103 global $wgScript;
104 if ( $path == $wgScript && $want !== 'all' ) {
105 // Script inside a rewrite path?
106 // Abort to keep from breaking...
107 return $matches;
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'] != '' ) {
148 // Mangled 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 );
159 return $matches;
163 * Work out an appropriate URL prefix containing scheme and host, based on
164 * information detected from $_SERVER
166 * @return string
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' );
173 $host = 'localhost';
174 $port = $stdPort;
175 foreach ( $varNames as $varName ) {
176 if ( !isset( $_SERVER[$varName] ) ) {
177 continue;
179 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
180 if ( !$parts ) {
181 // Invalid, do not use
182 continue;
184 $host = $parts[0];
185 if ( $parts[1] === false ) {
186 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
187 $port = $_SERVER['SERVER_PORT'];
188 } // else leave it as $stdPort
189 } else {
190 $port = $parts[1];
192 break;
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().
203 * @return array
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' ) ) {
209 return 'https';
210 } else {
211 return 'http';
213 return $arr;
217 * Get the current URL protocol (http or https)
218 * @return string
220 public function getProtocol() {
221 if ( $this->protocol === null ) {
222 $this->protocol = self::detectProtocol();
224 return $this->protocol;
228 * Check for title, action, and/or variant data in the URL
229 * and interpolate it into the GET variables.
230 * This should only be run after $wgContLang is available,
231 * as we may need the list of language variants to determine
232 * available variant URLs.
234 public function interpolateTitle() {
235 // bug 16019: title interpolation on API queries is useless and sometimes harmful
236 if ( defined( 'MW_API' ) ) {
237 return;
240 $matches = self::getPathInfo( 'title' );
241 foreach ( $matches as $key => $val ) {
242 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
247 * URL rewriting function; tries to extract page title and,
248 * optionally, one other fixed parameter value from a URL path.
250 * @param string $path the URL path given from the client
251 * @param array $bases one or more URLs, optionally with $1 at the end
252 * @param string $key if provided, the matching key in $bases will be
253 * passed on as the value of this URL parameter
254 * @return array of URL variables to interpolate; empty if no match
256 static function extractTitle( $path, $bases, $key = false ) {
257 foreach ( (array)$bases as $keyValue => $base ) {
258 // Find the part after $wgArticlePath
259 $base = str_replace( '$1', '', $base );
260 $baseLen = strlen( $base );
261 if ( substr( $path, 0, $baseLen ) == $base ) {
262 $raw = substr( $path, $baseLen );
263 if ( $raw !== '' ) {
264 $matches = array( 'title' => rawurldecode( $raw ) );
265 if ( $key ) {
266 $matches[$key] = $keyValue;
268 return $matches;
272 return array();
276 * Recursively strips slashes from the given array;
277 * used for undoing the evil that is magic_quotes_gpc.
279 * @param array $arr will be modified
280 * @param bool $topLevel Specifies if the array passed is from the top
281 * level of the source. In PHP5 magic_quotes only escapes the first level
282 * of keys that belong to an array.
283 * @return array the original array
284 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
286 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
287 $clean = array();
288 foreach ( $arr as $key => $val ) {
289 if ( is_array( $val ) ) {
290 $cleanKey = $topLevel ? stripslashes( $key ) : $key;
291 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
292 } else {
293 $cleanKey = stripslashes( $key );
294 $clean[$cleanKey] = stripslashes( $val );
297 $arr = $clean;
298 return $arr;
302 * If magic_quotes_gpc option is on, run the global arrays
303 * through fix_magic_quotes to strip out the stupid slashes.
304 * WARNING: This should only be done once! Running a second
305 * time could damage the values.
307 private function checkMagicQuotes() {
308 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
309 && get_magic_quotes_gpc();
310 if ( $mustFixQuotes ) {
311 $this->fix_magic_quotes( $_COOKIE );
312 $this->fix_magic_quotes( $_ENV );
313 $this->fix_magic_quotes( $_GET );
314 $this->fix_magic_quotes( $_POST );
315 $this->fix_magic_quotes( $_REQUEST );
316 $this->fix_magic_quotes( $_SERVER );
321 * Recursively normalizes UTF-8 strings in the given array.
323 * @param $data string|array
324 * @return array|string cleaned-up version of the given
325 * @private
327 function normalizeUnicode( $data ) {
328 if ( is_array( $data ) ) {
329 foreach ( $data as $key => $val ) {
330 $data[$key] = $this->normalizeUnicode( $val );
332 } else {
333 global $wgContLang;
334 $data = isset( $wgContLang ) ? $wgContLang->normalize( $data ) : UtfNormal::cleanUp( $data );
336 return $data;
340 * Fetch a value from the given array or return $default if it's not set.
342 * @param $arr Array
343 * @param $name String
344 * @param $default Mixed
345 * @return mixed
347 private function getGPCVal( $arr, $name, $default ) {
348 # PHP is so nice to not touch input data, except sometimes:
349 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
350 # Work around PHP *feature* to avoid *bugs* elsewhere.
351 $name = strtr( $name, '.', '_' );
352 if ( isset( $arr[$name] ) ) {
353 global $wgContLang;
354 $data = $arr[$name];
355 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
356 # Check for alternate/legacy character encoding.
357 if ( isset( $wgContLang ) ) {
358 $data = $wgContLang->checkTitleEncoding( $data );
361 $data = $this->normalizeUnicode( $data );
362 return $data;
363 } else {
364 return $default;
369 * Fetch a scalar from the input or return $default if it's not set.
370 * Returns a string. Arrays are discarded. Useful for
371 * non-freeform text inputs (e.g. predefined internal text keys
372 * selected by a drop-down menu). For freeform input, see getText().
374 * @param $name String
375 * @param string $default optional default (or NULL)
376 * @return String
378 public function getVal( $name, $default = null ) {
379 $val = $this->getGPCVal( $this->data, $name, $default );
380 if ( is_array( $val ) ) {
381 $val = $default;
383 if ( is_null( $val ) ) {
384 return $val;
385 } else {
386 return (string)$val;
391 * Set an arbitrary value into our get/post data.
393 * @param string $key key name to use
394 * @param $value Mixed: value to set
395 * @return Mixed: old value if one was present, null otherwise
397 public function setVal( $key, $value ) {
398 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
399 $this->data[$key] = $value;
400 return $ret;
404 * Unset an arbitrary value from our get/post data.
406 * @param string $key key name to use
407 * @return Mixed: old value if one was present, null otherwise
409 public function unsetVal( $key ) {
410 if ( !isset( $this->data[$key] ) ) {
411 $ret = null;
412 } else {
413 $ret = $this->data[$key];
414 unset( $this->data[$key] );
416 return $ret;
420 * Fetch an array from the input or return $default if it's not set.
421 * If source was scalar, will return an array with a single element.
422 * If no source and no default, returns NULL.
424 * @param $name String
425 * @param array $default optional default (or NULL)
426 * @return Array
428 public function getArray( $name, $default = null ) {
429 $val = $this->getGPCVal( $this->data, $name, $default );
430 if ( is_null( $val ) ) {
431 return null;
432 } else {
433 return (array)$val;
438 * Fetch an array of integers, or return $default if it's not set.
439 * If source was scalar, will return an array with a single element.
440 * If no source and no default, returns NULL.
441 * If an array is returned, contents are guaranteed to be integers.
443 * @param $name String
444 * @param array $default option default (or NULL)
445 * @return Array of ints
447 public function getIntArray( $name, $default = null ) {
448 $val = $this->getArray( $name, $default );
449 if ( is_array( $val ) ) {
450 $val = array_map( 'intval', $val );
452 return $val;
456 * Fetch an integer value from the input or return $default if not set.
457 * Guaranteed to return an integer; non-numeric input will typically
458 * return 0.
460 * @param $name String
461 * @param $default Integer
462 * @return Integer
464 public function getInt( $name, $default = 0 ) {
465 return intval( $this->getVal( $name, $default ) );
469 * Fetch an integer value from the input or return null if empty.
470 * Guaranteed to return an integer or null; non-numeric input will
471 * typically return null.
473 * @param $name String
474 * @return Integer
476 public function getIntOrNull( $name ) {
477 $val = $this->getVal( $name );
478 return is_numeric( $val )
479 ? intval( $val )
480 : null;
484 * Fetch a floating point value from the input or return $default if not set.
485 * Guaranteed to return a float; non-numeric input will typically
486 * return 0.
488 * @since 1.23
489 * @param $name String
490 * @param $default Float
491 * @return Float
493 public function getFloat( $name, $default = 0 ) {
494 return floatval( $this->getVal( $name, $default ) );
498 * Fetch a boolean value from the input or return $default if not set.
499 * Guaranteed to return true or false, with normal PHP semantics for
500 * boolean interpretation of strings.
502 * @param $name String
503 * @param $default Boolean
504 * @return Boolean
506 public function getBool( $name, $default = false ) {
507 return (bool)$this->getVal( $name, $default );
511 * Fetch a boolean value from the input or return $default if not set.
512 * Unlike getBool, the string "false" will result in boolean false, which is
513 * useful when interpreting information sent from JavaScript.
515 * @param $name String
516 * @param $default Boolean
517 * @return Boolean
519 public function getFuzzyBool( $name, $default = false ) {
520 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
524 * Return true if the named value is set in the input, whatever that
525 * value is (even "0"). Return false if the named value is not set.
526 * Example use is checking for the presence of check boxes in forms.
528 * @param $name String
529 * @return Boolean
531 public function getCheck( $name ) {
532 # Checkboxes and buttons are only present when clicked
533 # Presence connotes truth, absence false
534 return $this->getVal( $name, null ) !== null;
538 * Fetch a text string from the given array or return $default if it's not
539 * set. Carriage returns are stripped from the text, and with some language
540 * modules there is an input transliteration applied. This should generally
541 * be used for form "<textarea>" and "<input>" fields. Used for
542 * user-supplied freeform text input (for which input transformations may
543 * be required - e.g. Esperanto x-coding).
545 * @param $name String
546 * @param string $default optional
547 * @return String
549 public function getText( $name, $default = '' ) {
550 global $wgContLang;
551 $val = $this->getVal( $name, $default );
552 return str_replace( "\r\n", "\n",
553 $wgContLang->recodeInput( $val ) );
557 * Extracts the given named values into an array.
558 * If no arguments are given, returns all input values.
559 * No transformation is performed on the values.
561 * @return array
563 public function getValues() {
564 $names = func_get_args();
565 if ( count( $names ) == 0 ) {
566 $names = array_keys( $this->data );
569 $retVal = array();
570 foreach ( $names as $name ) {
571 $value = $this->getGPCVal( $this->data, $name, null );
572 if ( !is_null( $value ) ) {
573 $retVal[$name] = $value;
576 return $retVal;
580 * Returns the names of all input values excluding those in $exclude.
582 * @param $exclude Array
583 * @return array
585 public function getValueNames( $exclude = array() ) {
586 return array_diff( array_keys( $this->getValues() ), $exclude );
590 * Get the values passed in the query string.
591 * No transformation is performed on the values.
593 * @return Array
595 public function getQueryValues() {
596 return $_GET;
600 * Return the contents of the Query with no decoding. Use when you need to
601 * know exactly what was sent, e.g. for an OAuth signature over the elements.
603 * @return String
605 public function getRawQueryString() {
606 return $_SERVER['QUERY_STRING'];
610 * Return the contents of the POST with no decoding. Use when you need to
611 * know exactly what was sent, e.g. for an OAuth signature over the elements.
613 * @return String
615 public function getRawPostString() {
616 if ( !$this->wasPosted() ) {
617 return '';
619 return $this->getRawInput();
623 * Return the raw request body, with no processing. Cached since some methods
624 * disallow reading the stream more than once. As stated in the php docs, this
625 * does not work with enctype="multipart/form-data".
627 * @return String
629 public function getRawInput() {
630 static $input = false;
631 if ( $input === false ) {
632 $input = file_get_contents( 'php://input' );
634 return $input;
638 * Get the HTTP method used for this request.
640 * @return String
642 public function getMethod() {
643 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
647 * Returns true if the present request was reached by a POST operation,
648 * false otherwise (GET, HEAD, or command-line).
650 * Note that values retrieved by the object may come from the
651 * GET URL etc even on a POST request.
653 * @return Boolean
655 public function wasPosted() {
656 return $this->getMethod() == 'POST';
660 * Returns true if there is a session cookie set.
661 * This does not necessarily mean that the user is logged in!
663 * If you want to check for an open session, use session_id()
664 * instead; that will also tell you if the session was opened
665 * during the current request (in which case the cookie will
666 * be sent back to the client at the end of the script run).
668 * @return Boolean
670 public function checkSessionCookie() {
671 return isset( $_COOKIE[session_name()] );
675 * Get a cookie from the $_COOKIE jar
677 * @param string $key the name of the cookie
678 * @param string $prefix a prefix to use for the cookie name, if not $wgCookiePrefix
679 * @param $default Mixed: what to return if the value isn't found
680 * @return Mixed: cookie value or $default if the cookie not set
682 public function getCookie( $key, $prefix = null, $default = null ) {
683 if ( $prefix === null ) {
684 global $wgCookiePrefix;
685 $prefix = $wgCookiePrefix;
687 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
691 * Return the path and query string portion of the request URI.
692 * This will be suitable for use as a relative link in HTML output.
694 * @throws MWException
695 * @return String
697 public function getRequestURL() {
698 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
699 $base = $_SERVER['REQUEST_URI'];
700 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
701 // Probably IIS; doesn't set REQUEST_URI
702 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
703 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
704 $base = $_SERVER['SCRIPT_NAME'];
705 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
706 $base .= '?' . $_SERVER['QUERY_STRING'];
708 } else {
709 // This shouldn't happen!
710 throw new MWException( "Web server doesn't provide either " .
711 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
712 "of your web server configuration to http://bugzilla.wikimedia.org/" );
714 // User-agents should not send a fragment with the URI, but
715 // if they do, and the web server passes it on to us, we
716 // need to strip it or we get false-positive redirect loops
717 // or weird output URLs
718 $hash = strpos( $base, '#' );
719 if ( $hash !== false ) {
720 $base = substr( $base, 0, $hash );
723 if ( $base[0] == '/' ) {
724 // More than one slash will look like it is protocol relative
725 return preg_replace( '!^/+!', '/', $base );
726 } else {
727 // We may get paths with a host prepended; strip it.
728 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
733 * Return the request URI with the canonical service and hostname, path,
734 * and query string. This will be suitable for use as an absolute link
735 * in HTML or other output.
737 * If $wgServer is protocol-relative, this will return a fully
738 * qualified URL with the protocol that was used for this request.
740 * @return String
742 public function getFullRequestURL() {
743 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
747 * Take an arbitrary query and rewrite the present URL to include it
748 * @param string $query query string fragment; do not include initial '?'
750 * @return String
752 public function appendQuery( $query ) {
753 return $this->appendQueryArray( wfCgiToArray( $query ) );
757 * HTML-safe version of appendQuery().
758 * @deprecated: Deprecated in 1.20, warnings in 1.21, remove in 1.22.
760 * @param string $query query string fragment; do not include initial '?'
761 * @return String
763 public function escapeAppendQuery( $query ) {
764 return htmlspecialchars( $this->appendQuery( $query ) );
768 * @param $key
769 * @param $value
770 * @param $onlyquery bool
771 * @return String
773 public function appendQueryValue( $key, $value, $onlyquery = false ) {
774 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
778 * Appends or replaces value of query variables.
780 * @param array $array of values to replace/add to query
781 * @param bool $onlyquery whether to only return the query string and not
782 * the complete URL
783 * @return String
785 public function appendQueryArray( $array, $onlyquery = false ) {
786 global $wgTitle;
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 $deflimit Integer: 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' ) {
804 global $wgUser;
806 $limit = $this->getInt( 'limit', 0 );
807 if ( $limit < 0 ) {
808 $limit = 0;
810 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
811 $limit = $wgUser->getIntOption( $optionname );
813 if ( $limit <= 0 ) {
814 $limit = $deflimit;
816 if ( $limit > 5000 ) {
817 $limit = 5000; # We have *some* limits...
820 $offset = $this->getInt( 'offset', 0 );
821 if ( $offset < 0 ) {
822 $offset = 0;
825 return array( $limit, $offset );
829 * Return the path to the temporary file where PHP has stored the upload.
831 * @param $key String:
832 * @return 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 size of the upload, or 0.
842 * @deprecated since 1.17
843 * @param $key String:
844 * @return integer
846 public function getFileSize( $key ) {
847 wfDeprecated( __METHOD__, '1.17' );
848 $file = new WebRequestUpload( $this, $key );
849 return $file->getSize();
853 * Return the upload error or 0
855 * @param $key String:
856 * @return integer
858 public function getUploadError( $key ) {
859 $file = new WebRequestUpload( $this, $key );
860 return $file->getError();
864 * Return the original filename of the uploaded file, as reported by
865 * the submitting user agent. HTML-style character entities are
866 * interpreted and normalized to Unicode normalization form C, in part
867 * to deal with weird input from Safari with non-ASCII filenames.
869 * Other than this the name is not verified for being a safe filename.
871 * @param $key String:
872 * @return string or NULL if no such file.
874 public function getFileName( $key ) {
875 $file = new WebRequestUpload( $this, $key );
876 return $file->getName();
880 * Return a WebRequestUpload object corresponding to the key
882 * @param $key string
883 * @return WebRequestUpload
885 public function getUpload( $key ) {
886 return new WebRequestUpload( $this, $key );
890 * Return a handle to WebResponse style object, for setting cookies,
891 * headers and other stuff, for Request being worked on.
893 * @return WebResponse
895 public function response() {
896 /* Lazy initialization of response object for this request */
897 if ( !is_object( $this->response ) ) {
898 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
899 $this->response = new $class();
901 return $this->response;
905 * Initialise the header list
907 private function initHeaders() {
908 if ( count( $this->headers ) ) {
909 return;
912 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
913 if ( $apacheHeaders ) {
914 foreach ( $apacheHeaders as $tempName => $tempValue ) {
915 $this->headers[strtoupper( $tempName )] = $tempValue;
917 } else {
918 foreach ( $_SERVER as $name => $value ) {
919 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
920 $name = str_replace( '_', '-', substr( $name, 5 ) );
921 $this->headers[$name] = $value;
922 } elseif ( $name === 'CONTENT_LENGTH' ) {
923 $this->headers['CONTENT-LENGTH'] = $value;
930 * Get an array containing all request headers
932 * @return Array mapping header name to its value
934 public function getAllHeaders() {
935 $this->initHeaders();
936 return $this->headers;
940 * Get a request header, or false if it isn't set
941 * @param string $name case-insensitive header name
943 * @return string|bool False on failure
945 public function getHeader( $name ) {
946 $this->initHeaders();
947 $name = strtoupper( $name );
948 if ( isset( $this->headers[$name] ) ) {
949 return $this->headers[$name];
950 } else {
951 return false;
956 * Get data from $_SESSION
958 * @param string $key name of key in $_SESSION
959 * @return Mixed
961 public function getSessionData( $key ) {
962 if ( !isset( $_SESSION[$key] ) ) {
963 return null;
965 return $_SESSION[$key];
969 * Set session data
971 * @param string $key name of key in $_SESSION
972 * @param $data Mixed
974 public function setSessionData( $key, $data ) {
975 $_SESSION[$key] = $data;
979 * Check if Internet Explorer will detect an incorrect cache extension in
980 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
981 * message or redirect to a safer URL. Returns true if the URL is OK, and
982 * false if an error message has been shown and the request should be aborted.
984 * @param $extWhitelist array
985 * @throws HttpError
986 * @return bool
988 public function checkUrlExtension( $extWhitelist = array() ) {
989 global $wgScriptExtension;
990 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
991 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
992 if ( !$this->wasPosted() ) {
993 $newUrl = IEUrlExtension::fixUrlForIE6(
994 $this->getFullRequestURL(), $extWhitelist );
995 if ( $newUrl !== false ) {
996 $this->doSecurityRedirect( $newUrl );
997 return false;
1000 throw new HttpError( 403,
1001 'Invalid file extension found in the path info or query string.' );
1003 return true;
1007 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1008 * IE 6. Returns true if it was successful, false otherwise.
1010 * @param $url string
1011 * @return bool
1013 protected function doSecurityRedirect( $url ) {
1014 header( 'Location: ' . $url );
1015 header( 'Content-Type: text/html' );
1016 $encUrl = htmlspecialchars( $url );
1017 echo <<<HTML
1018 <html>
1019 <head>
1020 <title>Security redirect</title>
1021 </head>
1022 <body>
1023 <h1>Security redirect</h1>
1025 We can't serve non-HTML content from the URL you have requested, because
1026 Internet Explorer would interpret it as an incorrect and potentially dangerous
1027 content type.</p>
1028 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the URL you have requested, except that
1029 "&amp;*" is appended. This prevents Internet Explorer from seeing a bogus file
1030 extension.
1031 </p>
1032 </body>
1033 </html>
1034 HTML;
1035 echo "\n";
1036 return true;
1040 * Returns true if the PATH_INFO ends with an extension other than a script
1041 * extension. This could confuse IE for scripts that send arbitrary data which
1042 * is not HTML but may be detected as such.
1044 * Various past attempts to use the URL to make this check have generally
1045 * run up against the fact that CGI does not provide a standard method to
1046 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
1047 * but only by prefixing it with the script name and maybe some other stuff,
1048 * the extension is not mangled. So this should be a reasonably portable
1049 * way to perform this security check.
1051 * Also checks for anything that looks like a file extension at the end of
1052 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
1053 * if there was no dot before the question mark (bug 28235).
1055 * @deprecated Use checkUrlExtension().
1057 * @param $extWhitelist array
1059 * @return bool
1061 public function isPathInfoBad( $extWhitelist = array() ) {
1062 wfDeprecated( __METHOD__, '1.17' );
1063 global $wgScriptExtension;
1064 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
1065 return IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist );
1069 * Parse the Accept-Language header sent by the client into an array
1070 * @return array array( languageCode => q-value ) sorted by q-value in descending order then
1071 * appearing time in the header in ascending order.
1072 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1073 * This is aligned with rfc2616 section 14.4
1074 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1076 public function getAcceptLang() {
1077 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
1078 $acceptLang = $this->getHeader( 'Accept-Language' );
1079 if ( !$acceptLang ) {
1080 return array();
1083 // Return the language codes in lower case
1084 $acceptLang = strtolower( $acceptLang );
1086 // Break up string into pieces (languages and q factors)
1087 $lang_parse = null;
1088 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1089 $acceptLang, $lang_parse );
1091 if ( !count( $lang_parse[1] ) ) {
1092 return array();
1095 $langcodes = $lang_parse[1];
1096 $qvalues = $lang_parse[4];
1097 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1099 // Set default q factor to 1
1100 foreach ( $indices as $index ) {
1101 if ( $qvalues[$index] === '' ) {
1102 $qvalues[$index] = 1;
1103 } elseif ( $qvalues[$index] == 0 ) {
1104 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1108 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1109 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1111 // Create a list like "en" => 0.8
1112 $langs = array_combine( $langcodes, $qvalues );
1114 return $langs;
1118 * Fetch the raw IP from the request
1120 * @since 1.19
1122 * @throws MWException
1123 * @return String
1125 protected function getRawIP() {
1126 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1127 return null;
1130 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1131 throw new MWException( __METHOD__ . " : Could not determine the remote IP address due to multiple values." );
1132 } else {
1133 $ipchain = $_SERVER['REMOTE_ADDR'];
1136 return IP::canonicalize( $ipchain );
1140 * Work out the IP address based on various globals
1141 * For trusted proxies, use the XFF client IP (first of the chain)
1143 * @since 1.19
1145 * @throws MWException
1146 * @return string
1148 public function getIP() {
1149 global $wgUsePrivateIPs;
1151 # Return cached result
1152 if ( $this->ip !== null ) {
1153 return $this->ip;
1156 # collect the originating ips
1157 $ip = $this->getRawIP();
1159 # Append XFF
1160 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1161 if ( $forwardedFor !== false ) {
1162 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1163 $ipchain = array_reverse( $ipchain );
1164 if ( $ip ) {
1165 array_unshift( $ipchain, $ip );
1168 # Step through XFF list and find the last address in the list which is a
1169 # trusted server. Set $ip to the IP address given by that trusted server,
1170 # unless the address is not sensible (e.g. private). However, prefer private
1171 # IP addresses over proxy servers controlled by this site (more sensible).
1172 foreach ( $ipchain as $i => $curIP ) {
1173 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1174 if ( wfIsTrustedProxy( $curIP ) && isset( $ipchain[$i + 1] ) ) {
1175 if ( wfIsConfiguredProxy( $curIP ) || // bug 48919; treat IP as sane
1176 IP::isPublic( $ipchain[$i + 1] ) ||
1177 $wgUsePrivateIPs
1179 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1180 if ( !$nextIP && wfIsConfiguredProxy( $ip ) ) {
1181 // We have not yet made it past CDN/proxy servers of this site,
1182 // so either they are misconfigured or there is some IP spoofing.
1183 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1185 $ip = $nextIP;
1186 continue;
1189 break;
1193 # Allow extensions to improve our guess
1194 wfRunHooks( 'GetIP', array( &$ip ) );
1196 if ( !$ip ) {
1197 throw new MWException( "Unable to determine IP." );
1200 wfDebug( "IP: $ip\n" );
1201 $this->ip = $ip;
1202 return $ip;
1206 * @param string $ip
1207 * @return void
1208 * @since 1.21
1210 public function setIP( $ip ) {
1211 $this->ip = $ip;
1216 * Object to access the $_FILES array
1218 class WebRequestUpload {
1219 protected $request;
1220 protected $doesExist;
1221 protected $fileInfo;
1224 * Constructor. Should only be called by WebRequest
1226 * @param $request WebRequest The associated request
1227 * @param string $key Key in $_FILES array (name of form field)
1229 public function __construct( $request, $key ) {
1230 $this->request = $request;
1231 $this->doesExist = isset( $_FILES[$key] );
1232 if ( $this->doesExist ) {
1233 $this->fileInfo = $_FILES[$key];
1238 * Return whether a file with this name was uploaded.
1240 * @return bool
1242 public function exists() {
1243 return $this->doesExist;
1247 * Return the original filename of the uploaded file
1249 * @return mixed Filename or null if non-existent
1251 public function getName() {
1252 if ( !$this->exists() ) {
1253 return null;
1256 global $wgContLang;
1257 $name = $this->fileInfo['name'];
1259 # Safari sends filenames in HTML-encoded Unicode form D...
1260 # Horrid and evil! Let's try to make some kind of sense of it.
1261 $name = Sanitizer::decodeCharReferences( $name );
1262 $name = $wgContLang->normalize( $name );
1263 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1264 return $name;
1268 * Return the file size of the uploaded file
1270 * @return int File size or zero if non-existent
1272 public function getSize() {
1273 if ( !$this->exists() ) {
1274 return 0;
1277 return $this->fileInfo['size'];
1281 * Return the path to the temporary file
1283 * @return mixed Path or null if non-existent
1285 public function getTempName() {
1286 if ( !$this->exists() ) {
1287 return null;
1290 return $this->fileInfo['tmp_name'];
1294 * Return the upload error. See link for explanation
1295 * http://www.php.net/manual/en/features.file-upload.errors.php
1297 * @return int One of the UPLOAD_ constants, 0 if non-existent
1299 public function getError() {
1300 if ( !$this->exists() ) {
1301 return 0; # UPLOAD_ERR_OK
1304 return $this->fileInfo['error'];
1308 * Returns whether this upload failed because of overflow of a maximum set
1309 * in php.ini
1311 * @return bool
1313 public function isIniSizeOverflow() {
1314 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1315 # PHP indicated that upload_max_filesize is exceeded
1316 return true;
1319 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1320 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1321 # post_max_size is exceeded
1322 return true;
1325 return false;
1330 * WebRequest clone which takes values from a provided array.
1332 * @ingroup HTTP
1334 class FauxRequest extends WebRequest {
1335 private $wasPosted = false;
1336 private $session = array();
1339 * @param array $data of *non*-urlencoded key => value pairs, the
1340 * fake GET/POST values
1341 * @param bool $wasPosted whether to treat the data as POST
1342 * @param $session Mixed: session array or null
1343 * @param string $protocol 'http' or 'https'
1344 * @throws MWException
1346 public function __construct( $data = array(), $wasPosted = false, $session = null, $protocol = 'http' ) {
1347 if ( is_array( $data ) ) {
1348 $this->data = $data;
1349 } else {
1350 throw new MWException( "FauxRequest() got bogus data" );
1352 $this->wasPosted = $wasPosted;
1353 if ( $session ) {
1354 $this->session = $session;
1356 $this->protocol = $protocol;
1360 * @param $method string
1361 * @throws MWException
1363 private function notImplemented( $method ) {
1364 throw new MWException( "{$method}() not implemented" );
1368 * @param $name string
1369 * @param $default string
1370 * @return string
1372 public function getText( $name, $default = '' ) {
1373 # Override; don't recode since we're using internal data
1374 return (string)$this->getVal( $name, $default );
1378 * @return Array
1380 public function getValues() {
1381 return $this->data;
1385 * @return array
1387 public function getQueryValues() {
1388 if ( $this->wasPosted ) {
1389 return array();
1390 } else {
1391 return $this->data;
1395 public function getMethod() {
1396 return $this->wasPosted ? 'POST' : 'GET';
1400 * @return bool
1402 public function wasPosted() {
1403 return $this->wasPosted;
1406 public function getCookie( $key, $prefix = null, $default = null ) {
1407 return $default;
1410 public function checkSessionCookie() {
1411 return false;
1414 public function getRequestURL() {
1415 $this->notImplemented( __METHOD__ );
1418 public function getProtocol() {
1419 return $this->protocol;
1423 * @param string $name The name of the header to get (case insensitive).
1424 * @return bool|string
1426 public function getHeader( $name ) {
1427 $name = strtoupper( $name );
1428 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1432 * @param $name string
1433 * @param $val string
1435 public function setHeader( $name, $val ) {
1436 $name = strtoupper( $name );
1437 $this->headers[$name] = $val;
1441 * @param $key
1442 * @return mixed
1444 public function getSessionData( $key ) {
1445 if ( isset( $this->session[$key] ) ) {
1446 return $this->session[$key];
1448 return null;
1452 * @param $key
1453 * @param $data
1455 public function setSessionData( $key, $data ) {
1456 $this->session[$key] = $data;
1460 * @return array|Mixed|null
1462 public function getSessionArray() {
1463 return $this->session;
1467 * @param array $extWhitelist
1468 * @return bool
1470 public function isPathInfoBad( $extWhitelist = array() ) {
1471 return false;
1475 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1476 * @return String
1478 public function getRawQueryString() {
1479 return '';
1483 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1484 * @return String
1486 public function getRawPostString() {
1487 return '';
1491 * FauxRequests shouldn't depend on raw request data (but that could be implemented here)
1492 * @return String
1494 public function getRawInput() {
1495 return '';
1499 * @param array $extWhitelist
1500 * @return bool
1502 public function checkUrlExtension( $extWhitelist = array() ) {
1503 return true;
1507 * @return string
1509 protected function getRawIP() {
1510 return '127.0.0.1';
1515 * Similar to FauxRequest, but only fakes URL parameters and method
1516 * (POST or GET) and use the base request for the remaining stuff
1517 * (cookies, session and headers).
1519 * @ingroup HTTP
1520 * @since 1.19
1522 class DerivativeRequest extends FauxRequest {
1523 private $base;
1526 * @param WebRequest $base
1527 * @param array $data Array of *non*-urlencoded key => value pairs, the
1528 * fake GET/POST values
1529 * @param bool $wasPosted Whether to treat the data as POST
1531 public function __construct( WebRequest $base, $data, $wasPosted = false ) {
1532 $this->base = $base;
1533 parent::__construct( $data, $wasPosted );
1536 public function getCookie( $key, $prefix = null, $default = null ) {
1537 return $this->base->getCookie( $key, $prefix, $default );
1540 public function checkSessionCookie() {
1541 return $this->base->checkSessionCookie();
1544 public function getHeader( $name ) {
1545 return $this->base->getHeader( $name );
1548 public function getAllHeaders() {
1549 return $this->base->getAllHeaders();
1552 public function getSessionData( $key ) {
1553 return $this->base->getSessionData( $key );
1556 public function setSessionData( $key, $data ) {
1557 $this->base->setSessionData( $key, $data );
1560 public function getAcceptLang() {
1561 return $this->base->getAcceptLang();
1564 public function getIP() {
1565 return $this->base->getIP();
1568 public function getProtocol() {
1569 return $this->base->getProtocol();