3 * Deal with importing all those nasssty globals and things
6 # Copyright (C) 2003 Brion Vibber <brion@pobox.com>
7 # http://www.mediawiki.org/
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License along
20 # with this program; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 # http://www.gnu.org/copyleft/gpl.html
26 * Some entry points may use this file without first enabling the
29 if ( !function_exists( '__autoload' ) ) {
30 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
34 * The WebRequest class encapsulates getting at data passed in the
35 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
36 * stripping illegal input characters and normalizing Unicode sequences.
38 * Usually this is used via a global singleton, $wgRequest. You should
39 * not create a second WebRequest object; make a FauxRequest object if
40 * you want to pass arbitrary data to some function in place of the web
46 protected $data, $headers = array();
49 public function __construct() {
50 /// @todo Fixme: this preemptive de-quoting can interfere with other web libraries
51 /// and increases our memory footprint. It would be cleaner to do on
52 /// demand; but currently we have no wrapper for $_SERVER etc.
53 $this->checkMagicQuotes();
55 // POST overrides GET data
56 // We don't use $_REQUEST here to avoid interference from cookies...
57 $this->data
= $_POST +
$_GET;
61 * Check for title, action, and/or variant data in the URL
62 * and interpolate it into the GET variables.
63 * This should only be run after $wgContLang is available,
64 * as we may need the list of language variants to determine
65 * available variant URLs.
67 public function interpolateTitle() {
68 global $wgUsePathInfo;
69 if ( $wgUsePathInfo ) {
70 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
71 // And also by Apache 2.x, double slashes are converted to single slashes.
72 // So we will use REQUEST_URI if possible.
74 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
75 // Slurp out the path portion to examine...
76 $url = $_SERVER['REQUEST_URI'];
77 if ( !preg_match( '!^https?://!', $url ) ) {
78 $url = 'http://unused' . $url;
80 $a = parse_url( $url );
82 $path = isset( $a['path'] ) ?
$a['path'] : '';
85 if( $path == $wgScript ) {
86 // Script inside a rewrite path?
87 // Abort to keep from breaking...
90 // Raw PATH_INFO style
91 $matches = $this->extractTitle( $path, "$wgScript/$1" );
93 global $wgArticlePath;
94 if( !$matches && $wgArticlePath ) {
95 $matches = $this->extractTitle( $path, $wgArticlePath );
98 global $wgActionPaths;
99 if( !$matches && $wgActionPaths ) {
100 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
103 global $wgVariantArticlePath, $wgContLang;
104 if( !$matches && $wgVariantArticlePath ) {
105 $variantPaths = array();
106 foreach( $wgContLang->getVariants() as $variant ) {
107 $variantPaths[$variant] =
108 str_replace( '$2', $variant, $wgVariantArticlePath );
110 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
113 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
115 // http://bugs.php.net/bug.php?id=31892
116 // Also reported when ini_get('cgi.fix_pathinfo')==false
117 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
119 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
120 // Regular old PATH_INFO yay
121 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
123 foreach( $matches as $key => $val) {
124 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
130 * Internal URL rewriting function; tries to extract page title and,
131 * optionally, one other fixed parameter value from a URL path.
133 * @param $path string: the URL path given from the client
134 * @param $bases array: one or more URLs, optionally with $1 at the end
135 * @param $key string: if provided, the matching key in $bases will be
136 * passed on as the value of this URL parameter
137 * @return array of URL variables to interpolate; empty if no match
139 private function extractTitle( $path, $bases, $key=false ) {
140 foreach( (array)$bases as $keyValue => $base ) {
141 // Find the part after $wgArticlePath
142 $base = str_replace( '$1', '', $base );
143 $baseLen = strlen( $base );
144 if( substr( $path, 0, $baseLen ) == $base ) {
145 $raw = substr( $path, $baseLen );
147 $matches = array( 'title' => rawurldecode( $raw ) );
149 $matches[$key] = $keyValue;
159 * Recursively strips slashes from the given array;
160 * used for undoing the evil that is magic_quotes_gpc.
161 * @param $arr array: will be modified
162 * @return array the original array
164 private function &fix_magic_quotes( &$arr ) {
165 foreach( $arr as $key => $val ) {
166 if( is_array( $val ) ) {
167 $this->fix_magic_quotes( $arr[$key] );
169 $arr[$key] = stripslashes( $val );
176 * If magic_quotes_gpc option is on, run the global arrays
177 * through fix_magic_quotes to strip out the stupid slashes.
178 * WARNING: This should only be done once! Running a second
179 * time could damage the values.
181 private function checkMagicQuotes() {
182 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
183 && get_magic_quotes_gpc();
184 if( $mustFixQuotes ) {
185 $this->fix_magic_quotes( $_COOKIE );
186 $this->fix_magic_quotes( $_ENV );
187 $this->fix_magic_quotes( $_GET );
188 $this->fix_magic_quotes( $_POST );
189 $this->fix_magic_quotes( $_REQUEST );
190 $this->fix_magic_quotes( $_SERVER );
195 * Recursively normalizes UTF-8 strings in the given array.
196 * @param $data string or array
197 * @return cleaned-up version of the given
200 function normalizeUnicode( $data ) {
201 if( is_array( $data ) ) {
202 foreach( $data as $key => $val ) {
203 $data[$key] = $this->normalizeUnicode( $val );
207 $data = $wgContLang->normalize( $data );
213 * Fetch a value from the given array or return $default if it's not set.
216 * @param $name string
217 * @param $default mixed
220 private function getGPCVal( $arr, $name, $default ) {
221 # PHP is so nice to not touch input data, except sometimes:
222 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
223 # Work around PHP *feature* to avoid *bugs* elsewhere.
224 $name = strtr( $name, '.', '_' );
225 if( isset( $arr[$name] ) ) {
228 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
229 # Check for alternate/legacy character encoding.
230 if( isset( $wgContLang ) ) {
231 $data = $wgContLang->checkTitleEncoding( $data );
234 $data = $this->normalizeUnicode( $data );
243 * Fetch a scalar from the input or return $default if it's not set.
244 * Returns a string. Arrays are discarded. Useful for
245 * non-freeform text inputs (e.g. predefined internal text keys
246 * selected by a drop-down menu). For freeform input, see getText().
248 * @param $name string
249 * @param $default string: optional default (or NULL)
252 public function getVal( $name, $default = null ) {
253 $val = $this->getGPCVal( $this->data
, $name, $default );
254 if( is_array( $val ) ) {
257 if( is_null( $val ) ) {
265 * Set an aribtrary value into our get/post data.
266 * @param $key string Key name to use
267 * @param $value mixed Value to set
268 * @return mixed old value if one was present, null otherwise
270 public function setVal( $key, $value ) {
271 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
272 $this->data
[$key] = $value;
277 * Fetch an array from the input or return $default if it's not set.
278 * If source was scalar, will return an array with a single element.
279 * If no source and no default, returns NULL.
281 * @param $name string
282 * @param $default array: optional default (or NULL)
285 public function getArray( $name, $default = null ) {
286 $val = $this->getGPCVal( $this->data
, $name, $default );
287 if( is_null( $val ) ) {
295 * Fetch an array of integers, or return $default if it's not set.
296 * If source was scalar, will return an array with a single element.
297 * If no source and no default, returns NULL.
298 * If an array is returned, contents are guaranteed to be integers.
300 * @param $name string
301 * @param $default array: option default (or NULL)
302 * @return array of ints
304 public function getIntArray( $name, $default = null ) {
305 $val = $this->getArray( $name, $default );
306 if( is_array( $val ) ) {
307 $val = array_map( 'intval', $val );
313 * Fetch an integer value from the input or return $default if not set.
314 * Guaranteed to return an integer; non-numeric input will typically
316 * @param $name string
317 * @param $default int
320 public function getInt( $name, $default = 0 ) {
321 return intval( $this->getVal( $name, $default ) );
325 * Fetch an integer value from the input or return null if empty.
326 * Guaranteed to return an integer or null; non-numeric input will
327 * typically return null.
328 * @param $name string
331 public function getIntOrNull( $name ) {
332 $val = $this->getVal( $name );
333 return is_numeric( $val )
339 * Fetch a boolean value from the input or return $default if not set.
340 * Guaranteed to return true or false, with normal PHP semantics for
341 * boolean interpretation of strings.
342 * @param $name string
343 * @param $default bool
346 public function getBool( $name, $default = false ) {
347 return $this->getVal( $name, $default ) ?
true : false;
351 * Return true if the named value is set in the input, whatever that
352 * value is (even "0"). Return false if the named value is not set.
353 * Example use is checking for the presence of check boxes in forms.
354 * @param $name string
357 public function getCheck( $name ) {
358 # Checkboxes and buttons are only present when clicked
359 # Presence connotes truth, abscense false
360 $val = $this->getVal( $name, null );
361 return isset( $val );
365 * Fetch a text string from the given array or return $default if it's not
366 * set. \r is stripped from the text, and with some language modules there
367 * is an input transliteration applied. This should generally be used for
368 * form <textarea> and <input> fields. Used for user-supplied freeform text
369 * input (for which input transformations may be required - e.g. Esperanto
372 * @param $name string
373 * @param $default string: optional
376 public function getText( $name, $default = '' ) {
378 $val = $this->getVal( $name, $default );
379 return str_replace( "\r\n", "\n",
380 $wgContLang->recodeInput( $val ) );
384 * Extracts the given named values into an array.
385 * If no arguments are given, returns all input values.
386 * No transformation is performed on the values.
388 public function getValues() {
389 $names = func_get_args();
390 if ( count( $names ) == 0 ) {
391 $names = array_keys( $this->data
);
395 foreach ( $names as $name ) {
396 $value = $this->getVal( $name );
397 if ( !is_null( $value ) ) {
398 $retVal[$name] = $value;
405 * Returns true if the present request was reached by a POST operation,
406 * false otherwise (GET, HEAD, or command-line).
408 * Note that values retrieved by the object may come from the
409 * GET URL etc even on a POST request.
413 public function wasPosted() {
414 return $_SERVER['REQUEST_METHOD'] == 'POST';
418 * Returns true if there is a session cookie set.
419 * This does not necessarily mean that the user is logged in!
421 * If you want to check for an open session, use session_id()
422 * instead; that will also tell you if the session was opened
423 * during the current request (in which case the cookie will
424 * be sent back to the client at the end of the script run).
428 public function checkSessionCookie() {
429 return isset( $_COOKIE[session_name()] );
433 * Return the path portion of the request URI.
436 public function getRequestURL() {
437 if( isset( $_SERVER['REQUEST_URI'] ) ) {
438 $base = $_SERVER['REQUEST_URI'];
439 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
440 // Probably IIS; doesn't set REQUEST_URI
441 $base = $_SERVER['SCRIPT_NAME'];
442 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
443 $base .= '?' . $_SERVER['QUERY_STRING'];
446 // This shouldn't happen!
447 throw new MWException( "Web server doesn't provide either " .
448 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
449 "web server configuration to http://bugzilla.wikimedia.org/" );
451 // User-agents should not send a fragment with the URI, but
452 // if they do, and the web server passes it on to us, we
453 // need to strip it or we get false-positive redirect loops
454 // or weird output URLs
455 $hash = strpos( $base, '#' );
456 if( $hash !== false ) {
457 $base = substr( $base, 0, $hash );
459 if( $base{0} == '/' ) {
462 // We may get paths with a host prepended; strip it.
463 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
468 * Return the request URI with the canonical service and hostname.
471 public function getFullRequestURL() {
473 return $wgServer . $this->getRequestURL();
477 * Take an arbitrary query and rewrite the present URL to include it
478 * @param $query String: query string fragment; do not include initial '?'
481 public function appendQuery( $query ) {
484 foreach( $_GET as $var => $val ) {
485 if ( $var == 'title' )
487 if ( is_array( $val ) )
488 /* This will happen given a request like
489 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
492 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
494 $basequery .= '&' . $query;
497 $basequery = substr( $basequery, 1 );
498 return $wgTitle->getLocalURL( $basequery );
502 * HTML-safe version of appendQuery().
503 * @param $query String: query string fragment; do not include initial '?'
506 public function escapeAppendQuery( $query ) {
507 return htmlspecialchars( $this->appendQuery( $query ) );
510 public function appendQueryValue( $key, $value, $onlyquery = false ) {
511 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
515 * Appends or replaces value of query variables.
516 * @param $array Array of values to replace/add to query
517 * @param $onlyquery Bool: whether to only return the query string and not
521 public function appendQueryArray( $array, $onlyquery = false ) {
524 unset( $newquery['title'] );
525 $newquery = array_merge( $newquery, $array );
526 $query = wfArrayToCGI( $newquery );
527 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
531 * Check for limit and offset parameters on the input, and return sensible
532 * defaults if not given. The limit must be positive and is capped at 5000.
533 * Offset must be positive but is not capped.
535 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
536 * @param $optionname String: to specify an option other than rclimit to pull from.
537 * @return array first element is limit, second is offset
539 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
542 $limit = $this->getInt( 'limit', 0 );
543 if( $limit < 0 ) $limit = 0;
544 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
545 $limit = (int)$wgUser->getOption( $optionname );
547 if( $limit <= 0 ) $limit = $deflimit;
548 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
550 $offset = $this->getInt( 'offset', 0 );
551 if( $offset < 0 ) $offset = 0;
553 return array( $limit, $offset );
557 * Return the path to the temporary file where PHP has stored the upload.
558 * @param $key String:
559 * @return string or NULL if no such file.
561 public function getFileTempname( $key ) {
562 if( !isset( $_FILES[$key] ) ) {
565 return $_FILES[$key]['tmp_name'];
569 * Return the size of the upload, or 0.
570 * @param $key String:
573 public function getFileSize( $key ) {
574 if( !isset( $_FILES[$key] ) ) {
577 return $_FILES[$key]['size'];
581 * Return the upload error or 0
582 * @param $key String:
585 public function getUploadError( $key ) {
586 if( !isset( $_FILES[$key] ) ||
!isset( $_FILES[$key]['error'] ) ) {
587 return 0/*UPLOAD_ERR_OK*/;
589 return $_FILES[$key]['error'];
593 * Return the original filename of the uploaded file, as reported by
594 * the submitting user agent. HTML-style character entities are
595 * interpreted and normalized to Unicode normalization form C, in part
596 * to deal with weird input from Safari with non-ASCII filenames.
598 * Other than this the name is not verified for being a safe filename.
600 * @param $key String:
601 * @return string or NULL if no such file.
603 public function getFileName( $key ) {
605 if( !isset( $_FILES[$key] ) ) {
608 $name = $_FILES[$key]['name'];
610 # Safari sends filenames in HTML-encoded Unicode form D...
611 # Horrid and evil! Let's try to make some kind of sense of it.
612 $name = Sanitizer
::decodeCharReferences( $name );
613 $name = $wgContLang->normalize( $name );
614 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
619 * Return a handle to WebResponse style object, for setting cookies,
620 * headers and other stuff, for Request being worked on.
622 public function response() {
623 /* Lazy initialization of response object for this request */
624 if ( !is_object( $this->_response
) ) {
625 $this->_response
= new WebResponse
;
627 return $this->_response
;
631 * Get a request header, or false if it isn't set
632 * @param $name String: case-insensitive header name
634 public function getHeader( $name ) {
635 $name = strtoupper( $name );
636 if ( function_exists( 'apache_request_headers' ) ) {
637 if ( !$this->headers
) {
638 foreach ( apache_request_headers() as $tempName => $tempValue ) {
639 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
642 if ( isset( $this->headers
[$name] ) ) {
643 return $this->headers
[$name];
648 $name = 'HTTP_' . str_replace( '-', '_', $name );
649 if ( isset( $_SERVER[$name] ) ) {
650 return $_SERVER[$name];
658 * Get data from $_SESSION
659 * @param $key String Name of key in $_SESSION
662 public function getSessionData( $key ) {
663 if( !isset( $_SESSION[$key] ) )
665 return $_SESSION[$key];
670 * @param $key String Name of key in $_SESSION
673 public function setSessionData( $key, $data ) {
674 $_SESSION[$key] = $data;
678 * Returns true if the PATH_INFO ends with an extension other than a script
679 * extension. This could confuse IE for scripts that send arbitrary data which
680 * is not HTML but may be detected as such.
682 * Various past attempts to use the URL to make this check have generally
683 * run up against the fact that CGI does not provide a standard method to
684 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
685 * but only by prefixing it with the script name and maybe some other stuff,
686 * the extension is not mangled. So this should be a reasonably portable
687 * way to perform this security check.
689 public function isPathInfoBad() {
690 global $wgScriptExtension;
692 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
695 $pi = $_SERVER['PATH_INFO'];
696 $dotPos = strrpos( $pi, '.' );
697 if ( $dotPos === false ) {
700 $ext = substr( $pi, $dotPos );
701 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
706 * WebRequest clone which takes values from a provided array.
710 class FauxRequest
extends WebRequest
{
711 private $wasPosted = false;
712 private $session = array();
715 * @param $data Array of *non*-urlencoded key => value pairs, the
716 * fake GET/POST values
717 * @param $wasPosted Bool: whether to treat the data as POST
719 public function __construct( $data, $wasPosted = false, $session = null ) {
720 if( is_array( $data ) ) {
723 throw new MWException( "FauxRequest() got bogus data" );
725 $this->wasPosted
= $wasPosted;
727 $this->session
= $session;
730 private function notImplemented( $method ) {
731 throw new MWException( "{$method}() not implemented" );
734 public function getText( $name, $default = '' ) {
735 # Override; don't recode since we're using internal data
736 return (string)$this->getVal( $name, $default );
739 public function getValues() {
743 public function wasPosted() {
744 return $this->wasPosted
;
747 public function checkSessionCookie() {
751 public function getRequestURL() {
752 $this->notImplemented( __METHOD__
);
755 public function appendQuery( $query ) {
756 $this->notImplemented( __METHOD__
);
759 public function getHeader( $name ) {
760 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
763 public function getSessionData( $key ) {
764 if( !isset( $this->session
[$key] ) )
766 return $this->session
[$key];
769 public function setSessionData( $key, $data ) {
770 $this->notImplemented( __METHOD__
);
773 public function isPathInfoBad() {